From ae50e6da2e7a369942f7e72e68c05c6757165c92 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 07:42:03 +1300 Subject: [PATCH 01/16] Prepare exact Account admission source capture and lease evidence --- .../player-access-and-session.md | 8 + ...GameplayPublicAdmissionSourceSnapshot.java | 21 + .../AccountMembershipRoleSourceSnapshot.java | 68 ++ ...ntGameplayPublicAdmissionSourceReader.java | 207 ++++++ .../AccountMembershipRoleSourceReader.java | 288 ++++++++ ...meplayPublicAdmissionSourceReaderTest.java | 571 ++++++++++++++++ ...AccountMembershipRoleSourceReaderTest.java | 640 ++++++++++++++++++ ...AccountGameplayAdmissionLeaseEvidence.java | 434 ++++++++++++ ...untGameplayAdmissionLeaseEvidenceTest.java | 362 ++++++++++ 9 files changed, 2599 insertions(+) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayPublicAdmissionSourceSnapshot.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipRoleSourceSnapshot.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipRoleSourceReader.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipRoleSourceReaderTest.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 07000d51ce..9f4d072d59 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,14 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Account Admission-Lease Prerequisite + +The isolated Account candidate adds an unregistered same-transaction source reader for fresh Game Design tenant provenance and the existing `NON_PAID_DEMO` entitlement class. It captures the actual issuer/Account/tenant/membership sources, exact membership event and role snapshot, current entitlement and its separate billing receipt, and the exact SQL token-identity fence. Active player membership, entitlement admission flags, provenance, issuance fence and receipt/checkpoint consistency are checked through the existing owner repositories; missing, changed or unsupported evidence is denied. Unit fixtures use doubles of those repositories and do not establish PostgreSQL lock or race behavior. + +The shared admission-lease evidence value preserves the complete unchanged baseline, public-target tuple, ordered authority checkpoints, exact token metadata, caller workload, binding identity, absolute expiry and applicable resume/prior-generation fields. It is a bounded canonical shape/digest codec, not authenticated Account evidence or a lease issuer. Its tuple and baseline validation currently inherits the existing public-delegation validator's signed-long source range; unsupported values are denied rather than substituted. Billing cutoff evidence refers to the tenant authority stream; the demo entitlement's separate availability receipt is not invented as another authority checkpoint. + +This prerequisite does not supply protected acquire/finalize/abort/reconcile RPCs, durable admission-lease allocation or `COMMITTED` evidence, authenticated lifecycle/target or token-registry verification, pending-invalidation enforcement, orphan cleanup, private-grant or paid-entitlement support, or executed PostgreSQL/fresh-image LOGIN → PLAY → LOOK proof. Construction of either source capture or carrier grants no admission, and the runtime path remains denied. The owning target contract is [Session Behavior](../../architecture/system-architecture-session-behavior.md), with Account's predicate and caller obligations in [Authentication](../../architecture/system-architecture-authentication.md). The consolidated source/codec gate passes Common Security and Account checks, integration-source compilation, formatting, static analysis, links and Markdown lint: 147 Common Security tests and 1,049 Account unit tests executed without failures; three Account unit tests skipped. Two non-database integration cases executed, while 124 integration cases skipped. These counts do not establish PostgreSQL locks, migration execution or lease finalization. + ### Credential-Bound Account LOGIN Owner The LOGIN prerequisite supplies the explicit Account owner for credential verification and immutable keyed request preparation, followed by the existing signer, pending registry, current authority projection, SQL commit, active readback and encrypted response-recovery owners. Exact retries bind the original Account identity, normalized email, authenticated workload, still-open pre-auth source context and transient credential presentation through a retained Account HMAC key; no raw credential or reusable unkeyed hash becomes operation evidence. V81 preserves historical unbound operations unchanged and non-authorizing while requiring immutable credential binding for new operations. Invalid credential denials commit their OTP-attempt evidence without creating an issuance; other authentication failures roll back. Canonical authentication and token authority remain in [Authentication](../../architecture/system-architecture-authentication.md) and [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayPublicAdmissionSourceSnapshot.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayPublicAdmissionSourceSnapshot.java new file mode 100644 index 0000000000..49ff41f2cd --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayPublicAdmissionSourceSnapshot.java @@ -0,0 +1,21 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; + +/** + * Immutable Account SQL sources captured for public fresh-admission owner work. + * + *

The values are valid only within the transaction that captured them. The token fence is + * persisted SQL state; it does not establish caller authentication, token cryptographic validity, + * registry state, or gameplay admission by itself. + */ +public record AccountGameplayPublicAdmissionSourceSnapshot( + AccountMembershipRoleSourceSnapshot membershipSource, + DemoTenantEntitlementSnapshot entitlementSource, + AccountGameplayTokenIdentityFence tokenIdentityFence) { + public AccountGameplayPublicAdmissionSourceSnapshot { + Objects.requireNonNull(membershipSource, "Current membership source is required"); + Objects.requireNonNull(entitlementSource, "Current demo entitlement source is required"); + Objects.requireNonNull(tokenIdentityFence, "Current SQL token fence is required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipRoleSourceSnapshot.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipRoleSourceSnapshot.java new file mode 100644 index 0000000000..9c5e49256e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipRoleSourceSnapshot.java @@ -0,0 +1,68 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; + +/** + * Immutable Account SQL source capture, including historical membership event and current owners. + * + *

This is not authentication, authorization, signed recipient evidence, an ACTIVE proof, a + * mutation, or positive no-applicable-deadline evidence. In particular, INACTIVE and invalidated + * history may be captured without authorizing admission. Its validity is limited to the enclosing + * owner transaction; later mutation must revalidate the exact sources under its own owner locks. + */ +public record AccountMembershipRoleSourceSnapshot( + IssuerAccountSourceSnapshot issuerAccountSources, + CompositeSnapshot currentAuthority, + TenantAuthorityEventV1Codec.Event tenantSource, + PairAuthority pair, + MembershipSource membership, + RoleSnapshot roles, + Checkpoint membershipCheckpoint, + Event storedMembershipEvent, + MembershipEvent membershipEvent) { + public AccountMembershipRoleSourceSnapshot { + Objects.requireNonNull(issuerAccountSources); + Objects.requireNonNull(currentAuthority); + Objects.requireNonNull(tenantSource); + Objects.requireNonNull(pair); + Objects.requireNonNull(membership); + Objects.requireNonNull(roles); + Objects.requireNonNull(membershipCheckpoint); + Objects.requireNonNull(storedMembershipEvent); + Objects.requireNonNull(membershipEvent); + } + + /** Copies every membership identity/state field instead of retaining a mutable storage entity. */ + public record MembershipSource( + long membershipId, + long accountRowId, + UUID accountId, + AccountIdentityProvenance accountIdentityProvenance, + long accountSourceNumericId, + UUID tenantId, + VerifiedTenantProvenance tenantProvenance, + String lifecycleState, + boolean gameplayAdmissionAllowed, + long membershipVersion, + long membershipAuthorityGeneration, + String authorityProvenance) { + public MembershipSource { + Objects.requireNonNull(accountId); + Objects.requireNonNull(accountIdentityProvenance); + Objects.requireNonNull(tenantId); + Objects.requireNonNull(tenantProvenance); + Objects.requireNonNull(lifecycleState); + Objects.requireNonNull(authorityProvenance); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java new file mode 100644 index 0000000000..821d30418a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java @@ -0,0 +1,207 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayPublicAdmissionSourceSnapshot; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.dto.AccountMembershipRoleSourceSnapshot; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, read-only-in-purpose SQL source composition for public fresh NON_PAID_DEMO work. + * + *

The caller must already own a writable Account transaction at REPEATABLE_READ or SERIALIZABLE + * isolation. The membership reader supplies the first Account lock. This reader does not create a + * transaction, write state, authenticate a caller or token, validate a signature or token registry, + * establish World ACTIVE/lifecycle, routing, coordination, grant, or deadline evidence, decide + * admission, or issue or commit an admission lease. Current SQL token-fence state is only one + * captured source and is not complete token authority. + */ +public final class AccountGameplayPublicAdmissionSourceReader { + private final AccountMembershipRoleSourceReader membershipSources; + private final AccountDemoTenantEntitlementRepository entitlements; + private final AccountGameplayTokenIdentityFenceRepository tokenFences; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Account owner sources are private transaction collaborators.") + public AccountGameplayPublicAdmissionSourceReader( + AccountMembershipRoleSourceReader membershipSources, + AccountDemoTenantEntitlementRepository entitlements, + AccountGameplayTokenIdentityFenceRepository tokenFences) { + this.membershipSources = Objects.requireNonNull(membershipSources); + this.entitlements = Objects.requireNonNull(entitlements); + this.tokenFences = Objects.requireNonNull(tokenFences); + } + + /** Captures exact Account owner sources under the caller's existing serialized transaction. */ + public AccountGameplayPublicAdmissionSourceSnapshot readCurrent( + UUID accountId, UUID tenantId, TokenIdentity identity) { + requireUuid(accountId, "account"); + requireUuid(tenantId, "tenant"); + Objects.requireNonNull(identity, "Exact committed token identity is required"); + if (!accountId.equals(identity.accountId())) { + throw new IllegalArgumentException("Token identity account differs from the exact account"); + } + requireWritableOwnerTransaction(); + + // This owner read establishes the Account-first lock order and the membership snapshot. + AccountMembershipRoleSourceSnapshot membership = + membershipSources.readCurrent(accountId, tenantId); + requireMembership(membership, accountId, tenantId, identity); + + DemoTenantEntitlementSnapshot evaluated = entitlements.readCurrent(tenantId); + require(evaluated != null, "Current demo entitlement source is unavailable"); + DemoTenantEntitlementSnapshot current = entitlements.revalidate(evaluated); + require( + current != null && current.equals(evaluated), + "Revalidated demo entitlement source is unavailable or changed"); + requireEntitlement(membership, current, tenantId); + + AccountGameplayTokenIdentityFence tokenFence = tokenFences.requireActiveForUpdate(identity); + require( + tokenFence != null + && identity.equals(tokenFence.identity()) + && tokenFence.state() == State.ACTIVE, + "Exact Account SQL token identity is not active"); + + return new AccountGameplayPublicAdmissionSourceSnapshot(membership, current, tokenFence); + } + + private static void requireMembership( + AccountMembershipRoleSourceSnapshot snapshot, + UUID accountId, + UUID tenantId, + TokenIdentity identity) { + require(snapshot != null, "Current membership source is unavailable"); + var member = snapshot.membership(); + require( + accountId.equals(member.accountId()) + && tenantId.equals(member.tenantId()) + && "ACTIVE".equals(member.lifecycleState()) + && member.gameplayAdmissionAllowed(), + "Current Account membership does not allow gameplay admission"); + require( + snapshot.roles().roles().contains("player") + && snapshot.roles().accountUuid() != null + && accountId.equals(snapshot.roles().accountUuid()) + && tenantId.equals(snapshot.roles().tenantUuid()) + && snapshot.roles().membershipId() == member.membershipId() + && snapshot.roles().snapshotVersion() == member.membershipVersion(), + "Current Account membership has no exact player role source"); + require( + accountId.equals(snapshot.issuerAccountSources().issuanceFence().accountId()) + && snapshot + .currentAuthority() + .issuanceFence() + .equals(snapshot.issuerAccountSources().issuanceFence()) + && snapshot.issuerAccountSources().issuanceFence().value() == identity.issuanceFence(), + "Current Account issuance fence differs from the exact token identity"); + require( + tenantId.equals(snapshot.tenantSource().tenantId()) + && tenantId.equals(snapshot.pair().tenantUuid()) + && accountId.equals(snapshot.pair().accountUuid()) + && snapshot.pair().provenance().equals(member.tenantProvenance()) + && snapshot.pair().provenance().equals(snapshot.roles().tenantProvenance()) + && tenantId.toString().equals(snapshot.membershipEvent().tenantId()) + && accountId.toString().equals(snapshot.membershipEvent().accountId()) + && snapshot.currentAuthority().tenants().size() == 1 + && snapshot.currentAuthority().memberships().size() == 1, + "Current Account membership source scope is inconsistent"); + var checkpoint = snapshot.membershipCheckpoint(); + var storedEvent = snapshot.storedMembershipEvent(); + var sourceEvent = snapshot.membershipEvent(); + require( + checkpoint.outboxStreamKey().equals(storedEvent.outboxStreamKey()) + && checkpoint.outboxSequence() == storedEvent.outboxSequence() + && checkpoint.sourceEventId().equals(storedEvent.eventId()) + && checkpoint.sourceEventDigest().equals(storedEvent.eventDigest()) + && snapshot.pair().eventSequence() == checkpoint.outboxSequence() + && snapshot.pair().eventId().equals(checkpoint.sourceEventId()) + && snapshot.pair().eventDigest().equals(checkpoint.sourceEventDigest()) + && sourceEvent.eventId().equals(storedEvent.eventId()) + && sourceEvent.eventDigest().equals(storedEvent.eventDigest()) + && sourceEvent.roles().equals(snapshot.roles().roles()) + && sourceEvent.membershipLifecycleState().equals(member.lifecycleState()) + && sourceEvent.gameplayAdmissionAllowed() == member.gameplayAdmissionAllowed(), + "Current Account membership event and checkpoint do not match the role snapshot"); + } + + private static void requireEntitlement( + AccountMembershipRoleSourceSnapshot membership, + DemoTenantEntitlementSnapshot entitlement, + UUID tenantId) { + var tenant = membership.tenantSource(); + var currentTenantAuthority = + membership.currentAuthority().tenants().stream() + .filter(state -> AuthorityScope.tenant(tenantId).equals(state.scope())) + .findFirst() + .orElse(null); + require( + currentTenantAuthority != null + && tenantId.equals(entitlement.canonicalTenantId()) + && "NEW_GAME_ROW".equals(entitlement.sourceEvidence().provenanceKind()) + && entitlement.sourceEvidence().equals(tenant.sourceEvidence()) + && membership.pair().provenance().kind() == TenantProvenanceKind.FRESH_GAME_DESIGN + && entitlement + .sourceEvidence() + .operationId() + .equals(membership.pair().provenance().sourceOperationId()) + && entitlement + .sourceEvidence() + .evidenceDigest() + .equals(membership.pair().provenance().digest()) + && entitlement.tenantAuthorityGeneration() == tenant.tenantAuthorityGeneration() + && entitlement.tenantAuthoritySourceVersion() == tenant.tenantAuthoritySourceVersion() + && currentTenantAuthority.generation() == tenant.tenantAuthorityGeneration() + && currentTenantAuthority.sourceVersion() == tenant.tenantAuthoritySourceVersion() + && entitlement.gameplayAvailable() + && entitlement.allowNewGameplayBindings(), + "Current public demo entitlement or fresh Game Design source is unavailable or denied"); + + require( + entitlement.tenantAuthorityOutboxStreamKey().equals(tenant.outboxStreamKey()) + && entitlement.tenantAuthorityOutboxSequence() == tenant.outboxSequence() + && entitlement.tenantAuthorityEventId().equals(tenant.eventId()) + && entitlement.tenantAuthorityEventDigest().equals(tenant.eventDigest()), + "Current demo entitlement differs from the tenant authority event checkpoint"); + require( + entitlement.outboxStreamKey().equals(tenant.tenantBillingStreamKey()) + && entitlement.tenantBillingSequence() == tenant.tenantBillingSequence() + && entitlement.eventId().equals(tenant.tenantBillingEventId()) + && entitlement.eventDigest().equals(tenant.tenantBillingEventDigest()), + "Current demo entitlement differs from the exact tenant billing receipt"); + } + + private static void requireWritableOwnerTransaction() { + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + require( + TransactionSynchronizationManager.isActualTransactionActive() + && !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + && (Objects.equals(isolation, TransactionDefinition.ISOLATION_REPEATABLE_READ) + || Objects.equals(isolation, TransactionDefinition.ISOLATION_SERIALIZABLE)), + "Writable Account REPEATABLE_READ or SERIALIZABLE transaction required"); + } + + private static void requireUuid(UUID value, String label) { + if (value == null + || value.equals(new UUID(0L, 0L)) + || value.version() != 4 + || value.variant() != 2) { + throw new IllegalArgumentException("Canonical non-nil v4 " + label + " UUID required"); + } + } + + private static void require(boolean valid, String message) { + if (!valid) throw new IllegalStateException(message); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipRoleSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipRoleSourceReader.java new file mode 100644 index 0000000000..4c71f255c6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipRoleSourceReader.java @@ -0,0 +1,288 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountMembershipRoleSourceSnapshot; +import net.firedevops.firemud.accountservice.dto.AccountMembershipRoleSourceSnapshot.MembershipSource; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, read-only-in-purpose current membership/role SQL source capture. + * + *

Requires a writable Account transaction for owner locks, with REPEATABLE_READ or SERIALIZABLE + * isolation. No transaction, network call, enrollment, mutation, actor authority, deadline evidence + * or admission decision is created here. Actual owner APIs currently support FRESH_GAME_DESIGN + * tenant provenance only; approved retained tenant mappings cannot be inferred through this reader. + * Applicable later owner decisions can consume this capture; it supplies no reduction intent. + */ +public final class AccountMembershipRoleSourceReader { + private final AccountAuthoritySourceEvidenceRepository sources; + private final AccountAuthorityGenerationRepository generations; + private final AccountTenantMembershipRepository memberships; + private final AccountMembershipPairAuthorityRepository pairs; + private final AccountTenantMembershipRoleSnapshotRepository roles; + private final AccountAuthorityOutboxRepository outbox; + private final AccountTenantAuthorityEventRepository tenants; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Account owner repositories are private transaction collaborators.") + public AccountMembershipRoleSourceReader( + AccountAuthoritySourceEvidenceRepository sources, + AccountAuthorityGenerationRepository generations, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository pairs, + AccountTenantMembershipRoleSnapshotRepository roles, + AccountAuthorityOutboxRepository outbox, + AccountTenantAuthorityEventRepository tenants) { + this.sources = Objects.requireNonNull(sources); + this.generations = Objects.requireNonNull(generations); + this.memberships = Objects.requireNonNull(memberships); + this.pairs = Objects.requireNonNull(pairs); + this.roles = Objects.requireNonNull(roles); + this.outbox = Objects.requireNonNull(outbox); + this.tenants = Objects.requireNonNull(tenants); + } + + public AccountMembershipRoleSourceSnapshot readCurrent(UUID accountId, UUID tenantId) { + requireUuid(accountId); + requireUuid(tenantId); + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + require( + TransactionSynchronizationManager.isActualTransactionActive() + && !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + && (Objects.equals(isolation, TransactionDefinition.ISOLATION_REPEATABLE_READ) + || Objects.equals(isolation, TransactionDefinition.ISOLATION_SERIALIZABLE))); + + // Both owner source/composite APIs lock Account first, before authority, tenant or pair rows. + var source = + sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId); + var authority = + generations.readCompositeSnapshot( + GameSessionAccountDelegationProfile.ISSUER, + accountId, + List.of(tenantId), + List.of(tenantId)); + require(source != null && authority != null); + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source); + require(authority.tenants().size() == 1 && authority.memberships().size() == 1); + var tenantState = authority.tenants().getFirst(); + var memberState = authority.memberships().getFirst(); + require( + AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER) + .equals(source.issuer().scope()) + && AuthorityScope.account(accountId).equals(source.account().scope()) + && source.issuer().scope().equals(authority.issuer().scope()) + && source.account().scope().equals(authority.account().scope()) + && AuthorityScope.tenant(tenantId).equals(tenantState.scope()) + && AuthorityScope.membership(accountId, tenantId).equals(memberState.scope()) + && source.issuer().generation() == authority.issuer().generation() + && source.issuer().sourceVersion() == authority.issuer().sourceVersion() + && source.account().generation() == authority.account().generation() + && source.account().sourceVersion() == authority.account().sourceVersion() + && source.issuanceFence().equals(authority.issuanceFence()) + && accountId.equals(authority.issuanceFence().accountId()) + && authority.issuanceFence().equals(authority.account().issuanceFence()) + && authority.issuanceFence().equals(memberState.issuanceFence()) + && authority.issuer().issuanceFence() == null + && tenantState.issuanceFence() == null); + var tenant = tenants.readCurrentByTenant(tenantId); + require(tenant != null); + require( + tenantId.equals(tenant.tenantId()) + && tenantId.equals(tenant.sourceEvidence().canonicalTenantId()) + && tenant.tenantAuthorityGeneration() == tenantState.generation() + && tenant.tenantAuthoritySourceVersion() == tenantState.sourceVersion()); + var member = + memberships + .findFreshMembershipForUpdate(accountId, tenantId) + .orElseThrow(AccountMembershipRoleSourceReader::unavailable); + var pair = + pairs + .readForUpdate(accountId, tenantId) + .orElseThrow(AccountMembershipRoleSourceReader::unavailable); + var provenance = pair.provenance(); + var account = member.getAccount(); + if (account == null) { + throw unavailable(); + } + require( + account.getId() != null + && account.getId() > 0L + && member.getId() != null + && member.getId() > 0L); + require( + accountId.equals(pair.accountUuid()) + && tenantId.equals(pair.tenantUuid()) + && pair.membershipExists() + && pair.eventSequence() > 0L + && provenance.kind() == TenantProvenanceKind.FRESH_GAME_DESIGN + && provenance.legacyTenantId() == null + && member.getTenantId() == null + && provenance.kind().name().equals(member.getTenantProvenanceKind()) + && provenance.sourceOperationId().equals(tenant.sourceEvidence().operationId()) + && provenance.digest().equals(tenant.sourceEvidence().evidenceDigest()) + && provenance.sourceOperationId().equals(member.getTenantSourceOperationId()) + && provenance.digest().equals(member.getTenantProvenanceDigest()) + && accountId.equals(account.getAccountUuid()) + && tenantId.equals(member.getTenantUuid()) + && AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.equals( + account.getAccountUuidProvenance()) + && account.getId().equals(account.getAccountUuidSourceNumericId()) + && account.getId().equals(source.account().accountSourceNumericId()) + && member.getMembershipVersion() == pair.membershipVersion() + && member.getMembershipAuthorityGeneration() == pair.membershipAuthorityGeneration() + && memberState.generation() == pair.membershipAuthorityGeneration() + && member.getAuthorityProvenance() != null + && !member.getAuthorityProvenance().isBlank()); + var role = + roles + .findForCanonicalUpdate( + accountId, tenantId, provenance, member.getId(), member.getMembershipVersion()) + .orElseThrow(AccountMembershipRoleSourceReader::unavailable); + require( + role.accountId() == account.getId() + && Objects.equals(role.tenantId(), member.getTenantId()) + && role.membershipId() == member.getId() + && role.snapshotVersion() == member.getMembershipVersion() + && accountId.equals(role.accountUuid()) + && tenantId.equals(role.tenantUuid()) + && provenance.equals(role.tenantProvenance())); + String stream = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountId + + "/" + + tenantId; + var checkpoint = + outbox.readCheckpoint(stream).orElseThrow(AccountMembershipRoleSourceReader::unavailable); + var event = + outbox + .findEvent(stream, checkpoint.outboxSequence()) + .orElseThrow(AccountMembershipRoleSourceReader::unavailable); + var verified = + MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8)); + require( + stream.equals(checkpoint.outboxStreamKey()) + && stream.equals(event.outboxStreamKey()) + && stream.equals(verified.outboxStreamKey()) + && ("membership/" + accountId + "/" + tenantId).equals(verified.sourceScope()) + && checkpoint.outboxSequence() == pair.eventSequence() + && event.outboxSequence() == pair.eventSequence() + && Long.toString(pair.eventSequence()).equals(verified.outboxSequence()) + && pair.eventId().equals(checkpoint.sourceEventId()) + && pair.eventId().equals(event.eventId()) + && pair.eventId().equals(verified.eventId()) + && pair.eventDigest().equals(checkpoint.sourceEventDigest()) + && pair.eventDigest().equals(event.eventDigest()) + && pair.eventDigest().equals(verified.eventDigest()) + && event.requestId().equals(verified.requestId()) + && Arrays.equals(event.payload(), verified.canonicalJsonUtf8()) + && accountId.toString().equals(verified.accountId()) + && tenantId.toString().equals(verified.tenantId()) + && Map.of(tenantId.toString(), Long.toString(pair.membershipVersion())) + .equals(verified.membershipVersion()) + && Long.toString(pair.membershipAuthorityGeneration()) + .equals(verified.membershipAuthorityGeneration()) + && Objects.equals(member.getLifecycleState(), verified.membershipLifecycleState()) + && member.isGameplayAdmissionAllowed() == verified.gameplayAdmissionAllowed() + && pair.lastTransitionInvalidated() == verified.callerBoundAuthorityInvalidated() + && role.roles().equals(verified.roles())); + // Historical event bytes remain unchanged when independent current sources advance. + var tuple = verified.authorityTuple(); + require( + tuple + .membershipAuthorityGeneration() + .equals(Map.of(tenantId.toString(), Long.toString(memberState.generation()))) + && tuple + .tenantAuthorityGeneration() + .keySet() + .equals(java.util.Set.of(tenantId.toString()))); + requireNotFuture(tuple.issuerAuthGeneration(), authority.issuer().generation()); + requireNotFuture(tuple.accountAuthorityGeneration(), authority.account().generation()); + requireNotFuture( + tuple.tenantAuthorityGeneration().get(tenantId.toString()), tenantState.generation()); + requireNotFuture(verified.issuanceFence(), authority.issuanceFence().value()); + // No private-grant source owner is included in this bounded reader. + require(tuple.privateRealmGrantVersions().isEmpty()); + tuple + .accountSecurityCutoff() + .ifPresent( + cutoff -> { + requireNotFuture(cutoff.accountAuthorityGeneration(), source.account().generation()); + requireNotFuture(cutoff.outboxSequence(), source.account().checkpoint().sequence()); + }); + tuple + .tenantBillingCutoff() + .ifPresent( + cutoffs -> { + require(cutoffs.keySet().equals(java.util.Set.of(tenantId.toString()))); + var cutoff = cutoffs.get(tenantId.toString()); + requireNotFuture(cutoff.tenantAuthorityGeneration(), tenantState.generation()); + requireNotFuture(cutoff.tenantBillingSequence(), tenant.tenantBillingSequence()); + requireNotFuture(cutoff.outboxSequence(), tenant.outboxSequence()); + }); + return new AccountMembershipRoleSourceSnapshot( + source, + authority, + tenant, + pair, + new MembershipSource( + member.getId(), + account.getId(), + accountId, + account.getAccountUuidProvenance(), + account.getAccountUuidSourceNumericId(), + tenantId, + provenance, + member.getLifecycleState(), + member.isGameplayAdmissionAllowed(), + member.getMembershipVersion(), + member.getMembershipAuthorityGeneration(), + member.getAuthorityProvenance()), + role, + checkpoint, + event, + verified); + } + + private static void requireNotFuture(String historical, long current) { + require(new BigInteger(historical).compareTo(BigInteger.valueOf(current)) <= 0); + } + + private static void requireUuid(UUID id) { + if (id == null || id.equals(new UUID(0L, 0L)) || id.version() != 4 || id.variant() != 2) { + throw new IllegalArgumentException("Canonical non-nil v4 UUID selector is required"); + } + } + + private static void require(boolean valid) { + if (!valid) throw unavailable(); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Current Account membership/role SQL source is unavailable or inconsistent"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java new file mode 100644 index 0000000000..f31b0d6f1e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java @@ -0,0 +1,571 @@ +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.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.function.UnaryOperator; +import net.firedevops.firemud.accountservice.dto.AccountGameplayPublicAdmissionSourceSnapshot; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.dto.AccountMembershipRoleSourceSnapshot; +import net.firedevops.firemud.accountservice.dto.AccountMembershipRoleSourceSnapshot.MembershipSource; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.service.AccountGameplayPublicAdmissionSourceReader; +import net.firedevops.firemud.accountservice.service.AccountMembershipRoleSourceReader; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedGameplayAuthorityProjectionTest; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner API doubles prove exact composition and guards, not SQL or token authentication. */ +class AccountGameplayPublicAdmissionSourceReaderTest { + private static final UUID ACCOUNT = AccountSelectedGameplayAuthorityProjectionTest.ACCOUNT; + private static final UUID TENANT = AccountSelectedGameplayAuthorityProjectionTest.TENANT; + + @BeforeEach + void transaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_REPEATABLE_READ); + } + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void composesExactExistingOwnerReadsInAccountFirstOrder() { + Fixture fixture = new Fixture(); + + AccountGameplayPublicAdmissionSourceSnapshot result = fixture.read(); + + assertThat(result.membershipSource()).isSameAs(fixture.membership); + assertThat(result.entitlementSource()).isEqualTo(fixture.entitlement); + assertThat(result.tokenIdentityFence()).isEqualTo(fixture.activeFence); + var ordered = inOrder(fixture.memberships, fixture.entitlements, fixture.tokenFences); + ordered.verify(fixture.memberships).readCurrent(ACCOUNT, TENANT); + ordered.verify(fixture.entitlements).readCurrent(TENANT); + ordered.verify(fixture.entitlements).revalidate(fixture.entitlement); + ordered.verify(fixture.tokenFences).requireActiveForUpdate(fixture.identity); + verifyNoMoreInteractions(fixture.memberships, fixture.entitlements, fixture.tokenFences); + } + + @Test + void changedTenantBillingCheckpointFenceScopeVersionLifecycleRolesAndFlagsDeny() { + List> changes = + List.of( + f -> + f.replaceEntitlement( + entitlement( + AccountSelectedGameplayAuthorityProjectionTest.tenant(UUID.randomUUID()))), + f -> f.updateEntitlement(fields -> fields.tenantBillingSequence++), + f -> f.updateEntitlement(fields -> fields.tenantAuthorityOutboxSequence++), + f -> f.identityWithIssuanceFence(2L), + f -> + f.replaceMembership( + member -> copyMember(member, UUID.randomUUID(), TENANT, null, null)), + f -> f.updateEntitlement(fields -> fields.tenantAuthorityGeneration++), + f -> + f.replaceMembership( + member -> copyMember(member, ACCOUNT, TENANT, "INACTIVE", null)), + f -> + f.replaceMembership( + member -> copyMember(member, ACCOUNT, TENANT, null, List.of("tenantAdmin"))), + f -> + f.replaceMembership( + member -> copyMember(member, ACCOUNT, TENANT, null, null, false)), + f -> f.updateEntitlement(fields -> fields.gameplayAvailable = false), + f -> f.updateEntitlement(fields -> fields.allowNewGameplayBindings = false)); + + for (Consumer change : changes) { + Fixture fixture = new Fixture(); + change.accept(fixture); + assertDenied(fixture); + } + } + + @Test + void changedExactTenantSourceAndBillingReceiptIdentitiesDeny() { + for (Consumer change : + List.>of( + fields -> fields.sourceEvidence = differentSourceEvidence(), + fields -> fields.tenantAuthoritySourceVersion++, + fields -> fields.tenantAuthorityEventId = UUID.randomUUID(), + fields -> fields.tenantAuthorityEventDigest = "sha256:" + "0".repeat(64), + fields -> fields.eventId = UUID.randomUUID(), + fields -> { + fields.eventDigest = "sha256:" + "0".repeat(64); + fields.snapshotIdentity = fields.eventDigest; + })) { + Fixture fixture = new Fixture(); + fixture.updateEntitlement(change); + assertDenied(fixture); + } + } + + @Test + void missingOrNullOwnerEvidenceFailsClosed() { + Fixture missingMembership = new Fixture(); + when(missingMembership.memberships.readCurrent(ACCOUNT, TENANT)).thenReturn(null); + assertDenied(missingMembership); + verifyNoInteractions(missingMembership.entitlements, missingMembership.tokenFences); + + Fixture missingEntitlement = new Fixture(); + when(missingEntitlement.entitlements.readCurrent(TENANT)).thenReturn(null); + assertDenied(missingEntitlement); + verifyNoInteractions(missingEntitlement.tokenFences); + + Fixture missingRevalidation = new Fixture(); + when(missingRevalidation.entitlements.revalidate(missingRevalidation.entitlement)) + .thenReturn(null); + assertDenied(missingRevalidation); + verifyNoInteractions(missingRevalidation.tokenFences); + + Fixture missingFence = new Fixture(); + when(missingFence.tokenFences.requireActiveForUpdate(missingFence.identity)).thenReturn(null); + assertDenied(missingFence); + } + + @Test + void inactiveSqlFenceAndChangedRevalidatedSnapshotDeny() { + Fixture inactive = new Fixture(); + when(inactive.tokenFences.requireActiveForUpdate(inactive.identity)) + .thenReturn( + new AccountGameplayTokenIdentityFence( + inactive.identity, 2L, State.PENDING, UUID.randomUUID(), "0".repeat(64))); + assertDenied(inactive); + + Fixture changedDuringRevalidation = new Fixture(); + EntitlementFields changedFields = new EntitlementFields(changedDuringRevalidation.entitlement); + changedFields.entitlementVersion++; + DemoTenantEntitlementSnapshot changed = changedFields.build(); + when(changedDuringRevalidation.entitlements.revalidate(changedDuringRevalidation.entitlement)) + .thenReturn(changed); + assertDenied(changedDuringRevalidation); + verifyNoInteractions(changedDuringRevalidation.tokenFences); + } + + @Test + void transactionAndIsolationGuardRunsBeforeAnyOwnerRead() { + for (Consumer invalidTransaction : + List.>of( + f -> TransactionSynchronizationManager.setActualTransactionActive(false), + f -> TransactionSynchronizationManager.setCurrentTransactionReadOnly(true), + f -> + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_READ_COMMITTED))) { + Fixture fixture = new Fixture(); + invalidTransaction.accept(fixture); + assertDenied(fixture); + verifyNoInteractions(fixture.memberships, fixture.entitlements, fixture.tokenFences); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_REPEATABLE_READ); + } + } + + @Test + void onlyExactCanonicalAccountAndTenantSelectorsAreAccepted() { + Fixture fixture = new Fixture(); + assertThatThrownBy( + () -> fixture.reader.readCurrent(UUID.randomUUID(), TENANT, fixture.identity)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(fixture.memberships, fixture.entitlements, fixture.tokenFences); + } + + @Test + void acceptsSerializableOwnerTransaction() { + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_SERIALIZABLE); + + assertThat(new Fixture().read()).isNotNull(); + } + + private static void assertDenied(Fixture fixture) { + assertThatThrownBy(fixture::read).isInstanceOf(RuntimeException.class); + } + + private static AccountMembershipRoleSourceSnapshot copyMember( + AccountMembershipRoleSourceSnapshot source, + UUID accountId, + UUID tenantId, + String lifecycle, + List roleIdentifiers) { + return copyMember(source, accountId, tenantId, lifecycle, roleIdentifiers, null); + } + + private static AccountMembershipRoleSourceSnapshot copyMember( + AccountMembershipRoleSourceSnapshot source, + UUID accountId, + UUID tenantId, + String lifecycle, + List roleIdentifiers, + Boolean gameplayAllowed) { + MembershipSource old = source.membership(); + MembershipSource member = + new MembershipSource( + old.membershipId(), + old.accountRowId(), + accountId, + old.accountIdentityProvenance(), + old.accountSourceNumericId(), + tenantId, + old.tenantProvenance(), + lifecycle == null ? old.lifecycleState() : lifecycle, + gameplayAllowed == null ? old.gameplayAdmissionAllowed() : gameplayAllowed, + old.membershipVersion(), + old.membershipAuthorityGeneration(), + old.authorityProvenance()); + RoleSnapshot oldRoles = source.roles(); + RoleSnapshot roles = + roleIdentifiers == null + ? oldRoles + : new RoleSnapshot( + oldRoles.accountId(), + oldRoles.tenantId(), + oldRoles.membershipId(), + oldRoles.snapshotVersion(), + roleIdentifiers, + oldRoles.accountUuid(), + oldRoles.tenantUuid(), + oldRoles.tenantProvenance()); + return new AccountMembershipRoleSourceSnapshot( + source.issuerAccountSources(), + source.currentAuthority(), + source.tenantSource(), + source.pair(), + member, + roles, + source.membershipCheckpoint(), + source.storedMembershipEvent(), + source.membershipEvent()); + } + + private static final class Fixture { + final AccountMembershipRoleSourceReader memberships = + mock(AccountMembershipRoleSourceReader.class); + final AccountDemoTenantEntitlementRepository entitlements = + mock(AccountDemoTenantEntitlementRepository.class); + final AccountGameplayTokenIdentityFenceRepository tokenFences = + mock(AccountGameplayTokenIdentityFenceRepository.class); + final AccountGameplayPublicAdmissionSourceReader reader = + new AccountGameplayPublicAdmissionSourceReader(memberships, entitlements, tokenFences); + TokenIdentity identity = + new TokenIdentity( + ACCOUNT, + UUID.fromString("efcfc7ed-1019-4ef7-9f27-87218fe0e911"), + UUID.fromString("f1b119cf-095f-4f03-b571-0fdd3d749c57"), + "a".repeat(64), + UUID.fromString("a1c51e75-ec05-4d9b-9ce0-965e775a9ac4"), + 1_800_000_000L, + 1L, + 1L); + final AccountGameplayTokenIdentityFence activeFence = + new AccountGameplayTokenIdentityFence(identity, 1L, State.ACTIVE, null, null); + final AccountMembershipRoleSourceSnapshot membership = membershipSnapshot(); + DemoTenantEntitlementSnapshot entitlement = + entitlement(AccountSelectedGameplayAuthorityProjectionTest.tenant(TENANT)); + + Fixture() { + when(memberships.readCurrent(ACCOUNT, TENANT)).thenReturn(membership); + when(entitlements.readCurrent(TENANT)).thenReturn(entitlement); + when(entitlements.revalidate(entitlement)).thenReturn(entitlement); + when(tokenFences.requireActiveForUpdate(identity)).thenReturn(activeFence); + } + + AccountGameplayPublicAdmissionSourceSnapshot read() { + return reader.readCurrent(ACCOUNT, TENANT, identity); + } + + void identityWithIssuanceFence(long fence) { + // A mismatched identity reaches the same owner read but cannot match Account's source fence. + TokenIdentity changed = + new TokenIdentity( + identity.accountId(), + identity.operationId(), + identity.issuanceRequestId(), + identity.tokenSha256(), + identity.tokenJti(), + identity.notBeforeEpochSecond(), + identity.tokenGeneration(), + fence); + when(tokenFences.requireActiveForUpdate(changed)) + .thenReturn(new AccountGameplayTokenIdentityFence(changed, 1L, State.ACTIVE, null, null)); + identity = changed; + } + + void replaceMembership(UnaryOperator change) { + AccountMembershipRoleSourceSnapshot changed = change.apply(membership); + when(memberships.readCurrent(ACCOUNT, TENANT)).thenReturn(changed); + } + + void updateEntitlement(Consumer change) { + EntitlementFields fields = new EntitlementFields(entitlement); + change.accept(fields); + entitlement = fields.build(); + when(entitlements.readCurrent(TENANT)).thenReturn(entitlement); + when(entitlements.revalidate(entitlement)).thenReturn(entitlement); + } + + void replaceEntitlement(DemoTenantEntitlementSnapshot changed) { + entitlement = changed; + when(entitlements.readCurrent(TENANT)).thenReturn(entitlement); + when(entitlements.revalidate(entitlement)).thenReturn(entitlement); + } + + private AccountMembershipRoleSourceSnapshot membershipSnapshot() { + String issuer = GameSessionAccountDelegationProfile.ISSUER; + var issuanceFence = new IssuanceFence(ACCOUNT, 1L, 1L); + var issuerSource = + new CurrentSourceEvidence( + AuthorityScope.issuer(issuer), + 1L, + 1L, + null, + new SourceCheckpoint( + "account:auth-authority:v1:issuer/" + issuer, + 0L, + Optional.empty(), + Optional.empty()), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 10L, + null); + var accountSource = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT), + 1L, + 1L, + issuanceFence, + new SourceCheckpoint( + "account:auth-authority:v1:account/" + ACCOUNT, + 0L, + Optional.empty(), + Optional.empty()), + Optional.empty(), + "ACCOUNT_REPOSITORY_INSERT", + 4L, + "ACCOUNT_REPOSITORY_INSERT", + 11L, + 11L); + var sources = new IssuerAccountSourceSnapshot(issuerSource, accountSource, issuanceFence); + var authority = + new CompositeSnapshot( + new ScopeState(AuthorityScope.issuer(issuer), 1L, 1L, null), + new ScopeState(AuthorityScope.account(ACCOUNT), 1L, 1L, issuanceFence), + List.of(new ScopeState(AuthorityScope.tenant(TENANT), 2L, 2L, null)), + List.of( + new ScopeState( + AuthorityScope.membership(ACCOUNT, TENANT), 1L, 1L, issuanceFence)), + issuanceFence); + TenantAuthorityEventV1Codec.Event tenant = + AccountSelectedGameplayAuthorityProjectionTest.tenant(TENANT); + var provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenant.sourceEvidence().operationId(), + tenant.sourceEvidence().evidenceDigest()); + var memberEvent = + AccountSelectedGameplayAuthorityProjectionTest.member(ACCOUNT, TENANT, "1", "2", "1"); + String membershipStream = "account:auth-authority:v1:membership/" + ACCOUNT + "/" + TENANT; + var pair = + new PairAuthority( + ACCOUNT, + TENANT, + provenance, + true, + 2L, + 1L, + 1L, + memberEvent.eventId(), + memberEvent.eventDigest(), + false); + var roles = + new RoleSnapshot(4L, null, 5L, 2L, List.of("player"), ACCOUNT, TENANT, provenance); + var member = + new MembershipSource( + 5L, + 4L, + ACCOUNT, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, + 4L, + TENANT, + provenance, + "ACTIVE", + true, + 2L, + 1L, + "EXPLICIT_JOIN"); + var checkpoint = + new Checkpoint(membershipStream, 1L, memberEvent.eventId(), memberEvent.eventDigest()); + var stored = + new Event( + membershipStream, + memberEvent.requestId(), + 1L, + memberEvent.eventId(), + memberEvent.eventDigest(), + memberEvent.canonicalJsonUtf8()); + return new AccountMembershipRoleSourceSnapshot( + sources, authority, tenant, pair, member, roles, checkpoint, stored, memberEvent); + } + } + + private static DemoTenantEntitlementSnapshot entitlement( + TenantAuthorityEventV1Codec.Event tenant) { + return new DemoTenantEntitlementSnapshot( + tenant.tenantId(), + tenant.sourceEvidence(), + "NON_PAID_DEMO", + "ACTIVE", + null, + false, + true, + true, + true, + true, + new net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest.Quotas( + 1L, 1L, 1L), + 1L, + tenant.tenantAuthorityGeneration(), + tenant.tenantAuthoritySourceVersion(), + tenant.tenantBillingStreamKey(), + tenant.tenantBillingSequence(), + tenant.tenantBillingEventId(), + tenant.tenantBillingEventDigest(), + tenant.tenantBillingEventDigest(), + tenant.outboxStreamKey(), + tenant.outboxSequence(), + tenant.eventId(), + tenant.eventDigest()); + } + + private static FreshTenantCreationEvidence differentSourceEvidence() { + var source = AccountSelectedGameplayAuthorityProjectionTest.tenant(TENANT).sourceEvidence(); + long changedRowId = source.sourceGameRowId() + 1L; + String changedTenantKey = source.sourceGameTenantKey() + "-different"; + return new FreshTenantCreationEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.creationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + changedRowId, + changedTenantKey, + source.provenanceKind(), + GameTenantCreationDigest.evidenceDigest( + source.targetNamespace(), + source.creationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + changedRowId, + changedTenantKey, + source.provenanceKind())); + } + + private static final class EntitlementFields { + UUID canonicalTenantId; + net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence sourceEvidence; + boolean gameplayAvailable; + boolean allowNewGameplayBindings; + long entitlementVersion; + long tenantAuthorityGeneration; + long tenantAuthoritySourceVersion; + String outboxStreamKey; + long tenantBillingSequence; + UUID eventId; + String eventDigest; + String snapshotIdentity; + String tenantAuthorityOutboxStreamKey; + long tenantAuthorityOutboxSequence; + UUID tenantAuthorityEventId; + String tenantAuthorityEventDigest; + + EntitlementFields(DemoTenantEntitlementSnapshot source) { + canonicalTenantId = source.canonicalTenantId(); + sourceEvidence = source.sourceEvidence(); + gameplayAvailable = source.gameplayAvailable(); + allowNewGameplayBindings = source.allowNewGameplayBindings(); + entitlementVersion = source.entitlementVersion(); + tenantAuthorityGeneration = source.tenantAuthorityGeneration(); + tenantAuthoritySourceVersion = source.tenantAuthoritySourceVersion(); + outboxStreamKey = source.outboxStreamKey(); + tenantBillingSequence = source.tenantBillingSequence(); + eventId = source.eventId(); + eventDigest = source.eventDigest(); + snapshotIdentity = source.snapshotIdentity(); + tenantAuthorityOutboxStreamKey = source.tenantAuthorityOutboxStreamKey(); + tenantAuthorityOutboxSequence = source.tenantAuthorityOutboxSequence(); + tenantAuthorityEventId = source.tenantAuthorityEventId(); + tenantAuthorityEventDigest = source.tenantAuthorityEventDigest(); + } + + DemoTenantEntitlementSnapshot build() { + return new DemoTenantEntitlementSnapshot( + canonicalTenantId, + sourceEvidence, + "NON_PAID_DEMO", + "ACTIVE", + null, + false, + gameplayAvailable, + true, + allowNewGameplayBindings, + true, + new net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest.Quotas( + 1L, 1L, 1L), + entitlementVersion, + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + outboxStreamKey, + tenantBillingSequence, + eventId, + eventDigest, + snapshotIdentity, + tenantAuthorityOutboxStreamKey, + tenantAuthorityOutboxSequence, + tenantAuthorityEventId, + tenantAuthorityEventDigest); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipRoleSourceReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipRoleSourceReaderTest.java new file mode 100644 index 0000000000..1453756c78 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipRoleSourceReaderTest.java @@ -0,0 +1,640 @@ +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.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Consumer; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.service.AccountMembershipRoleSourceReader; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedGameplayAuthorityProjectionTest; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +/** Owner doubles prove orchestration/source comparisons, not PostgreSQL or actor authentication. */ +class AccountMembershipRoleSourceReaderTest { + private static final UUID ACCOUNT = AccountSelectedGameplayAuthorityProjectionTest.ACCOUNT; + private static final UUID TENANT = AccountSelectedGameplayAuthorityProjectionTest.TENANT; + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + + @BeforeEach + void transaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_REPEATABLE_READ); + } + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void completeCaptureLocksAccountFirstAndCopiesMutableMembership() { + Fixture f = new Fixture(); + var snapshot = f.read(); + assertThat(snapshot.membershipEvent().membershipVersion()) + .isEqualTo(Map.of(TENANT.toString(), "2")); + assertThat(snapshot.membership().membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(snapshot.currentAuthority()).isEqualTo(f.authority); + assertThat(snapshot.tenantSource()).isEqualTo(f.tenant); + f.member.setLifecycleState("INACTIVE"); + assertThat(snapshot.membership().lifecycleState()).isEqualTo("ACTIVE"); + byte[] payload = snapshot.storedMembershipEvent().payload(); + payload[0] = 0; + assertThat(snapshot.storedMembershipEvent().payload()) + .containsExactly(f.event.canonicalJsonUtf8()); + assertThatThrownBy(() -> snapshot.roles().roles().add("tenantAdmin")) + .isInstanceOf(UnsupportedOperationException.class); + var ordered = + inOrder(f.sources, f.generations, f.tenants, f.memberships, f.pairs, f.roles, f.outbox); + ordered.verify(f.sources).readCurrentIssuerAccountSources(ISSUER, ACCOUNT); + ordered + .verify(f.generations) + .readCompositeSnapshot(ISSUER, ACCOUNT, List.of(TENANT), List.of(TENANT)); + ordered.verify(f.tenants).readCurrentByTenant(TENANT); + ordered.verify(f.memberships).findFreshMembershipForUpdate(ACCOUNT, TENANT); + ordered.verify(f.pairs).readForUpdate(ACCOUNT, TENANT); + ordered.verify(f.roles).findForCanonicalUpdate(ACCOUNT, TENANT, f.provenance, 5L, 2L); + } + + @Test + void inactiveInvalidatedHistoryIsStorageCaptureWithoutAdmission() { + Fixture f = new Fixture(); + f.member.setLifecycleState("INACTIVE"); + f.member.setGameplayAdmissionAllowed(false); + f.replaceEvent( + fields -> { + fields.put("membershipLifecycleState", "INACTIVE"); + fields.put("gameplayAdmissionAllowed", false); + fields.put("callerBoundAuthorityInvalidated", true); + }); + var snapshot = f.read(); + assertThat(snapshot.membership().lifecycleState()).isEqualTo("INACTIVE"); + assertThat(snapshot.membership().gameplayAdmissionAllowed()).isFalse(); + assertThat(snapshot.pair().lastTransitionInvalidated()).isTrue(); + } + + @Test + void independentlyAdvancedOwnersPreserveHistoricalMembershipEventExactly() { + Fixture f = new Fixture(); + f.replaceEvent( + fields -> + fields.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(TENANT.toString(), "1"), + "membershipAuthorityGeneration", + Map.of(TENANT.toString(), "1"), + "privateRealmGrantVersions", + List.of()))); + var historical = f.event; + f.advanceIndependentOwners(); + var snapshot = f.read(); + assertThat(snapshot.currentAuthority().issuer().generation()).isEqualTo(2L); + assertThat(snapshot.currentAuthority().account().generation()).isEqualTo(2L); + assertThat(snapshot.currentAuthority().tenants().getFirst().generation()).isEqualTo(2L); + assertThat(snapshot.currentAuthority().issuanceFence().value()).isEqualTo(2L); + assertThat(snapshot.membershipEvent().authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + assertThat(snapshot.membershipEvent().authorityTuple().accountAuthorityGeneration()) + .isEqualTo("1"); + assertThat(snapshot.membershipEvent().authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(TENANT.toString(), "1")); + assertThat(snapshot.membershipEvent().eventId()).isEqualTo(historical.eventId()); + assertThat(snapshot.membershipEvent().eventDigest()).isEqualTo(historical.eventDigest()); + assertThat(snapshot.storedMembershipEvent().payload()) + .containsExactly(historical.canonicalJsonUtf8()); + } + + @Test + void wrongMembershipIdentityProvenanceRolesAndIndependentCountersDeny() { + for (Consumer change : + List.>of( + f -> f.member.setTenantUuid(UUID.randomUUID()), + f -> f.member.setTenantSourceOperationId(UUID.randomUUID()), + f -> f.member.setTenantProvenanceDigest("sha256:" + "0".repeat(64)), + f -> f.member.getAccount().setAccountUuid(UUID.randomUUID()), + f -> f.member.getAccount().setAccountUuidSourceNumericId(9L), + f -> f.member.setMembershipVersion(3L), + f -> f.member.setMembershipAuthorityGeneration(2L), + f -> f.member.setAuthorityProvenance(null), + f -> + when(f.roles.findForCanonicalUpdate(ACCOUNT, TENANT, f.provenance, 5L, 2L)) + .thenReturn( + Optional.of( + new RoleSnapshot( + 4L, + null, + 5L, + 2L, + List.of("player", "tenantAdmin"), + ACCOUNT, + TENANT, + f.provenance))), + f -> + when(f.roles.findForCanonicalUpdate(ACCOUNT, TENANT, f.provenance, 5L, 2L)) + .thenReturn(Optional.empty()))) { + Fixture f = new Fixture(); + change.accept(f); + assertThatThrownBy(f::read).isInstanceOf(IllegalStateException.class); + } + } + + @Test + void missingPairMembershipEventOrCheckpointAndZeroEventDeny() { + for (Consumer change : + List.>of( + f -> + when(f.memberships.findFreshMembershipForUpdate(ACCOUNT, TENANT)) + .thenReturn(Optional.empty()), + f -> when(f.pairs.readForUpdate(ACCOUNT, TENANT)).thenReturn(Optional.empty()), + f -> + when(f.pairs.readForUpdate(ACCOUNT, TENANT)) + .thenReturn( + Optional.of( + new PairAuthority( + ACCOUNT, + TENANT, + f.provenance, + false, + 1L, + 1L, + 0L, + null, + null, + false))), + f -> when(f.outbox.readCheckpoint(f.stream())).thenReturn(Optional.empty()), + f -> when(f.outbox.findEvent(f.stream(), 1L)).thenReturn(Optional.empty()), + f -> + when(f.outbox.readCheckpoint(f.stream())) + .thenReturn( + Optional.of( + new Checkpoint( + f.stream(), + 1L, + UUID.randomUUID().toString(), + f.event.eventDigest()))), + f -> + when(f.outbox.readCheckpoint(f.stream())) + .thenReturn( + Optional.of( + new Checkpoint( + f.stream(), 2L, f.event.eventId(), f.event.eventDigest()))))) { + Fixture f = new Fixture(); + change.accept(f); + assertThatThrownBy(f::read).isInstanceOf(IllegalStateException.class); + } + } + + @Test + void storedEventIdentityDigestCanonicalBytesScopeAndMapCannotBeForged() { + for (Consumer change : + List.>of( + f -> + f.stored( + new Event( + f.stream(), + f.event.requestId(), + 1L, + UUID.randomUUID().toString(), + f.event.eventDigest(), + f.event.canonicalJsonUtf8())), + f -> + f.stored( + new Event( + f.stream(), + f.event.requestId(), + 1L, + f.event.eventId(), + "sha256:" + "0".repeat(64), + f.event.canonicalJsonUtf8())), + f -> + f.stored( + new Event( + f.stream(), + "different-request", + 1L, + f.event.eventId(), + f.event.eventDigest(), + f.event.canonicalJsonUtf8())), + f -> + f.stored( + new Event( + f.stream(), + f.event.requestId(), + 1L, + f.event.eventId(), + f.event.eventDigest(), + (f.event.canonicalJson() + " ") + .getBytes(java.nio.charset.StandardCharsets.UTF_8))), + f -> + f.replaceEvent( + fields -> fields.put("membershipVersion", Map.of(TENANT.toString(), "3"))), + f -> f.replaceEvent(fields -> fields.put("roles", List.of("player", "tenantAdmin"))), + f -> f.replaceEvent(fields -> fields.put("issuanceFence", "2")), + f -> + f.install( + AccountSelectedGameplayAuthorityProjectionTest.member( + UUID.randomUUID(), TENANT, "1", "2", "1")), + f -> + f.stored( + new Event( + f.stream(), + f.event.requestId(), + 1L, + f.event.eventId(), + f.event.eventDigest(), + f.event + .canonicalJson() + .replace( + "\"membershipVersion\":{\"" + TENANT + "\":\"2\"}", + "\"membershipVersion\":\"2\"") + .getBytes(java.nio.charset.StandardCharsets.UTF_8))))) { + Fixture f = new Fixture(); + change.accept(f); + assertThatThrownBy(f::read).isInstanceOf(RuntimeException.class); + } + } + + @Test + void currentCompositeScopeFenceAndSourceContradictionsDeny() { + Fixture f = new Fixture(); + when(f.sources.readCurrentIssuerAccountSources(ISSUER, ACCOUNT)).thenReturn(null); + assertThatThrownBy(f::read).isInstanceOf(IllegalStateException.class); + Fixture wrongScope = new Fixture(); + wrongScope.composite( + new CompositeSnapshot( + wrongScope.authority.issuer(), + wrongScope.authority.account(), + List.of(new ScopeState(AuthorityScope.tenant(UUID.randomUUID()), 2L, 2L, null)), + wrongScope.authority.memberships(), + wrongScope.fence)); + assertThatThrownBy(wrongScope::read).isInstanceOf(IllegalStateException.class); + Fixture wrongFence = new Fixture(); + wrongFence.composite( + new CompositeSnapshot( + wrongFence.authority.issuer(), + wrongFence.authority.account(), + wrongFence.authority.tenants(), + List.of( + new ScopeState( + AuthorityScope.membership(ACCOUNT, TENANT), + 1L, + 1L, + new IssuanceFence(ACCOUNT, 2L, 2L))), + wrongFence.fence)); + assertThatThrownBy(wrongFence::read).isInstanceOf(IllegalStateException.class); + } + + @Test + void noWritableRepeatableOwnerTransactionDeniesBeforeAnySourceRead() { + Fixture f = new Fixture(); + TransactionSynchronizationManager.setActualTransactionActive(false); + assertThatThrownBy(f::read).isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(f::read).isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThatThrownBy(f::read).isInstanceOf(IllegalStateException.class); + verifyNoInteractions( + f.sources, f.generations, f.memberships, f.pairs, f.roles, f.outbox, f.tenants); + assertThatThrownBy(() -> f.reader.readCurrent(new UUID(0L, 0L), TENANT)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static final class Fixture { + final AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + final AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + final AccountTenantMembershipRepository memberships = + mock(AccountTenantMembershipRepository.class); + final AccountMembershipPairAuthorityRepository pairs = + mock(AccountMembershipPairAuthorityRepository.class); + final AccountTenantMembershipRoleSnapshotRepository roles = + mock(AccountTenantMembershipRoleSnapshotRepository.class); + final AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + final AccountTenantAuthorityEventRepository tenants = + mock(AccountTenantAuthorityEventRepository.class); + final AccountMembershipRoleSourceReader reader = + new AccountMembershipRoleSourceReader( + sources, generations, memberships, pairs, roles, outbox, tenants); + final IssuanceFence fence = new IssuanceFence(ACCOUNT, 1L, 1L); + final net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event tenant = + AccountSelectedGameplayAuthorityProjectionTest.tenant(TENANT); + final VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenant.sourceEvidence().operationId(), + tenant.sourceEvidence().evidenceDigest()); + final AccountTenantMembership member = new AccountTenantMembership(); + CompositeSnapshot authority; + MembershipEvent event; + + Fixture() { + var issuer = + new CurrentSourceEvidence( + AuthorityScope.issuer(ISSUER), + 1L, + 1L, + null, + new SourceCheckpoint( + "account:auth-authority:v1:issuer/" + ISSUER, + 0L, + Optional.empty(), + Optional.empty()), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 10L, + null); + var accountSource = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT), + 1L, + 1L, + fence, + new SourceCheckpoint( + "account:auth-authority:v1:account/" + ACCOUNT, + 0L, + Optional.empty(), + Optional.empty()), + Optional.empty(), + "ACCOUNT_REPOSITORY_INSERT", + 4L, + "ACCOUNT_REPOSITORY_INSERT", + 11L, + 11L); + when(sources.readCurrentIssuerAccountSources(ISSUER, ACCOUNT)) + .thenReturn(new IssuerAccountSourceSnapshot(issuer, accountSource, fence)); + composite( + new CompositeSnapshot( + new ScopeState(issuer.scope(), 1L, 1L, null), + new ScopeState(accountSource.scope(), 1L, 1L, fence), + List.of(new ScopeState(AuthorityScope.tenant(TENANT), 2L, 2L, null)), + List.of(new ScopeState(AuthorityScope.membership(ACCOUNT, TENANT), 1L, 1L, fence)), + fence)); + when(tenants.readCurrentByTenant(TENANT)).thenReturn(tenant); + Account account = new Account(); + account.setId(4L); + account.setAccountUuid(ACCOUNT); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setAccountUuidSourceNumericId(4L); + member.setAccount(account); + member.setId(5L); + member.setTenantUuid(TENANT); + member.setTenantProvenanceKind(provenance.kind().name()); + member.setTenantSourceOperationId(provenance.sourceOperationId()); + member.setTenantProvenanceDigest(provenance.digest()); + member.setMembershipVersion(2L); + member.setMembershipAuthorityGeneration(1L); + member.setLifecycleState("ACTIVE"); + member.setGameplayAdmissionAllowed(true); + member.setAuthorityProvenance("EXPLICIT_JOIN"); + when(memberships.findFreshMembershipForUpdate(ACCOUNT, TENANT)) + .thenReturn(Optional.of(member)); + when(roles.findForCanonicalUpdate(ACCOUNT, TENANT, provenance, 5L, 2L)) + .thenReturn( + Optional.of( + new RoleSnapshot( + 4L, null, 5L, 2L, List.of("player"), ACCOUNT, TENANT, provenance))); + install( + AccountSelectedGameplayAuthorityProjectionTest.member(ACCOUNT, TENANT, "1", "2", "1")); + } + + void composite(CompositeSnapshot value) { + authority = value; + when(generations.readCompositeSnapshot(ISSUER, ACCOUNT, List.of(TENANT), List.of(TENANT))) + .thenReturn(value); + } + + void advanceIndependentOwners() { + String issuerStream = "account:auth-authority:v1:issuer/" + ISSUER; + String request = UUID.randomUUID().toString(); + var issuerEvent = + net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec + .sealIssuer( + new net.firedevops.firemud.common.account.authority + .AccountAuthoritySourceEventV1Codec.IssuerPreimage( + request, request, issuerStream, "1", ISSUER, "2", "2", "SIGNER_COMPROMISE")); + var issuer = + new CurrentSourceEvidence( + AuthorityScope.issuer(ISSUER), + 2L, + 2L, + null, + new SourceCheckpoint( + issuerStream, + 1L, + Optional.of(issuerEvent.eventId()), + Optional.of(issuerEvent.eventDigest())), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 10L, + null); + var issuerProjection = + new net.firedevops.firemud.accountservice.service.IssuerGenerationProjection( + ISSUER, + "2", + "2", + issuerStream, + "1", + Optional.of(issuerEvent.eventId()), + Optional.of(issuerEvent.eventDigest()), + Optional.of(issuerEvent.canonicalJson())); + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT; + var accountEvent = + net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec + .seal( + Map.ofEntries( + Map.entry( + "schemaVersion", + net.firedevops.firemud.common.account.authority + .AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry( + "eventType", + net.firedevops.firemud.common.account.authority + .AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + net.firedevops.firemud.common.account.authority + .AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + + request), + Map.entry("requestId", request), + Map.entry("accountId", ACCOUNT.toString()), + Map.entry("sourceScope", "account/" + ACCOUNT), + Map.entry("outboxStreamKey", accountStream), + Map.entry("outboxSequence", "1"), + Map.entry("accountAuthorityGeneration", "2"), + Map.entry("sourceVersion", "2"), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + "2", + "outboxStreamKey", + accountStream, + "outboxSequence", + "1")), + Map.entry("mutationKinds", List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED")), + Map.entry( + "accountState", + Map.of( + "emailVerified", + true, + "loginAuthModes", + List.of("EMAIL_OTP", "PASSWORD"), + "globalRoles", + List.of(), + "lifecycleState", + "ACTIVE")))); + var currentFence = new IssuanceFence(ACCOUNT, 2L, 2L); + var cutoff = + new net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec + .AccountSecurityCutoff("2", accountStream, "1"); + var accountSource = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT), + 2L, + 2L, + currentFence, + new SourceCheckpoint( + accountStream, + 1L, + Optional.of(accountEvent.eventId()), + Optional.of(accountEvent.eventDigest())), + Optional.of(cutoff), + "ACCOUNT_REPOSITORY_INSERT", + 4L, + "ACCOUNT_REPOSITORY_INSERT", + 11L, + 11L); + var accountProjection = + new net.firedevops.firemud.accountservice.service.AccountGenerationProjection( + ACCOUNT.toString(), + "2", + "2", + accountStream, + "1", + Optional.of(accountEvent.canonicalJson())); + when(sources.readCurrentIssuerAccountSources(ISSUER, ACCOUNT)) + .thenReturn( + new IssuerAccountSourceSnapshot( + issuer, accountSource, currentFence, accountProjection, issuerProjection)); + composite( + new CompositeSnapshot( + new ScopeState(issuer.scope(), 2L, 2L, null), + new ScopeState(accountSource.scope(), 2L, 2L, currentFence), + authority.tenants(), + List.of( + new ScopeState(AuthorityScope.membership(ACCOUNT, TENANT), 1L, 1L, currentFence)), + currentFence)); + } + + void install(MembershipEvent value) { + event = value; + when(pairs.readForUpdate(ACCOUNT, TENANT)) + .thenReturn( + Optional.of( + new PairAuthority( + ACCOUNT, + TENANT, + provenance, + true, + 2L, + 1L, + 1L, + event.eventId(), + event.eventDigest(), + event.callerBoundAuthorityInvalidated()))); + when(outbox.readCheckpoint(stream())) + .thenReturn( + Optional.of(new Checkpoint(stream(), 1L, event.eventId(), event.eventDigest()))); + stored( + new Event( + stream(), + event.requestId(), + 1L, + event.eventId(), + event.eventDigest(), + event.canonicalJsonUtf8())); + } + + void stored(Event value) { + when(outbox.findEvent(stream(), 1L)).thenReturn(Optional.of(value)); + } + + void replaceEvent(Consumer> change) { + try { + Map fields = + new LinkedHashMap<>( + JsonMapper.builder() + .build() + .readValue(event.canonicalJson(), new TypeReference>() {})); + fields.remove("eventDigest"); + change.accept(fields); + install(MembershipAuthorityEventV1Codec.seal(fields)); + } catch (Exception failure) { + throw new AssertionError(failure); + } + } + + String stream() { + return "account:auth-authority:v1:membership/" + ACCOUNT + "/" + TENANT; + } + + net.firedevops.firemud.accountservice.dto.AccountMembershipRoleSourceSnapshot read() { + return reader.readCurrent(ACCOUNT, TENANT); + } + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java new file mode 100644 index 0000000000..eb42f2e370 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java @@ -0,0 +1,434 @@ +package net.firedevops.firemud.common.account.admission; + +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.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import tools.jackson.core.JacksonException; +import tools.jackson.core.JsonParser; +import tools.jackson.core.JsonToken; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable, shape-only public-production lease carrier. This value authenticates no issuer, + * establishes no current source evidence, and never grants admission or proves COMMITTED state. + * + *

Tuple counters and membership versions inherit the public delegation validator's positive + * signed-long range. Values above that supported source range are rejected without substitution. + */ +public final class AccountGameplayAdmissionLeaseEvidence { + public static final String SCHEMA = "account-gameplay-admission-lease-evidence/v1"; + public static final long MAX_DURATION_MILLIS = 15_000L; + public static final int MAX_EVIDENCE_BYTES = 64 * 1024; + public static final int MAX_DEPTH = 8; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Set FIELDS = + Set.of( + "schema", + "schemaVersion", + "mode", + "targetNamespace", + "callerWorkload", + "requestId", + "leaseId", + "leaseFence", + "bindingScope", + "leaseKind", + "authorityTuple", + "issuanceFence", + "membershipBaseline", + "outboxCheckpoints", + "tokenIdentityEvidence", + "evaluatedAt", + "expiresAt"); + private final Map carrier; + private final String canonicalJson; + private final String digest; + + private AccountGameplayAdmissionLeaseEvidence(Map source) { + Map value = Map.copyOf(object(freeze(source, 1, new ByteBudget()))); + byte[] canonicalBytes = canonicalBytes(value); + Set expected = new java.util.HashSet<>(FIELDS); + LeaseKind kind = LeaseKind.valueOf(string(value, "leaseKind")); + if (kind == LeaseKind.RESUME) { + expected.add("resumeEpisodeId"); + expected.add("expectedOldBindingGeneration"); + } else if (value.containsKey("expectedOldBindingGeneration")) { + expected.add("expectedOldBindingGeneration"); + } + exact(value, expected); + if (!SCHEMA.equals(value.get("schema")) + || !"1".equals(value.get("schemaVersion")) + || !"PUBLIC_PRODUCTION".equals(value.get("mode"))) throw invalid(); + uuid(string(value, "requestId"), true); + uuid(string(value, "leaseId"), true); + if (kind == LeaseKind.RESUME) uuid(string(value, "resumeEpisodeId"), true); + if (value.containsKey("expectedOldBindingGeneration")) + positive(string(value, "expectedOldBindingGeneration")); + positive(string(value, "leaseFence")); + String namespace = string(value, "targetNamespace"); + String peerUri = string(value, "callerWorkload"); + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri(peerUri) + .orElseThrow(AccountGameplayAdmissionLeaseEvidence::invalid); + if (!peer.uri().equals(peerUri) + || !namespace.equals(peer.namespace()) + || !peer.isService("game-session-service")) throw invalid(); + + Map scope = object(value.get("bindingScope")); + exact( + scope, + Set.of( + "accountId", + "tenantId", + "realmId", + "worldSlug", + "realmSlug", + "playableStateNamespaceId", + "playableStateScope", + "gameInstanceId", + "characterId", + "sessionId", + "bindingGeneration", + "catalogRevision", + "pointerVersion", + "regionId", + "regionEpoch")); + for (String field : + List.of( + "accountId", + "tenantId", + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) uuid(string(scope, field), false); + for (String field : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + positive(string(scope, field)); + for (String field : List.of("worldSlug", "realmSlug")) text(string(scope, field)); + if (!Set.of("SHARED", "ISOLATED").contains(scope.get("playableStateScope"))) throw invalid(); + String tenant = string(scope, "tenantId"); + String account = string(scope, "accountId"); + + Map baseline = object(value.get("membershipBaseline")); + exact( + baseline, + Set.of("membershipLifecycleState", "membershipVersion", "membershipAuthorityGeneration")); + MembershipLifecycleState.valueOf(string(baseline, "membershipLifecycleState")); + Map versions = object(baseline.get("membershipVersion")); + exact(versions, Set.of(tenant)); + nonnegative(string(versions, tenant)); + String membershipGeneration = string(baseline, "membershipAuthorityGeneration"); + positive(membershipGeneration); + Map tuple = object(value.get("authorityTuple")); + // Reuse the profile's supported positive signed-long range, including exact values above 2^53. + try { + GameSessionAccountDelegationProfile.requirePublicTenantBoundAuthority( + tenant, tuple, versions); + } catch (RuntimeException failure) { + throw new IllegalArgumentException("Malformed public-tenant authority tuple", failure); + } + if (!membershipGeneration.equals( + object(tuple.get("membershipAuthorityGeneration")).get(tenant))) throw invalid(); + String fence = string(value, "issuanceFence"); + positive(fence); + + List checkpoints = list(value.get("outboxCheckpoints")); + Map coordinates = new LinkedHashMap<>(); + byte[] previous = null; + for (Object entry : checkpoints) { + Map checkpoint = object(entry); + exact(checkpoint, Set.of("outboxStreamKey", "outboxSequence")); + String key = string(checkpoint, "outboxStreamKey"); + text(key); + String sequence = string(checkpoint, "outboxSequence"); + nonnegative(sequence); + byte[] bytes = key.getBytes(StandardCharsets.UTF_8); + if (previous != null && Arrays.compareUnsigned(previous, bytes) >= 0) throw invalid(); + previous = bytes; + coordinates.put(key, sequence); + } + String prefix = "account:auth-authority:v1:"; + String issuerStream = prefix + "issuer/" + GameSessionAccountDelegationProfile.ISSUER; + String accountStream = prefix + "account/" + account; + String tenantStream = prefix + "tenant/" + tenant; + String membershipStream = prefix + "membership/" + account + "/" + tenant; + exact(coordinates, Set.of(issuerStream, accountStream, tenantStream, membershipStream)); + for (String stream : List.of(tenantStream, membershipStream)) positive(coordinates.get(stream)); + if (tuple.containsKey("accountSecurityCutoff")) { + cutoff(object(tuple.get("accountSecurityCutoff")), accountStream, coordinates); + } + if (tuple.containsKey("tenantBillingCutoff")) { + cutoff( + object(object(tuple.get("tenantBillingCutoff")).get(tenant)), tenantStream, coordinates); + } + + Map token = object(value.get("tokenIdentityEvidence")); + exact( + token, + Set.of( + "accountId", + "operationId", + "issuanceRequestId", + "tokenJti", + "tokenSHA256", + "tokenGeneration", + "issuanceFence", + "tokenIdentityFence", + "tokenProfile", + "issuedAt", + "notBefore", + "expiresAt")); + uuid(string(token, "accountId"), false); + for (String field : List.of("operationId", "issuanceRequestId", "tokenJti")) + uuid(string(token, field), true); + if (!account.equals(token.get("accountId")) + || !fence.equals(token.get("issuanceFence")) + || !string(token, "tokenSHA256").matches("[0-9a-f]{64}") + || !GameSessionAccountDelegationProfile.PROFILE.equals(token.get("tokenProfile"))) + throw invalid(); + for (String field : List.of("tokenGeneration", "issuanceFence", "tokenIdentityFence")) + positive(string(token, field)); + BigInteger issued = timestamp(token, "issuedAt").multiply(BigInteger.valueOf(1000L)); + BigInteger notBefore = timestamp(token, "notBefore").multiply(BigInteger.valueOf(1000L)); + BigInteger tokenExpiry = timestamp(token, "expiresAt").multiply(BigInteger.valueOf(1000L)); + BigInteger evaluated = timestamp(value, "evaluatedAt"); + BigInteger expiry = timestamp(value, "expiresAt"); + BigInteger duration = expiry.subtract(evaluated); + if (issued.compareTo(evaluated) > 0 + || notBefore.compareTo(issued) > 0 + || expiry.compareTo(tokenExpiry) > 0 + || duration.signum() <= 0 + || duration.compareTo(BigInteger.valueOf(MAX_DURATION_MILLIS)) > 0) throw invalid(); + carrier = value; + try { + canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); + digest = + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonicalBytes)); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalArgumentException("Cannot canonicalize lease evidence", failure); + } + } + + public enum LeaseKind { + NEW_BINDING, + RESUME + } + + public enum MembershipLifecycleState { + ACTIVE, + INACTIVE + } + + /** Validates and defensively freezes original carriers without establishing their provenance. */ + public static AccountGameplayAdmissionLeaseEvidence fromCarrier(Map carrier) { + if (carrier == null) throw invalid(); + return new AccountGameplayAdmissionLeaseEvidence(carrier); + } + + /** Accepts only the exact canonical serialization; duplicate and unknown fields fail closed. */ + public static AccountGameplayAdmissionLeaseEvidence parseCanonical(String json) { + requireByteBound(json); + try { + // Inspect depth before allocating a nested object tree; duplicate detection applies here too. + try (JsonParser parser = JSON.createParser(json)) { + int depth = 0; + JsonToken token; + while ((token = parser.nextToken()) != null) { + if ((token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) + && ++depth > MAX_DEPTH) throw invalid(); + if (token == JsonToken.END_OBJECT || token == JsonToken.END_ARRAY) depth--; + } + } + AccountGameplayAdmissionLeaseEvidence result = + fromCarrier(object(JSON.readValue(json, Object.class))); + if (!result.canonicalJson.equals(json)) throw invalid(); + return result; + } catch (JacksonException failure) { + throw new IllegalArgumentException("Malformed lease evidence", failure); + } + } + + public Map carrier() { + return carrier; + } + + public String canonicalJson() { + return canonicalJson; + } + + public String sha256() { + return digest; + } + + public BigInteger leaseFence() { + return positive(string(carrier, "leaseFence")); + } + + public LeaseKind leaseKind() { + return LeaseKind.valueOf(string(carrier, "leaseKind")); + } + + /** Exact original immutable carriers and their canonical digest define retry identity. */ + public boolean hasSameIdentity(AccountGameplayAdmissionLeaseEvidence other) { + return other != null && carrier.equals(other.carrier) && digest.equals(other.digest); + } + + @Override + public boolean equals(Object other) { + return other instanceof AccountGameplayAdmissionLeaseEvidence evidence + && hasSameIdentity(evidence); + } + + @Override + public int hashCode() { + return carrier.hashCode(); + } + + @Override + public String toString() { + return "AccountGameplayAdmissionLeaseEvidence[redacted]"; + } + + private static void cutoff( + Map cutoff, String stream, Map checkpoints) { + if (!stream.equals(cutoff.get("outboxStreamKey")) + || nonnegative(checkpoints.get(stream)) + .compareTo(positive(string(cutoff, "outboxSequence"))) + < 0) throw invalid(); + } + + private static BigInteger timestamp(Map object, String field) { + BigInteger value = positive(string(object, field)); + if (value.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) throw invalid(); + return value; + } + + private static BigInteger positive(String value) { + BigInteger integer = nonnegative(value); + if (integer.signum() <= 0) throw invalid(); + return integer; + } + + private static BigInteger nonnegative(String value) { + if (value == null || !value.matches("0|[1-9][0-9]*")) throw invalid(); + return new BigInteger(value); + } + + private static void uuid(String value, boolean highEntropy) { + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (RuntimeException failure) { + throw invalid(); + } + if (!parsed.toString().equals(value) + || parsed.equals(new UUID(0, 0)) + || (highEntropy && (parsed.version() != 4 || parsed.variant() != 2))) throw invalid(); + } + + private static void text(String value) { + if (value.isBlank() + || value.length() > 2048 + || value.codePoints().anyMatch(Character::isISOControl)) throw invalid(); + } + + private static String string(Map object, String field) { + if (!(object.get(field) instanceof String value)) throw invalid(); + return value; + } + + private static void exact(Map object, Set fields) { + if (!object.keySet().equals(fields)) throw invalid(); + } + + private static Map object(Object value) { + if (!(value instanceof Map map)) throw invalid(); + Map result = new LinkedHashMap<>(); + map.forEach( + (key, child) -> { + if (!(key instanceof String text)) throw invalid(); + result.put(text, child); + }); + return result; + } + + private static List list(Object value) { + if (!(value instanceof List entries)) throw invalid(); + return entries; + } + + private static Object freeze(Object value, int depth, ByteBudget budget) { + if (depth > MAX_DEPTH) throw invalid(); + budget.consume(1); + if (value instanceof Map map) { + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : map.entrySet()) { + if (!(entry.getKey() instanceof String key)) throw invalid(); + budget.consume(requireByteBound(key) + 4); + result.put(key, freeze(entry.getValue(), depth + 1, budget)); + } + return java.util.Collections.unmodifiableMap(result); + } + if (value instanceof List values) { + List frozen = new ArrayList<>(); + for (Object child : values) frozen.add(freeze(child, depth + 1, budget)); + return List.copyOf(frozen); + } + if (!(value instanceof String text)) throw invalid(); + budget.consume(requireByteBound(text) + 2); + return value; + } + + private static int requireByteBound(String value) { + if (value == null || value.length() > MAX_EVIDENCE_BYTES) throw invalid(); + int size = value.getBytes(StandardCharsets.UTF_8).length; + if (size > MAX_EVIDENCE_BYTES) throw invalid(); + return size; + } + + private static byte[] canonicalBytes(Map value) { + try { + String serialized = JSON.writeValueAsString(value); + requireByteBound(serialized); + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(serialized); + if (bytes.length > MAX_EVIDENCE_BYTES) throw invalid(); + return bytes; + } catch (IOException | JacksonException failure) { + throw new IllegalArgumentException("Cannot canonicalize lease evidence", failure); + } + } + + private static final class ByteBudget { + private int remaining = MAX_EVIDENCE_BYTES; + + private void consume(int count) { + remaining -= count; + if (remaining < 0) throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Malformed public-production admission lease evidence"); + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java new file mode 100644 index 0000000000..180a77ae0a --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java @@ -0,0 +1,362 @@ +package net.firedevops.firemud.common.account.admission; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import org.junit.jupiter.api.Test; + +class AccountGameplayAdmissionLeaseEvidenceTest { + private static final String ACCOUNT = "11111111-1111-4111-8111-111111111111"; + private static final String TENANT = "22222222-2222-4222-8222-222222222222"; + private static final String OTHER = "33333333-3333-4333-8333-333333333333"; + private static final String HIGH = "9007199254740993"; + private static final String PREFIX = "account:auth-authority:v1:"; + + @Test + void retainsExactCanonicalRetryIdentityAndCountersAboveDoublePrecision() { + var value = evidence(); + var parsed = AccountGameplayAdmissionLeaseEvidence.parseCanonical(value.canonicalJson()); + assertThat(parsed).isEqualTo(value); + assertThat(value.hasSameIdentity(parsed)).isTrue(); + assertThat(value.sha256()).matches("[0-9a-f]{64}"); + assertThat(value.leaseFence()).isEqualTo(new BigInteger(HIGH)); + assertThat(value.canonicalJson()) + .contains("\"membershipVersion\":{\"" + TENANT + "\":\"" + HIGH + "\"}"); + assertThat(value.toString()).doesNotContain(ACCOUNT, value.sha256()); + } + + @Test + void lifecycleShapeCarriesInactiveWithoutGrantingAuthority() { + Map carrier = fixture(); + object(carrier, "membershipBaseline").put("membershipLifecycleState", "INACTIVE"); + assertThat(AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier).sha256()) + .isNotEqualTo(evidence().sha256()); + } + + @Test + void everyCompleteCarrierContributesToDigest() { + List>> changes = + List.of( + c -> + object(object(c, "membershipBaseline"), "membershipVersion") + .put(TENANT, "9007199254740994"), + c -> object(c, "authorityTuple").put("issuerAuthGeneration", "2"), + c -> object(c, "bindingScope").put("worldSlug", "another-world"), + c -> object(c, "tokenIdentityEvidence").put("tokenSHA256", "b".repeat(64)), + c -> c.put("expiresAt", "1014000"), + c -> checkpoints(c).get(0).put("outboxSequence", "1")); + for (Consumer> change : changes) { + var carrier = fixture(); + change.accept(carrier); + var changed = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + assertThat(changed.sha256()).isNotEqualTo(evidence().sha256()); + assertThat(changed.hasSameIdentity(evidence())).isFalse(); + } + } + + @Test + void rejectsBaselineMissingExtraScalarWrongTenantAndMismatchedGeneration() { + rejects(c -> c.remove("membershipBaseline")); + rejects(c -> object(c, "membershipBaseline").put("extra", "1")); + rejects(c -> object(c, "membershipBaseline").remove("membershipAuthorityGeneration")); + rejects(c -> object(c, "membershipBaseline").put("membershipVersion", HIGH)); + rejects(c -> object(c, "membershipBaseline").put("membershipVersion", Map.of(OTHER, HIGH))); + rejects(c -> object(c, "membershipBaseline").put("membershipVersion", Map.of(TENANT, "01"))); + rejects(c -> object(c, "membershipBaseline").put("membershipVersion", Map.of(TENANT, 1L))); + rejects(c -> object(c, "membershipBaseline").put("membershipAuthorityGeneration", "2")); + rejects( + c -> + object(c, "membershipBaseline") + .put("membershipVersion", Map.of(TENANT, "9223372036854775808"))); + } + + @Test + void rejectsDuplicateUnorderedMissingExtraAndMalformedCheckpoints() { + rejects(c -> checkpoints(c).add(new LinkedHashMap<>(checkpoints(c).get(0)))); + rejects(c -> java.util.Collections.swap(checkpoints(c), 0, 1)); + rejects(c -> checkpoints(c).remove(0)); + rejects(c -> checkpoints(c).get(0).put("outboxSequence", "00")); + rejects(c -> checkpoints(c).get(2).put("outboxSequence", "0")); + rejects(c -> checkpoints(c).get(0).put("eventId", OTHER)); + } + + @Test + void rejectsWrongModeScopePeerTokenAndResumeEpisode() { + rejects(c -> c.put("mode", "PRIVATE")); + rejects(c -> c.put("leaseKind", "REFRESH")); + rejects(c -> c.put("resumeEpisodeId", OTHER)); + rejects(c -> c.put("leaseKind", "RESUME")); + rejects(c -> object(c, "bindingScope").put("playableStateScope", "PUBLIC_PRODUCTION")); + rejects(c -> object(c, "bindingScope").put("regionId", "region-1")); + rejects(c -> c.put("targetNamespace", "other")); + rejects(c -> c.put("callerWorkload", "spiffe://firemud/ns/test/sa/account-service")); + rejects(c -> object(c, "tokenIdentityEvidence").put("accountId", OTHER)); + rejects(c -> object(c, "tokenIdentityEvidence").put("issuanceFence", "2")); + rejects(c -> object(c, "tokenIdentityEvidence").put("tokenBytes", "secret")); + rejects(c -> object(c, "tokenIdentityEvidence").put("tokenProfile", "gameplay-connect")); + var resume = fixture(); + resume.put("leaseKind", "RESUME"); + resume.put("resumeEpisodeId", OTHER); + resume.put("expectedOldBindingGeneration", "7"); + assertThat(AccountGameplayAdmissionLeaseEvidence.fromCarrier(resume).leaseKind()) + .isEqualTo(AccountGameplayAdmissionLeaseEvidence.LeaseKind.RESUME); + } + + @Test + void retainsExplicitPriorGenerationWithoutDerivingHistory() { + var initial = fixture(); + var prior = fixture(); + prior.put("expectedOldBindingGeneration", "7"); + var priorValue = AccountGameplayAdmissionLeaseEvidence.fromCarrier(prior); + assertThat(priorValue.sha256()) + .isNotEqualTo(AccountGameplayAdmissionLeaseEvidence.fromCarrier(initial).sha256()); + assertThat(AccountGameplayAdmissionLeaseEvidence.parseCanonical(priorValue.canonicalJson())) + .isEqualTo(priorValue); + rejects(c -> c.put("expectedOldBindingGeneration", "0")); + rejects(c -> c.put("expectedOldBindingGeneration", null)); + rejects( + c -> { + c.put("leaseKind", "RESUME"); + c.put("resumeEpisodeId", OTHER); + }); + } + + @Test + void rejectsExpiredLongerThanSlaOrExtendingTokenAndNoncanonicalParsing() { + rejects(c -> c.put("expiresAt", "1000000")); + rejects(c -> c.put("expiresAt", "1015001")); + rejects(c -> object(c, "tokenIdentityEvidence").put("expiresAt", "1014")); + rejects(c -> object(c, "tokenIdentityEvidence").put("notBefore", "1001")); + rejects(c -> c.put("leaseFence", "+1")); + rejects(c -> c.put("schemaVersion", "2")); + String json = evidence().canonicalJson(); + assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.parseCanonical(" " + json)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.parseCanonical(json + "{}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.parseCanonical(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseEvidence.parseCanonical( + json.replace( + "\"schemaVersion\":\"1\"", + "\"schemaVersion\":\"1\",\"schemaVersion\":\"1\""))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void cutoffReferencesMustBeCoveredByCompleteCheckpointCoordinates() { + var carrier = fixture(); + object(carrier, "authorityTuple").put("accountAuthorityGeneration", "2"); + object(carrier, "authorityTuple") + .put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + "2", + "outboxStreamKey", + PREFIX + "account/" + ACCOUNT, + "outboxSequence", + "1")); + checkpoints(carrier).get(0).put("outboxSequence", "1"); + assertThat(AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier)).isNotNull(); + checkpoints(carrier).get(0).put("outboxSequence", "2"); + var retained = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + assertThat(object(retained.carrier(), "authorityTuple").get("accountSecurityCutoff")) + .isEqualTo(object(carrier, "authorityTuple").get("accountSecurityCutoff")); + checkpoints(carrier).get(0).put("outboxSequence", "0"); + assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier)) + .isInstanceOf(IllegalArgumentException.class); + var billing = fixture(); + object(billing, "authorityTuple") + .put( + "tenantBillingCutoff", + Map.of( + TENANT, + Map.of( + "tenantAuthorityGeneration", + HIGH, + "tenantBillingSequence", + "7", + "outboxStreamKey", + PREFIX + "tenant/" + TENANT, + "outboxSequence", + HIGH))); + assertThat(AccountGameplayAdmissionLeaseEvidence.fromCarrier(billing)).isNotNull(); + checkpoints(billing).get(3).put("outboxSequence", "9007199254740994"); + assertThat(AccountGameplayAdmissionLeaseEvidence.fromCarrier(billing)).isNotNull(); + checkpoints(billing).get(3).put("outboxSequence", "2"); + assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.fromCarrier(billing)) + .isInstanceOf(IllegalArgumentException.class); + object(billing, "authorityTuple") + .put( + "tenantBillingCutoff", + Map.of( + TENANT, + Map.of( + "tenantAuthorityGeneration", + HIGH, + "tenantBillingSequence", + "7", + "outboxStreamKey", + PREFIX + "account/" + ACCOUNT, + "outboxSequence", + "1"))); + assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.fromCarrier(billing)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsOversizedDeepCyclicAndNullCarriersBeforeBuildingUnboundedEvidence() { + rejects( + c -> + c.put( + "large", "a".repeat(AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + 1))); + rejects(c -> c.put("large", "界".repeat(22000))); + rejects( + c -> { + Map nested = Map.of("leaf", "value"); + for (int index = 0; index < 10; index++) { + nested = Map.of("nested", nested); + } + c.put("nested", nested); + }); + rejects(c -> c.put("cycle", c)); + rejects(c -> c.put("nullable", null)); + assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.fromCarrier(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseEvidence.parseCanonical( + " ".repeat(AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseEvidence.parseCanonical( + "[".repeat(10) + "\"value\"" + "]".repeat(10))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void freezesNestedMapsAndCheckpointListsAgainstCallerMutation() { + var carrier = fixture(); + var value = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + String original = value.canonicalJson(); + object(object(carrier, "membershipBaseline"), "membershipVersion").put(TENANT, "2"); + checkpoints(carrier).clear(); + assertThat(value.canonicalJson()).isEqualTo(original); + assertThatThrownBy( + () -> object(value.carrier(), "authorityTuple").put("issuerAuthGeneration", "2")) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> checkpoints(value.carrier()).clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + private static AccountGameplayAdmissionLeaseEvidence evidence() { + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(fixture()); + } + + private static void rejects(Consumer> change) { + var value = fixture(); + change.accept(value); + assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.fromCarrier(value)) + .isInstanceOf(IllegalArgumentException.class); + } + + @SuppressWarnings("unchecked") + private static Map object(Map value, String key) { + return (Map) value.get(key); + } + + @SuppressWarnings("unchecked") + private static List> checkpoints(Map value) { + return (List>) value.get("outboxCheckpoints"); + } + + private static Map fixture() { + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", "test"); + value.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + value.put("requestId", OTHER); + value.put("leaseId", TENANT); + value.put("leaseFence", HIGH); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, OTHER); + scope.put("accountId", ACCOUNT); + scope.put("tenantId", TENANT); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, HIGH); + value.put("bindingScope", scope); + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", "1"); + tuple.put("accountAuthorityGeneration", "1"); + tuple.put("tenantAuthorityGeneration", Map.of(TENANT, HIGH)); + tuple.put("membershipAuthorityGeneration", Map.of(TENANT, HIGH)); + tuple.put("privateRealmGrantVersions", List.of()); + value.put("authorityTuple", tuple); + value.put("issuanceFence", HIGH); + value.put( + "membershipBaseline", + new LinkedHashMap<>( + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + new LinkedHashMap<>(Map.of(TENANT, HIGH)), + "membershipAuthorityGeneration", + HIGH))); + List> checkpoints = new ArrayList<>(); + for (String suffix : + List.of( + "account/" + ACCOUNT, + "issuer/firemud-account-service", + "membership/" + ACCOUNT + "/" + TENANT, + "tenant/" + TENANT)) { + checkpoints.add( + new LinkedHashMap<>( + Map.of( + "outboxStreamKey", + PREFIX + suffix, + "outboxSequence", + suffix.startsWith("account/") || suffix.startsWith("issuer/") ? "0" : HIGH))); + } + value.put("outboxCheckpoints", checkpoints); + Map token = new LinkedHashMap<>(); + token.put("accountId", ACCOUNT); + for (String key : List.of("operationId", "issuanceRequestId", "tokenJti")) + token.put(key, OTHER); + token.put("tokenSHA256", "a".repeat(64)); + token.put("tokenProfile", "game-session-account-delegation"); + for (String key : List.of("tokenGeneration", "issuanceFence", "tokenIdentityFence")) + token.put(key, HIGH); + token.put("issuedAt", "999"); + token.put("notBefore", "999"); + token.put("expiresAt", "1300"); + value.put("tokenIdentityEvidence", token); + value.put("evaluatedAt", "1000000"); + value.put("expiresAt", "1015000"); + return value; + } +} From 9e6bb64d29a6a38320d52accdce64382446596ed Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 08:27:40 +1300 Subject: [PATCH 02/16] Persist exact Account admission lease storage and recovery --- .../account-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 10 +- ...ccountGameplayAdmissionLeaseOperation.java | 44 ++ ...GameplayPublicAdmissionSourceSnapshot.java | 6 +- ...countGameplayAdmissionLeaseRepository.java | 311 +++++++++++ ...ntGameplayPublicAdmissionSourceReader.java | 54 +- ...nt_gameplay_admission_lease_operations.sql | 113 ++++ ...issionLeasePersistenceIntegrationTest.java | 512 ++++++++++++++++++ ...ionIssuancePersistenceIntegrationTest.java | 407 ++++++++++++++ ...tGameplayAdmissionLeaseRepositoryTest.java | 264 +++++++++ ...meplayPublicAdmissionSourceReaderTest.java | 72 ++- 11 files changed, 1781 insertions(+), 14 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java create mode 100644 services/account-service/src/main/resources/db/migration/V87__account_gameplay_admission_lease_operations.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 6156cb1dee..db2e66a0d0 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -36,7 +36,7 @@ Hosted Creator Party/operator identity, terms catalog, acceptance/currentness ev The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current consumers still rely on only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and do not enforce the complete atomic-freshness contract or consume the emitted lifecycle/generation fields. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and character discovery require membership after applicable target and entitlement checks; on an eligible public-production target only absent membership may return non-actionable `JOIN_REQUIRED`, while existing membership with `gameplayAdmissionAllowed=false` is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` can still return non-actionable `JOIN_REQUIRED` for missing or present non-admitting membership before fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. These flows do not create or restore membership. The Account-owned public-production `JOIN` writer is implemented locally with a v1 policy-bound digest and atomic membership, operation-outcome, and audit-outbox evidence. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Exact-final-head PostgreSQL runtime proof remains unavailable locally without Docker; no live PostgreSQL runtime proof or direct text-client end-to-end proof is claimed. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when a tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only that cardinality guard and retry boundary. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. -The current `application.yml` and `application-prod.yml` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods. The shared interceptor therefore bypasses bearer validation, while the current handlers use request-body `accountId`/`tenantId` values without exact workload or typed caller-context checks. This contradicts the internal-only matrix contract and blocks readiness until the methods are removed from the public bypass list and missing-token, wrong-workload, tenant-binding, and cross-tenant negative proof is present. +The current `application.yml` and `application-prod.yml` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods so workload-only mTLS calls bypass bearer validation. The membership handler separately requires the exact Game Session workload peer and resolves the Account UUID through Account-owned identity evidence. The entitlement handler requires the exact same-namespace Game Session or World Management peer. Complete typed target/caller binding and same-snapshot admission evidence remain incomplete, as described in the owning [Account runtime-read API contract](./api-contracts.md#runtime-membership-and-entitlement-api-consequences). Neither response supplies an admission lease or authorizes a binding. Readiness requires the canonical protected owner composition and its missing-caller, wrong-workload, target-binding and cross-tenant negative proof; the detailed current gaps are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). The target realm-grant mutation boundary remains the Account API's tenant-admin or separately authorized platform-admin operator path ([Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract)). The live legacy `POST`/`DELETE /internal/runtime/realm-access-grants` routes instead admit the broad shared global-privileged-role helper (including `moderator`), accept caller-supplied `grantedBy`/`grantReason`, and do not apply the target lifecycle identity, revision, digest, or request-replay contract. They must be removed or fail closed until the canonical owner transport and its authenticated attribution and replay proof are implemented; this route is not an additional grant authority. 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 9f4d072d59..c54207568c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,11 +8,15 @@ This is a non-normative implementation tracker for player access and session. Ca ### Account Admission-Lease Prerequisite -The isolated Account candidate adds an unregistered same-transaction source reader for fresh Game Design tenant provenance and the existing `NON_PAID_DEMO` entitlement class. It captures the actual issuer/Account/tenant/membership sources, exact membership event and role snapshot, current entitlement and its separate billing receipt, and the exact SQL token-identity fence. Active player membership, entitlement admission flags, provenance, issuance fence and receipt/checkpoint consistency are checked through the existing owner repositories; missing, changed or unsupported evidence is denied. Unit fixtures use doubles of those repositories and do not establish PostgreSQL lock or race behavior. +The isolated Account candidate adds an unregistered same-transaction source reader for fresh Game Design tenant provenance and the existing `NON_PAID_DEMO` entitlement class. It captures the actual issuer/Account/tenant/membership sources, persisted Account lifecycle, exact membership event and role snapshot, current entitlement and its separate billing receipt, and the exact SQL token-identity fence. The exact Account row identity and `ACTIVE` lifecycle, active player membership, entitlement admission flags, provenance, issuance fence and receipt/checkpoint consistency are checked through the existing owner repositories; missing, changed or unsupported evidence is denied. Unit fixtures use doubles of those repositories and do not establish PostgreSQL lock or race behavior. Four PostgreSQL source-capture definitions compose the existing first-JOIN, entitlement and issuance owners; their seeded evidence does not prove authenticated Game Design transport, gameplay admission or lease finalization. The shared admission-lease evidence value preserves the complete unchanged baseline, public-target tuple, ordered authority checkpoints, exact token metadata, caller workload, binding identity, absolute expiry and applicable resume/prior-generation fields. It is a bounded canonical shape/digest codec, not authenticated Account evidence or a lease issuer. Its tuple and baseline validation currently inherits the existing public-delegation validator's signed-long source range; unsupported values are denied rather than substituted. Billing cutoff evidence refers to the tenant authority stream; the demo entitlement's separate availability receipt is not invented as another authority checkpoint. -This prerequisite does not supply protected acquire/finalize/abort/reconcile RPCs, durable admission-lease allocation or `COMMITTED` evidence, authenticated lifecycle/target or token-registry verification, pending-invalidation enforcement, orphan cleanup, private-grant or paid-entitlement support, or executed PostgreSQL/fresh-image LOGIN → PLAY → LOOK proof. Construction of either source capture or carrier grants no admission, and the runtime path remains denied. The owning target contract is [Session Behavior](../../architecture/system-architecture-session-behavior.md), with Account's predicate and caller obligations in [Authentication](../../architecture/system-architecture-authentication.md). The consolidated source/codec gate passes Common Security and Account checks, integration-source compilation, formatting, static analysis, links and Markdown lint: 147 Common Security tests and 1,049 Account unit tests executed without failures; three Account unit tests skipped. Two non-database integration cases executed, while 124 integration cases skipped. These counts do not establish PostgreSQL locks, migration execution or lease finalization. +V87 adds unregistered Account-owned allocation and exact operation storage. Its independent per-Account lease fence and immutable request/lease identity are read back before returning; lost-response lookup recovers the original allocation and canonical operation by request without generating another identity. Writable SERIALIZABLE transactions lock Account first. Terminal storage preserves the original carrier and absolute deadline; `ABORTED` atomically retains an exact pending orphan-cleanup identity. Storage `COMMITTED` is not an authenticated finalization result. Workload equality is storage correlation, and empty lookup proves neither authoritative absence nor token retirement. The six PostgreSQL storage definitions cover fresh and retained-account migration, changed evidence, terminal conflicts, rollback, expiry, concurrent allocation and lost-response readback. Their carriers are explicitly fabricated shape fixtures, not admission authority. PostgreSQL-specific constraints remain enforced by the migration even where narrowly excluded from jOOQ's schema simulator. + +This prerequisite does not supply protected acquire/finalize/abort/reconcile RPCs, authenticated target or token-registry verification, Account safety-restriction sources, pending-invalidation enforcement, physical COMMIT-time expiry proof, committed-binding orphan reconciliation or delivered cleanup, private-grant or paid-entitlement support, or executed PostgreSQL/fresh-image LOGIN → PLAY → LOOK proof. Construction of source capture, carrier or operation storage grants no admission, and the runtime path remains denied. The owning target contract is [Session Behavior](../../architecture/system-architecture-session-behavior.md), with Account's predicate and caller obligations in [Authentication](../../architecture/system-architecture-authentication.md). Local consolidated proof is recorded below; compilation and simulated schema generation do not establish physical PostgreSQL locks, migration execution or lease finalization. + +The consolidated storage/source checkpoint executes 147 Common Security and 1,071 Account unit cases without failures or errors; three Account unit cases skip. Two non-database integration cases execute, while 134 integration cases skip without authorized local PostgreSQL infrastructure. Account and Common Security checks, jOOQ generation, integration-source compilation, formatting, static analysis, links and Markdown are the selected local gates; skipped database definitions are not runtime or migration proof. ### Credential-Bound Account LOGIN Owner @@ -38,7 +42,7 @@ Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, G Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. -Account runtime admission reads remain a security/proof blocker, but their implemented boundaries differ. `GetTenantMembershipForRuntime` requires the exact Game Session workload peer and resolves the canonical Account UUID through Account-owned identity evidence before reading membership; it verifies the private account/tenant/world/realm correlation and echoes the UUID. Focused negative proof covers malformed identifiers and unavailable or mismatched owner evidence. `GetTenantEntitlementsForRuntime` remains configured as a public gRPC method and lacks exact workload-peer and tenant binding, so it does not yet meet the target internal-workload boundary. The canonical target and remaining proof gap are recorded in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). +Account runtime admission reads remain a security/proof blocker, but both handlers enforce workload identity. `GetTenantMembershipForRuntime` requires the exact Game Session workload peer and resolves the canonical Account UUID through Account-owned identity evidence before reading membership; it verifies the private account/tenant/world/realm correlation and echoes the UUID. Focused negative proof covers malformed identifiers and unavailable or mismatched owner evidence. `GetTenantEntitlementsForRuntime` requires the exact same-namespace Game Session or World Management peer. Both workload-only methods bypass bearer validation; complete typed target/caller binding, same-snapshot evidence and admission-lease producer/consumer proof remain incomplete. The canonical target and remaining proof gap are recorded in [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md), [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). PLAYER-01 ownership and the target `CHARS`/`PLAY` actor-entry rules are canonical in [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity Management API/runtime](../../architecture/microservices/entity-management-service/api-contracts.md), not this tracker. Current synthetic/unresolved-character fallback risk, descriptor/template resolution gaps, namespace-qualified actor-revalidation gaps, and fork-local copy proof gaps remain and do not upgrade AA-2.1 status. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java new file mode 100644 index 0000000000..97324a505a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java @@ -0,0 +1,44 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; + +/** Durable Account storage readback only; even COMMITTED is not authenticated admission proof. */ +public record AccountGameplayAdmissionLeaseOperation( + AccountGameplayAdmissionLeaseEvidence evidence, + State state, + UUID bindingDecisionId, + UUID orphanCleanupId) { + public AccountGameplayAdmissionLeaseOperation { + Objects.requireNonNull(evidence); + Objects.requireNonNull(state); + if ((bindingDecisionId != null + && (bindingDecisionId.version() != 4 || bindingDecisionId.variant() != 2)) + || (orphanCleanupId != null + && (orphanCleanupId.version() != 4 || orphanCleanupId.variant() != 2))) { + throw new IllegalArgumentException("Canonical non-nil UUIDv4 terminal identity required"); + } + if ((state == State.PENDING && (bindingDecisionId != null || orphanCleanupId != null)) + || (state == State.COMMITTED && (bindingDecisionId == null || orphanCleanupId != null)) + || (state == State.ABORTED && (bindingDecisionId == null || orphanCleanupId == null))) { + throw new IllegalArgumentException("Incomplete admission operation storage state"); + } + } + + public enum State { + PENDING, + COMMITTED, + ABORTED + } + + /** ABORTED retains exact binding/token evidence as pending work, never completed cleanup. */ + public boolean hasPendingOrphanCleanup() { + return state == State.ABORTED; + } + + @Override + public String toString() { + return "AccountGameplayAdmissionLeaseOperation[state=" + state + "]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayPublicAdmissionSourceSnapshot.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayPublicAdmissionSourceSnapshot.java index 49ff41f2cd..f8a48195ba 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayPublicAdmissionSourceSnapshot.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayPublicAdmissionSourceSnapshot.java @@ -1,20 +1,24 @@ package net.firedevops.firemud.accountservice.dto; import java.util.Objects; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; /** * Immutable Account SQL sources captured for public fresh-admission owner work. * *

The values are valid only within the transaction that captured them. The token fence is - * persisted SQL state; it does not establish caller authentication, token cryptographic validity, + * persisted SQL state and the lifecycle enum is copied from the exact Account row. Neither carries + * caller authentication, token cryptographic validity, the separate safety-restriction projections, * registry state, or gameplay admission by itself. */ public record AccountGameplayPublicAdmissionSourceSnapshot( AccountMembershipRoleSourceSnapshot membershipSource, + AccountLifecycleState accountLifecycleState, DemoTenantEntitlementSnapshot entitlementSource, AccountGameplayTokenIdentityFence tokenIdentityFence) { public AccountGameplayPublicAdmissionSourceSnapshot { Objects.requireNonNull(membershipSource, "Current membership source is required"); + Objects.requireNonNull(accountLifecycleState, "Current Account lifecycle source is required"); Objects.requireNonNull(entitlementSource, "Current demo entitlement source is required"); Objects.requireNonNull(tokenIdentityFence, "Current SQL token fence is required"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java new file mode 100644 index 0000000000..183c061635 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java @@ -0,0 +1,311 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, non-admitting Account-owned storage foundation. No production caller exists. + * + *

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

SQL statement time guards expiry; this does not prove expiry at physical transaction COMMIT. + * ABORTED atomically retains the original full lease and exact orphan decision as pending cleanup; + * Account neither deletes Game Session state nor claims token retirement or cleanup delivery. + */ +public final class AccountGameplayAdmissionLeaseRepository { + private static final String OPERATIONS = "account_gameplay_admission_lease_operations"; + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private injected persistence context; the repository never exposes it") + public AccountGameplayAdmissionLeaseRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Fence domain is independent of issuance/token fences; retries retain the first allocation. */ + Allocation allocate(UUID accountId, UUID requestId, UUID leaseId) { + lockAccount(accountId); + requireUuidV4(requestId); + requireUuidV4(leaseId); + Record existing = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_lease_allocations WHERE request_id = ?", + requestId); + if (existing != null) { + Allocation prior = allocation(existing); + if (!prior.accountId().equals(accountId) + || !prior.requestId().equals(requestId) + || !prior.leaseId().equals(leaseId)) throw conflict(); + return prior; + } + dsl.execute( + "INSERT INTO account_gameplay_admission_lease_fences(account_uuid, last_fence) VALUES (?, 1) " + + "ON CONFLICT (account_uuid) DO UPDATE SET last_fence = " + + "account_gameplay_admission_lease_fences.last_fence + 1", + accountId); + Record counter = + dsl.fetchOne( + "SELECT last_fence FROM account_gameplay_admission_lease_fences WHERE account_uuid = ?", + accountId); + if (counter == null) { + throw new IllegalStateException("Account admission lease counter readback unavailable"); + } + Long fence = counter.get("last_fence", Long.class); + if (fence == null || fence <= 0L) { + throw new IllegalStateException("Account admission lease counter readback invalid"); + } + int inserted = + dsl.execute( + "INSERT INTO account_gameplay_admission_lease_allocations " + + "(account_uuid, request_id, lease_id, lease_fence) VALUES (?, ?, ?, ?)", + accountId, + requestId, + leaseId, + fence); + if (inserted != 1) { + throw new IllegalStateException("Account admission lease allocation insert unavailable"); + } + Allocation expected = new Allocation(accountId, requestId, leaseId, fence); + Record readback = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_lease_allocations WHERE request_id = ?", + requestId); + if (readback == null) { + throw new IllegalStateException("Account admission lease allocation readback unavailable"); + } + Allocation stored = allocation(readback); + if (!expected.equals(stored)) throw conflict(); + return stored; + } + + /** + * Recovers the original allocation after a lost response using only the original request. An + * empty result is storage absence only, never authoritative absence or no-token proof. + */ + Optional findAllocation(UUID accountId, UUID requestId) { + lockAccount(accountId); + requireUuidV4(requestId); + Record row = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_lease_allocations WHERE request_id = ?", + requestId); + if (row == null) return Optional.empty(); + Allocation stored = allocation(row); + if (!accountId.equals(stored.accountId()) || !requestId.equals(stored.requestId())) + throw conflict(); + return Optional.of(stored); + } + + /** + * Recovers validated original operation storage after a lost response. Workload equality is + * storage correlation only. An eventual facade must supply its concretely verified peer and + * compare current authorization and immutable client inputs before any externally usable retry. + * Empty storage is never admission, authoritative absence or no-token evidence. + */ + Optional findByRequest( + UUID accountId, UUID requestId, String expectedCallerWorkload) { + lockAccount(accountId); + requireUuidV4(requestId); + if (expectedCallerWorkload == null || expectedCallerWorkload.isBlank()) { + throw new IllegalArgumentException("Exact stored caller workload correlation required"); + } + Record row = select(requestId); + if (row == null) return Optional.empty(); + AccountGameplayAdmissionLeaseEvidence evidence = + AccountGameplayAdmissionLeaseEvidence.parseCanonical( + row.get("evidence_json", String.class)); + AccountGameplayAdmissionLeaseOperation stored = exact(row, evidence); + if (!accountId.equals(accountId(stored.evidence())) + || !requestId.equals(id(stored.evidence(), "requestId")) + || !expectedCallerWorkload.equals(stored.evidence().carrier().get("callerWorkload"))) { + throw conflict(); + } + return Optional.of(stored); + } + + /** Stores only the exact carrier for an already retained Account-owned allocation. */ + AccountGameplayAdmissionLeaseOperation beginPending( + AccountGameplayAdmissionLeaseEvidence evidence) { + Objects.requireNonNull(evidence); + UUID accountId = accountId(evidence); + lockAccount(accountId); + Allocation expected = + new Allocation( + accountId, + id(evidence, "requestId"), + id(evidence, "leaseId"), + evidence.leaseFence().longValueExact()); + Record allocated = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_lease_allocations WHERE request_id = ?", + expected.requestId()); + if (allocated == null || !expected.equals(allocation(allocated))) throw conflict(); + Record prior = select(expected.requestId()); + if (prior != null) return exact(prior, evidence); + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATIONS + + " (account_uuid, request_id, lease_id, lease_fence, caller_workload, evidence_json, " + + "evidence_sha256, evaluated_at_ms, expires_at_ms, status) " + + "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING' " + + "WHERE ? <= floor(extract(epoch FROM clock_timestamp()) * 1000) " + + "AND ? > floor(extract(epoch FROM clock_timestamp()) * 1000)", + accountId, + expected.requestId(), + expected.leaseId(), + expected.leaseFence(), + evidence.carrier().get("callerWorkload"), + evidence.canonicalJson(), + evidence.sha256(), + time(evidence, "evaluatedAt"), + time(evidence, "expiresAt"), + time(evidence, "evaluatedAt"), + time(evidence, "expiresAt")); + if (inserted != 1) throw new IllegalStateException("Admission lease storage deadline expired"); + return exact(select(expected.requestId()), evidence); + } + + /** Exact retry/readback retains the original state and deadline, including expired evidence. */ + Optional readExact( + AccountGameplayAdmissionLeaseEvidence evidence) { + Objects.requireNonNull(evidence); + lockAccount(accountId(evidence)); + Record stored = select(id(evidence, "requestId")); + return stored == null ? Optional.empty() : Optional.of(exact(stored, evidence)); + } + + AccountGameplayAdmissionLeaseOperation recordCommitted( + AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { + return terminal(evidence, State.COMMITTED, bindingDecisionId, null); + } + + AccountGameplayAdmissionLeaseOperation recordAborted( + AccountGameplayAdmissionLeaseEvidence evidence, + UUID bindingDecisionId, + UUID orphanCleanupId) { + requireUuidV4(orphanCleanupId); + return terminal(evidence, State.ABORTED, bindingDecisionId, orphanCleanupId); + } + + private AccountGameplayAdmissionLeaseOperation terminal( + AccountGameplayAdmissionLeaseEvidence evidence, State state, UUID decision, UUID cleanup) { + requireUuidV4(decision); + AccountGameplayAdmissionLeaseOperation prior = + readExact(evidence) + .orElseThrow( + () -> new IllegalStateException("Exact admission lease operation missing")); + if (prior.state() != State.PENDING) { + if (prior.state() != state + || !Objects.equals(prior.bindingDecisionId(), decision) + || !Objects.equals(prior.orphanCleanupId(), cleanup)) throw conflict(); + return prior; + } + int updated = + dsl.execute( + "UPDATE " + + OPERATIONS + + " SET status = ?, binding_decision_id = ?, orphan_cleanup_id = ? " + + "WHERE request_id = ? AND status = 'PENDING' " + + "AND (? = 'ABORTED' OR expires_at_ms > floor(extract(epoch FROM clock_timestamp()) * 1000))", + state.name(), + decision, + cleanup, + id(evidence, "requestId"), + state.name()); + if (updated != 1) throw new IllegalStateException("Admission lease storage deadline expired"); + return exact(select(id(evidence, "requestId")), evidence); + } + + private void lockAccount(UUID accountId) { + requireUuidV4(accountId); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_SERIALIZABLE) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException("Writable SERIALIZABLE Account transaction required"); + } + if (dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", accountId) + == null) throw new IllegalStateException("Account admission storage owner missing"); + } + + private Record select(UUID requestId) { + return dsl.fetchOne( + "SELECT * FROM " + OPERATIONS + " WHERE request_id = ? FOR UPDATE", requestId); + } + + private static AccountGameplayAdmissionLeaseOperation exact( + Record row, AccountGameplayAdmissionLeaseEvidence expected) { + if (row == null) throw new IllegalStateException("Admission lease storage readback missing"); + AccountGameplayAdmissionLeaseEvidence stored = + AccountGameplayAdmissionLeaseEvidence.parseCanonical( + row.get("evidence_json", String.class)); + if (!stored.sha256().equals(row.get("evidence_sha256", String.class)) + || !stored.hasSameIdentity(expected) + || !accountId(stored).equals(row.get("account_uuid", UUID.class)) + || !id(stored, "requestId").equals(row.get("request_id", UUID.class)) + || !id(stored, "leaseId").equals(row.get("lease_id", UUID.class)) + || !Long.valueOf(stored.leaseFence().longValueExact()) + .equals(row.get("lease_fence", Long.class)) + || !stored.carrier().get("callerWorkload").equals(row.get("caller_workload", String.class)) + || !Long.valueOf(time(stored, "evaluatedAt")).equals(row.get("evaluated_at_ms", Long.class)) + || !Long.valueOf(time(stored, "expiresAt")).equals(row.get("expires_at_ms", Long.class))) + throw conflict(); + return new AccountGameplayAdmissionLeaseOperation( + stored, + State.valueOf(row.get("status", String.class)), + row.get("binding_decision_id", UUID.class), + row.get("orphan_cleanup_id", UUID.class)); + } + + private static Allocation allocation(Record row) { + UUID account = row.get("account_uuid", UUID.class); + UUID request = row.get("request_id", UUID.class); + UUID lease = row.get("lease_id", UUID.class); + Long fence = row.get("lease_fence", Long.class); + requireUuidV4(account); + requireUuidV4(request); + requireUuidV4(lease); + if (fence == null || fence <= 0L) throw conflict(); + return new Allocation(account, request, lease, fence); + } + + private static UUID accountId(AccountGameplayAdmissionLeaseEvidence evidence) { + return UUID.fromString( + (String) ((java.util.Map) evidence.carrier().get("bindingScope")).get("accountId")); + } + + private static UUID id(AccountGameplayAdmissionLeaseEvidence evidence, String key) { + return UUID.fromString((String) evidence.carrier().get(key)); + } + + private static long time(AccountGameplayAdmissionLeaseEvidence evidence, String key) { + return Long.parseLong((String) evidence.carrier().get(key)); + } + + private static void requireUuidV4(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) + throw new IllegalArgumentException("Canonical non-nil UUIDv4 identity required"); + } + + private static IllegalStateException conflict() { + return new IllegalStateException("Exact admission operation identity conflict"); + } + + record Allocation(UUID accountId, UUID requestId, UUID leaseId, long leaseFence) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java index 821d30418a..7f910b7272 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java @@ -9,10 +9,14 @@ import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; import net.firedevops.firemud.accountservice.dto.AccountMembershipRoleSourceSnapshot; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountRepository; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -22,12 +26,13 @@ *

The caller must already own a writable Account transaction at REPEATABLE_READ or SERIALIZABLE * isolation. The membership reader supplies the first Account lock. This reader does not create a * transaction, write state, authenticate a caller or token, validate a signature or token registry, - * establish World ACTIVE/lifecycle, routing, coordination, grant, or deadline evidence, decide - * admission, or issue or commit an admission lease. Current SQL token-fence state is only one - * captured source and is not complete token authority. + * establish Account safety restrictions, World ACTIVE, routing, coordination, grant, or deadline + * evidence, decide admission, or issue or commit an admission lease. Current SQL token-fence state + * and Account lifecycle are only captured sources, not complete token authority or admission. */ public final class AccountGameplayPublicAdmissionSourceReader { private final AccountMembershipRoleSourceReader membershipSources; + private final AccountRepository accounts; private final AccountDemoTenantEntitlementRepository entitlements; private final AccountGameplayTokenIdentityFenceRepository tokenFences; @@ -36,9 +41,11 @@ public final class AccountGameplayPublicAdmissionSourceReader { justification = "Injected Account owner sources are private transaction collaborators.") public AccountGameplayPublicAdmissionSourceReader( AccountMembershipRoleSourceReader membershipSources, + AccountRepository accounts, AccountDemoTenantEntitlementRepository entitlements, AccountGameplayTokenIdentityFenceRepository tokenFences) { this.membershipSources = Objects.requireNonNull(membershipSources); + this.accounts = Objects.requireNonNull(accounts); this.entitlements = Objects.requireNonNull(entitlements); this.tokenFences = Objects.requireNonNull(tokenFences); } @@ -58,6 +65,12 @@ public AccountGameplayPublicAdmissionSourceSnapshot readCurrent( AccountMembershipRoleSourceSnapshot membership = membershipSources.readCurrent(accountId, tenantId); requireMembership(membership, accountId, tenantId, identity); + Account account = + accounts + .findByAccountUuid(accountId) + .orElseThrow(AccountGameplayPublicAdmissionSourceReader::accountSourceUnavailable); + AccountLifecycleState accountLifecycleState = + requireAccountIdentityAndActiveLifecycle(account, membership, accountId); DemoTenantEntitlementSnapshot evaluated = entitlements.readCurrent(tenantId); require(evaluated != null, "Current demo entitlement source is unavailable"); @@ -74,7 +87,40 @@ public AccountGameplayPublicAdmissionSourceSnapshot readCurrent( && tokenFence.state() == State.ACTIVE, "Exact Account SQL token identity is not active"); - return new AccountGameplayPublicAdmissionSourceSnapshot(membership, current, tokenFence); + return new AccountGameplayPublicAdmissionSourceSnapshot( + membership, accountLifecycleState, current, tokenFence); + } + + private static AccountLifecycleState requireAccountIdentityAndActiveLifecycle( + Account account, AccountMembershipRoleSourceSnapshot membership, UUID accountId) { + var member = membership.membership(); + var accountSource = membership.issuerAccountSources().account(); + require( + accountId.equals(account.getAccountUuid()) + && account.getId() != null + && account.getId() > 0L + && account.getId() == member.accountRowId() + && Objects.equals(account.getId(), accountSource.accountSourceNumericId()) + && account.getAccountUuidProvenance() + == AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + && account.getAccountUuidProvenance() == member.accountIdentityProvenance() + && AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + .name() + .equals(accountSource.accountUuidProvenance()) + && account.getAccountUuidSourceNumericId() != null + && account.getAccountUuidSourceNumericId().equals(account.getId()) + && account.getAccountUuidSourceNumericId() == member.accountSourceNumericId(), + "Current Account lifecycle source is unavailable or inconsistent"); + AccountLifecycleState lifecycleState = account.getLifecycleState(); + require( + lifecycleState == AccountLifecycleState.ACTIVE, + "Current Account lifecycle does not allow gameplay admission"); + return lifecycleState; + } + + private static IllegalStateException accountSourceUnavailable() { + return new IllegalStateException( + "Current Account lifecycle source is unavailable or inconsistent"); } private static void requireMembership( diff --git a/services/account-service/src/main/resources/db/migration/V87__account_gameplay_admission_lease_operations.sql b/services/account-service/src/main/resources/db/migration/V87__account_gameplay_admission_lease_operations.sql new file mode 100644 index 0000000000..c2675aded2 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V87__account_gameplay_admission_lease_operations.sql @@ -0,0 +1,113 @@ +-- Storage foundation only. No row, fence or terminal status establishes authenticated admission. +-- The lease fence is an independent per-Account domain, never an issuance/token fence. +CREATE TABLE account_gameplay_admission_lease_fences ( + account_uuid UUID PRIMARY KEY REFERENCES accounts(account_uuid) + CHECK (account_uuid::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + last_fence BIGINT NOT NULL CHECK (last_fence > 0) +); + +CREATE TABLE account_gameplay_admission_lease_allocations ( + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) + CHECK (account_uuid::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + request_id UUID PRIMARY KEY CHECK (request_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + lease_id UUID NOT NULL UNIQUE CHECK (lease_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + lease_fence BIGINT NOT NULL CHECK (lease_fence > 0), + UNIQUE (account_uuid, lease_fence), + UNIQUE (account_uuid, request_id, lease_id, lease_fence) +); + +CREATE TABLE account_gameplay_admission_lease_operations ( + account_uuid UUID NOT NULL, + request_id UUID PRIMARY KEY, + lease_id UUID NOT NULL UNIQUE, + lease_fence BIGINT NOT NULL, + caller_workload TEXT NOT NULL, + evidence_json TEXT NOT NULL CHECK (octet_length(evidence_json) BETWEEN 1 AND 65536), + evidence_sha256 VARCHAR(64) NOT NULL CHECK (evidence_sha256 ~ '^[0-9a-f]{64}$'), + evaluated_at_ms BIGINT NOT NULL CHECK (evaluated_at_ms > 0), + expires_at_ms BIGINT NOT NULL, + status VARCHAR(16) NOT NULL CHECK (status IN ('PENDING', 'COMMITTED', 'ABORTED')), + binding_decision_id UUID CHECK (binding_decision_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + orphan_cleanup_id UUID UNIQUE CHECK (orphan_cleanup_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + FOREIGN KEY (account_uuid, request_id, lease_id, lease_fence) + REFERENCES account_gameplay_admission_lease_allocations(account_uuid, request_id, lease_id, lease_fence), + CHECK (expires_at_ms > evaluated_at_ms AND expires_at_ms - evaluated_at_ms <= 15000), + CHECK ((status = 'PENDING' AND binding_decision_id IS NULL AND orphan_cleanup_id IS NULL) + OR (status = 'COMMITTED' AND binding_decision_id IS NOT NULL AND orphan_cleanup_id IS NULL) + OR (status = 'ABORTED' AND binding_decision_id IS NOT NULL AND orphan_cleanup_id IS NOT NULL)) +); + +-- PostgreSQL executes these exact digest and JSON identity constraints. The jOOQ/H2 schema +-- simulation cannot interpret their PostgreSQL expressions; omission from that simulation +-- does not replace physical PostgreSQL migration and negative-case proof. +-- [jooq ignore start] +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_lease_evidence_digest_check + CHECK (evidence_sha256 = encode(sha256(convert_to(evidence_json, 'UTF8')), 'hex')); +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_lease_evidence_identity_check + CHECK (COALESCE((evidence_json::jsonb ->> 'requestId') = request_id::text + AND (evidence_json::jsonb ->> 'leaseId') = lease_id::text + AND (evidence_json::jsonb ->> 'leaseFence') = lease_fence::text + AND (evidence_json::jsonb ->> 'callerWorkload') = caller_workload + AND (evidence_json::jsonb -> 'bindingScope' ->> 'accountId') = account_uuid::text + AND (evidence_json::jsonb ->> 'evaluatedAt') = evaluated_at_ms::text + AND (evidence_json::jsonb ->> 'expiresAt') = expires_at_ms::text, FALSE)); +-- [jooq ignore stop] + +-- ABORTED's immutable original evidence_json includes every exact orphan binding and token +-- coordinate. orphan_cleanup_id identifies durable PENDING work, not delivery/retirement success. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_admission_storage_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Account admission storage evidence cannot be removed' USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'account_gameplay_admission_lease_fences' THEN + PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF TG_OP = 'INSERT' THEN + IF NEW.last_fence <> 1 THEN RAISE EXCEPTION 'Lease fence must start at one' USING ERRCODE = '23514'; END IF; + ELSIF NEW.account_uuid IS DISTINCT FROM OLD.account_uuid OR NEW.last_fence <> OLD.last_fence + 1 THEN + RAISE EXCEPTION 'Lease fence must advance exactly once' USING ERRCODE = '23514'; + END IF; + ELSIF TG_TABLE_NAME = 'account_gameplay_admission_lease_allocations' THEN + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Lease allocation is immutable' USING ERRCODE = '23514'; + END IF; + PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF NOT EXISTS (SELECT 1 FROM account_gameplay_admission_lease_fences + WHERE account_uuid = NEW.account_uuid AND last_fence = NEW.lease_fence) THEN + RAISE EXCEPTION 'Lease allocation must bind current Account allocator' USING ERRCODE = '23514'; + END IF; + ELSE + IF TG_OP = 'INSERT' AND NEW.status <> 'PENDING' THEN + RAISE EXCEPTION 'Lease operation must start pending' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' AND (OLD.status <> 'PENDING' + OR (to_jsonb(NEW) - ARRAY['status', 'binding_decision_id', 'orphan_cleanup_id']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['status', 'binding_decision_id', 'orphan_cleanup_id'])) THEN + RAISE EXCEPTION 'Exact lease evidence and terminal decisions are immutable' USING ERRCODE = '23514'; + END IF; + IF (TG_OP = 'INSERT' OR NEW.status = 'COMMITTED') + AND (NEW.evaluated_at_ms > floor(extract(epoch FROM clock_timestamp()) * 1000) + OR NEW.expires_at_ms <= floor(extract(epoch FROM clock_timestamp()) * 1000)) THEN + RAISE EXCEPTION 'Lease operation storage deadline expired' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_admission_fence_guard BEFORE INSERT OR UPDATE OR DELETE + ON account_gameplay_admission_lease_fences FOR EACH ROW EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_allocation_guard BEFORE INSERT OR UPDATE OR DELETE + ON account_gameplay_admission_lease_allocations FOR EACH ROW EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_operation_guard BEFORE INSERT OR UPDATE OR DELETE + ON account_gameplay_admission_lease_operations FOR EACH ROW EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_fence_truncate_guard BEFORE TRUNCATE + ON account_gameplay_admission_lease_fences FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_allocation_truncate_guard BEFORE TRUNCATE + ON account_gameplay_admission_lease_allocations FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_operation_truncate_guard BEFORE TRUNCATE + ON account_gameplay_admission_lease_operations FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java new file mode 100644 index 0000000000..27376bea74 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -0,0 +1,512 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Real PostgreSQL definitions for non-admitting storage only. Carriers are fabricated shape + * fixtures, never authenticated source snapshots or evidence that a binding may be admitted. + */ +class AccountGameplayAdmissionLeasePersistenceIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + private static final String TENANT = "22222222-2222-4222-8222-222222222222"; + private static final String OTHER = "33333333-3333-4333-8333-333333333333"; + + @BeforeAll + static void start() { + POSTGRES.start(); + } + + @AfterAll + static void stop() { + POSTGRES.stop(); + } + + @Test + void lostResponseRecoveryUsesOriginalRequestWithoutReconstructingServerLeaseIdentity() { + var context = context(null); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + var allocation = tx(context, () -> repository.allocate(account, request, lease)); + assertThat(tx(context, () -> repository.findAllocation(account, request))).contains(allocation); + assertThat( + tx( + context, + () -> + repository.findByRequest( + account, request, "spiffe://firemud/ns/test/sa/game-session-service"))) + .isEmpty(); + var original = evidence(allocation); + var pending = tx(context, () -> repository.beginPending(original)); + assertThat( + tx( + context, + () -> + repository.findByRequest( + account, request, "spiffe://firemud/ns/test/sa/game-session-service"))) + .contains(pending); + UUID decision = UUID.randomUUID(); + var committed = tx(context, () -> repository.recordCommitted(original, decision)); + assertThat( + tx( + context, + () -> + repository.findByRequest( + account, request, "spiffe://firemud/ns/test/sa/game-session-service"))) + .contains(committed); + assertThat(tx(context, () -> repository.findAllocation(account, request))).contains(allocation); + UUID wrongAccount = account(context); + assertThatThrownBy(() -> tx(context, () -> repository.findAllocation(wrongAccount, request))) + .hasMessageContaining("identity conflict"); + assertThatThrownBy( + () -> + tx( + context, + () -> + repository.findByRequest( + wrongAccount, + request, + "spiffe://firemud/ns/test/sa/game-session-service"))) + .hasMessageContaining("identity conflict"); + assertThatThrownBy( + () -> + tx( + context, + () -> + repository.findByRequest( + account, request, "spiffe://firemud/ns/other/sa/game-session-service"))) + .hasMessageContaining("identity conflict"); + UUID missingRequest = UUID.randomUUID(); + assertThat(tx(context, () -> repository.findAllocation(account, missingRequest))).isEmpty(); + assertThat( + tx( + context, + () -> + repository.findByRequest( + account, + missingRequest, + "spiffe://firemud/ns/test/sa/game-session-service"))) + .isEmpty(); + assertThat(context.dsl().fetchCount(DSL.table("account_gameplay_admission_lease_allocations"))) + .isEqualTo(1); + } + + @Test + void freshMigrationStoresExactReplayAndRejectsChangedBaselineDigestOrAllocation() { + var context = context(null); + UUID account = account(context); + var evidence = pending(context, account); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + assertThat(tx(context, () -> repository.beginPending(evidence)).evidence()).isEqualTo(evidence); + var changed = new LinkedHashMap<>(evidence.carrier()); + changed.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "INACTIVE", + "membershipVersion", + Map.of(TENANT, "1"), + "membershipAuthorityGeneration", + "1")); + var changedEvidence = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed); + assertThatThrownBy(() -> tx(context, () -> repository.beginPending(changedEvidence))) + .hasMessageContaining("identity conflict"); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_operations SET evidence_sha256 = ? WHERE request_id = ?", + "b".repeat(64), + UUID.fromString((String) evidence.carrier().get("requestId"))))) + .isInstanceOf(RuntimeException.class); + changed.put("requestId", UUID.randomUUID().toString()); + changed.put("leaseId", UUID.randomUUID().toString()); + var unallocated = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed); + assertThatThrownBy(() -> tx(context, () -> repository.beginPending(unallocated))) + .hasMessageContaining("identity conflict"); + var otherAllocation = + tx(context, () -> repository.allocate(account, UUID.randomUUID(), UUID.randomUUID())); + var substituted = new LinkedHashMap<>(evidence.carrier()); + substituted.put("leaseFence", Long.toString(otherAllocation.leaseFence())); + var substitutedEvidence = AccountGameplayAdmissionLeaseEvidence.fromCarrier(substituted); + assertThatThrownBy(() -> tx(context, () -> repository.beginPending(substitutedEvidence))) + .hasMessageContaining("identity conflict"); + var original = evidence(otherAllocation); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_gameplay_admission_lease_operations " + + "(account_uuid, request_id, lease_id, lease_fence, caller_workload, evidence_json, " + + "evidence_sha256, evaluated_at_ms, expires_at_ms, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING')", + account, + otherAllocation.requestId(), + otherAllocation.leaseId(), + otherAllocation.leaseFence(), + original.carrier().get("callerWorkload"), + original.canonicalJson(), + "b".repeat(64), + Long.parseLong((String) original.carrier().get("evaluatedAt")), + Long.parseLong((String) original.carrier().get("expiresAt"))))) + .isInstanceOf(RuntimeException.class); + } + + @Test + void retainedAccountMigrationPreservesAccountAndAddsIndependentFenceDomain() { + var context = context("84.4"); + UUID account = account(context); + migrate(context, null); + var first = pending(context, account); + var second = pending(context, account); + assertThat(first.leaseFence().longValueExact()).isEqualTo(1); + assertThat(second.leaseFence().longValueExact()).isEqualTo(2); + assertThat(context.dsl().fetchCount(DSL.table("accounts"))).isEqualTo(1); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_fences SET last_fence = 1 WHERE account_uuid = ?", + account))) + .isInstanceOf(RuntimeException.class); + for (String table : + List.of( + "account_gameplay_admission_lease_fences", + "account_gameplay_admission_lease_allocations", + "account_gameplay_admission_lease_operations")) { + assertThatThrownBy(() -> tx(context, () -> context.dsl().execute("DELETE FROM " + table))) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> tx(context, () -> context.dsl().execute("TRUNCATE " + table))) + .isInstanceOf(RuntimeException.class); + } + } + + @Test + void commitsExactDecisionAndAtomicallyRetainsAbortedOrphanIntentWithTerminalConflict() { + var context = context(null); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var committed = pending(context, account); + UUID decision = UUID.randomUUID(); + var result = tx(context, () -> repository.recordCommitted(committed, decision)); + assertThat(result.state()).isEqualTo(State.COMMITTED); + assertThat(tx(context, () -> repository.recordCommitted(committed, decision))) + .isEqualTo(result); + assertThatThrownBy( + () -> tx(context, () -> repository.recordCommitted(committed, UUID.randomUUID()))) + .hasMessageContaining("identity conflict"); + assertThatThrownBy( + () -> + tx(context, () -> repository.recordAborted(committed, decision, UUID.randomUUID()))) + .hasMessageContaining("identity conflict"); + var aborted = pending(context, account); + UUID cleanup = UUID.randomUUID(); + assertThatThrownBy( + () -> + tx( + context, + () -> { + repository.recordAborted(aborted, decision, cleanup); + throw new IllegalStateException("simulate transaction rollback"); + })) + .hasMessageContaining("rollback"); + assertThat(tx(context, () -> repository.readExact(aborted).orElseThrow()).state()) + .isEqualTo(State.PENDING); + var orphan = tx(context, () -> repository.recordAborted(aborted, decision, cleanup)); + assertThat(orphan.hasPendingOrphanCleanup()).isTrue(); + assertThat(orphan.evidence()).isEqualTo(aborted); + assertThat(orphan.orphanCleanupId()).isEqualTo(cleanup); + assertThat(tx(context, () -> repository.recordAborted(aborted, decision, cleanup))) + .isEqualTo(orphan); + assertThatThrownBy( + () -> tx(context, () -> repository.recordAborted(aborted, decision, UUID.randomUUID()))) + .hasMessageContaining("identity conflict"); + } + + @Test + void expiredPendingCannotCommitOrRenewButKeepsExactReadbackAndCanAbort() { + var context = context(null); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var evidence = pending(context, account); + tx(context, () -> context.dsl().fetchOne("SELECT pg_sleep(16)")); + assertThat(tx(context, () -> repository.beginPending(evidence)).evidence()).isEqualTo(evidence); + assertThatThrownBy( + () -> tx(context, () -> repository.recordCommitted(evidence, UUID.randomUUID()))) + .hasMessageContaining("deadline expired"); + var changed = new LinkedHashMap<>(evidence.carrier()); + long now = Instant.now().toEpochMilli(); + changed.put("evaluatedAt", Long.toString(now)); + changed.put("expiresAt", Long.toString(now + 15000)); + var renewed = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed); + assertThatThrownBy(() -> tx(context, () -> repository.beginPending(renewed))) + .hasMessageContaining("identity conflict"); + assertThat( + tx( + context, + () -> repository.recordAborted(evidence, UUID.randomUUID(), UUID.randomUUID())) + .state()) + .isEqualTo(State.ABORTED); + } + + @Test + void concurrentDuplicatesReplayOneAllocationAndDistinctRequestsAdvanceFence() throws Exception { + var context = context(null); + UUID account = account(context); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var start = new CountDownLatch(1); + Callable duplicate = + () -> { + if (!start.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("start timeout"); + return retrySerialization( + () -> tx(context, () -> repository.allocate(account, request, lease))); + }; + try (var executor = Executors.newFixedThreadPool(2)) { + var left = executor.submit(duplicate); + var right = executor.submit(duplicate); + start.countDown(); + assertThat(left.get(30, TimeUnit.SECONDS)).isEqualTo(right.get(30, TimeUnit.SECONDS)); + var a = + executor.submit( + () -> + retrySerialization( + () -> + tx( + context, + () -> + repository.allocate( + account, UUID.randomUUID(), UUID.randomUUID())))); + var b = + executor.submit( + () -> + retrySerialization( + () -> + tx( + context, + () -> + repository.allocate( + account, UUID.randomUUID(), UUID.randomUUID())))); + assertThat( + List.of( + a.get(30, TimeUnit.SECONDS).leaseFence(), + b.get(30, TimeUnit.SECONDS).leaseFence())) + .containsExactlyInAnyOrder(2L, 3L); + } + } + + private static T retrySerialization(Supplier action) { + for (int attempt = 0; ; attempt++) { + try { + return action.get(); + } catch (RuntimeException failure) { + Throwable cause = failure; + boolean serialization = false; + while (cause != null) { + if (cause instanceof java.sql.SQLException sql && "40001".equals(sql.getSQLState())) + serialization = true; + cause = cause.getCause(); + } + if (!serialization || attempt >= 4) throw failure; + } + } + } + + private static AccountGameplayAdmissionLeaseEvidence pending(Context context, UUID account) { + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + return tx( + context, + () -> { + var allocation = repository.allocate(account, UUID.randomUUID(), UUID.randomUUID()); + var evidence = evidence(allocation); + repository.beginPending(evidence); + return evidence; + }); + } + + private static AccountGameplayAdmissionLeaseEvidence evidence( + AccountGameplayAdmissionLeaseRepository.Allocation allocation) { + String account = allocation.accountId().toString(); + long now = Instant.now().toEpochMilli(); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("targetNamespace", "test"); + carrier.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + carrier.put("requestId", allocation.requestId().toString()); + carrier.put("leaseId", allocation.leaseId().toString()); + carrier.put("leaseFence", Long.toString(allocation.leaseFence())); + carrier.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, OTHER); + scope.put("accountId", account); + scope.put("tenantId", TENANT); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "1"); + carrier.put("bindingScope", scope); + carrier.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(TENANT, "1"), + "membershipAuthorityGeneration", + Map.of(TENANT, "1"), + "privateRealmGrantVersions", + List.of())); + carrier.put("issuanceFence", "7"); + carrier.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(TENANT, "1"), + "membershipAuthorityGeneration", + "1")); + carrier.put( + "outboxCheckpoints", + List.of( + "account/" + account, + "issuer/firemud-account-service", + "membership/" + account + "/" + TENANT, + "tenant/" + TENANT) + .stream() + .map( + suffix -> + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:" + suffix, + "outboxSequence", + "1")) + .toList()); + Map token = new LinkedHashMap<>(); + token.put("accountId", account); + for (String key : List.of("operationId", "issuanceRequestId", "tokenJti")) + token.put(key, OTHER); + token.put("tokenSHA256", "a".repeat(64)); + token.put("tokenProfile", "game-session-account-delegation"); + token.put("tokenGeneration", "1"); + token.put("issuanceFence", "7"); + token.put("tokenIdentityFence", "9"); + token.put("issuedAt", Long.toString(now / 1000 - 1)); + token.put("notBefore", Long.toString(now / 1000 - 1)); + token.put("expiresAt", Long.toString(now / 1000 + 300)); + carrier.put("tokenIdentityEvidence", token); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put("expiresAt", Long.toString(now + 15000)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private static UUID account(Context context) { + var authorities = new AccountAuthorityGenerationRepository(context.dsl()); + var sources = + new AccountAuthoritySourceEvidenceRepository( + context.dsl(), authorities, new AccountAuthorityOutboxRepository(context.dsl())); + return tx( + context, + () -> { + sources.initializeIssuerIfAbsent("firemud-account-service"); + var account = new Account(); + account.setUsername("lease-" + UUID.randomUUID()); + account.setEmail(UUID.randomUUID() + "@example.test"); + account.setPasswordHash("storage-fixture-only"); + account.setLoginAuthModes("PASSWORD"); + return new AccountRepository(context.dsl(), sources).save(account).getAccountUuid(); + }); + } + + private static Context context(String target) { + String schema = "admission_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = POSTGRES.dataSource(schema); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + var context = + new Context( + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES), + transaction, + dataSource, + schema); + migrate(context, target); + return context; + } + + private static void migrate(Context context, String target) { + var configuration = + Flyway.configure() + .dataSource(context.dataSource()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration"); + if (target != null) configuration.target(target); + configuration.load().migrate(); + } + + private static T tx(Context context, Supplier action) { + return context.transaction().execute(status -> action.get()); + } + + private record Context( + DSLContext dsl, + TransactionTemplate transaction, + DriverManagerDataSource dataSource, + String schema) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java index 3d4e539607..e635ca3662 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -58,10 +58,15 @@ import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; @@ -69,6 +74,8 @@ 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.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; @@ -82,9 +89,24 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation; import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository.TokenRevokedException; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +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.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository.Capture; +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.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountGameplayPublicAdmissionSourceReader; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountMembershipRoleSourceReader; import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource; import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; @@ -112,6 +134,8 @@ import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff; import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; @@ -130,6 +154,7 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.PostgreSQLContainer; @@ -141,6 +166,7 @@ class AccountGameplayDelegationIssuancePersistenceIntegrationTest { "FIREMUD_ACCOUNT_SIGNER_TEST_POSTGRES_URL"; private static final String CALLER_WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final String GAME_DESIGN_NAMESPACE = "account-gameplay-admission-proof"; private static final JsonMapper JSON = JsonMapper.builder().build(); private static final PostgreSQLContainer postgres = @@ -1025,6 +1051,180 @@ void durableExactRevocationIntentDeniesAdmissionAndCommitRecoveryWithoutRecreati .isEqualTo("PENDING"); } + // Source-capture proof only; this does not claim authenticated admission or lease issuance. + @Test + void capturesFreshPlayerDemoSourcesBesideTheExactCommittedSqlTokenIdentity() throws Exception { + AdmissionSourceFixture fixture = newAdmissionSourceFixture(); + + var membership = + inRepeatableReadTransaction( + fixture.harness().context(), + () -> + fixture + .membershipReader() + .readCurrent(fixture.harness().accountId(), fixture.tenantId())); + assertThat(membership.membership().lifecycleState()).isEqualTo("ACTIVE"); + assertThat(membership.membership().gameplayAdmissionAllowed()).isTrue(); + assertThat(membership.roles().roles()).containsExactly("player"); + assertThat(membership.membershipEvent().roles()).containsExactly("player"); + assertThat(membership.tenantSource().sourceEvidence()).isEqualTo(fixture.tenantEvidence()); + assertThat(membership.tenantSource().sourceEvidence().provenanceKind()) + .isEqualTo("NEW_GAME_ROW"); + + var captured = + inRepeatableReadTransaction( + fixture.harness().context(), + () -> + fixture + .admissionReader() + .readCurrent( + fixture.harness().accountId(), fixture.tenantId(), fixture.identity())); + assertThat(captured.membershipSource().membership()).isEqualTo(membership.membership()); + assertThat(captured.accountLifecycleState()).isEqualTo(AccountLifecycleState.ACTIVE); + assertThat(captured.entitlementSource().entitlementKind()).isEqualTo("NON_PAID_DEMO"); + assertThat(captured.entitlementSource().sourceEvidence()).isEqualTo(fixture.tenantEvidence()); + assertThat(captured.entitlementSource().gameplayAvailable()).isTrue(); + assertThat(captured.entitlementSource().allowNewGameplayBindings()).isTrue(); + assertThat(captured.tokenIdentityFence().state()).isEqualTo(State.ACTIVE); + assertThat(captured.tokenIdentityFence().identity()).isEqualTo(fixture.identity()); + + Record sqlFence = + Objects.requireNonNull( + fixture + .harness() + .dsl() + .fetchOne( + "SELECT account_uuid, operation_id, issuance_request_id, token_hash, " + + "token_jti, not_before_epoch_second, token_generation, issuance_fence, " + + "token_identity_fence, state " + + "FROM account_gameplay_token_identity_fences WHERE operation_id = ?", + fixture.identity().operationId()), + "the committed issuance must have an exact SQL token-fence row"); + assertThat(sqlFence.get("account_uuid", UUID.class)).isEqualTo(fixture.identity().accountId()); + assertThat(sqlFence.get("operation_id", UUID.class)) + .isEqualTo(fixture.identity().operationId()); + assertThat(sqlFence.get("issuance_request_id", UUID.class)) + .isEqualTo(fixture.identity().issuanceRequestId()); + assertThat(sqlFence.get("token_hash", String.class)) + .isEqualTo(fixture.identity().tokenSha256()); + assertThat(sqlFence.get("token_jti", UUID.class)).isEqualTo(fixture.identity().tokenJti()); + assertThat(sqlFence.get("not_before_epoch_second", Long.class)) + .isEqualTo(fixture.identity().notBeforeEpochSecond()); + assertThat(sqlFence.get("token_generation", Long.class)) + .isEqualTo(fixture.identity().tokenGeneration()); + assertThat(sqlFence.get("issuance_fence", Long.class)) + .isEqualTo(fixture.identity().issuanceFence()); + assertThat(sqlFence.get("token_identity_fence", Long.class)).isEqualTo(1L); + assertThat(sqlFence.get("state", String.class)).isEqualTo("ACTIVE"); + } + + @Test + void publicAdmissionSourceCaptureRejectsDurablePendingTokenRevocation() throws Exception { + AdmissionSourceFixture fixture = newAdmissionSourceFixture(); + UUID requestId = UUID.randomUUID(); + String digest = + AccountGameplayTokenIdentityFenceRepository.revocationDigest(fixture.identity(), requestId); + var pending = + inTransaction( + fixture.harness().context(), + () -> + fixture.tokenFences().beginRevocationIntent(fixture.identity(), requestId, digest)); + assertThat(pending.state()).isEqualTo(State.PENDING); + assertThat(pending.tokenIdentityFence()).isEqualTo(2L); + + assertThatThrownBy( + () -> + inRepeatableReadTransaction( + fixture.harness().context(), + () -> + fixture + .admissionReader() + .readCurrent( + fixture.harness().accountId(), + fixture.tenantId(), + fixture.identity()))) + .isInstanceOf(TokenRevokedException.class); + } + + @Test + void membershipRoleSnapshotMustStillMatchItsCommittedCurrentEvent() throws Exception { + AdmissionSourceFixture fixture = newAdmissionSourceFixture(); + inRepeatableReadTransaction( + fixture.harness().context(), + () -> { + var membership = + fixture + .memberships() + .findFreshMembershipForUpdate(fixture.harness().accountId(), fixture.tenantId()) + .orElseThrow(); + fixture + .roles() + .replaceCanonical( + membership, + fixture.harness().accountId(), + fixture.tenantId(), + fixture.provenance(), + membership.getMembershipVersion(), + List.of("builder", "player")); + return null; + }); + + assertThatThrownBy( + () -> + inRepeatableReadTransaction( + fixture.harness().context(), + () -> + fixture + .admissionReader() + .readCurrent( + fixture.harness().accountId(), + fixture.tenantId(), + fixture.identity()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Current Account membership/role SQL source is unavailable or inconsistent"); + } + + @Test + void publicAdmissionSourceCaptureRejectsARealEntitlementAuthorityAdvance() throws Exception { + AdmissionSourceFixture fixture = newAdmissionSourceFixture(); + var changedEntitlement = + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + fixture.tenantId(), + fixture.tenantEvidence().creationRequestId(), + fixture.tenantEvidence().requestDigest(), + fixture.entitlement().entitlementVersion(), + fixture.entitlement().tenantAuthorityGeneration(), + fixture.entitlement().tenantAuthoritySourceVersion(), + true, + true, + false, + true, + fixture.entitlement().quotas()); + var committedChange = + inTransaction( + fixture.harness().context(), + () -> fixture.entitlements().provision(changedEntitlement, fixture.tenantEvidence())); + assertThat(committedChange.tenantAuthorityGeneration()) + .isGreaterThan(fixture.entitlement().tenantAuthorityGeneration()); + assertThat(committedChange.allowNewGameplayBindings()).isFalse(); + + assertThatThrownBy( + () -> + inRepeatableReadTransaction( + fixture.harness().context(), + () -> + fixture + .admissionReader() + .readCurrent( + fixture.harness().accountId(), + fixture.tenantId(), + fixture.identity()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Current public demo entitlement or fresh Game Design source is unavailable or denied"); + } + @Test void racingAdmissionWaitsForAccountRevocationTransactionThenObservesPendingFence() throws Exception { @@ -1146,6 +1346,199 @@ void concurrentDifferentAccountIssuerSnapshotsAndPendingIssuanceShareGlobalRows( } } + private AdmissionSourceFixture newAdmissionSourceFixture() throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.NONE, false); + assertThat(harness.service().commitPendingCandidate(harness.pending().requestId()).outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); + TokenIdentity identity = tokenFenceIdentity(harness); + + DSLContext dsl = harness.dsl(); + UUID tenantId = UUID.randomUUID(); + FreshTenantCreationEvidence tenantEvidence = freshAdmissionTenantEvidence(tenantId); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantEvidence.operationId(), + tenantEvidence.evidenceDigest()); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = harness.sources(); + FreshTenantIdentityAssociationRepository freshTenants = + new FreshTenantIdentityAssociationRepository(dsl, GAME_DESIGN_NAMESPACE); + AccountTenantEntitlementOutboxRepository billingOutbox = + new AccountTenantEntitlementOutboxRepository(dsl); + AccountTenantAuthorityEventRepository tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + dsl, outbox, billingOutbox, freshTenants, generations); + AccountDemoTenantEntitlementRepository entitlements = + new AccountDemoTenantEntitlementRepository( + dsl, freshTenants, generations, billingOutbox, tenantAuthorityEvents); + AccountGameplayTokenIdentityFenceRepository tokenFences = + new AccountGameplayTokenIdentityFenceRepository(dsl); + AccountRepository accounts = new AccountRepository(dsl, sources); + AccountMembershipPairAuthorityRepository pairs = + new AccountMembershipPairAuthorityRepository(dsl); + AccountTenantMembershipRepository memberships = + new AccountTenantMembershipRepository(dsl, accounts, freshTenants, pairs); + AccountTenantMembershipRoleSnapshotRepository roles = + new AccountTenantMembershipRoleSnapshotRepository(dsl); + + inTransaction( + harness.context(), + () -> { + freshTenants.importVerified(tenantEvidence); + sources.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + generations.initializeTenantIfAbsent(tenantId); + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + harness.accountId(), tenantId)); + return null; + }); + DemoTenantEntitlementRequest initialEntitlementRequest = + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + tenantId, + tenantEvidence.creationRequestId(), + tenantEvidence.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + DemoTenantEntitlementSnapshot entitlement = + inTransaction( + harness.context(), + () -> entitlements.provision(initialEntitlementRequest, tenantEvidence)); + + CanonicalJoinScopeV2 scope = canonicalAdmissionJoinScope(harness.accountId(), tenantId); + String requestId = UUID.randomUUID().toString(); + String callerBinding = "admission-source-owner-" + UUID.randomUUID(); + ApprovedLegacyTenantAssociationRepository legacyAssociations = + mock(ApprovedLegacyTenantAssociationRepository.class); + AccountTenantIdentityResolver tenantIdentityResolver = + new AccountTenantIdentityResolver(legacyAssociations, GAME_DESIGN_NAMESPACE); + AccountConnectScopeRepository connectScopes = + new AccountConnectScopeRepository(dsl, tenantIdentityResolver, freshTenants); + AccountJoinOperationRepository joinOperations = + new AccountJoinOperationRepository(dsl, connectScopes); + AccountMembershipAuthorityEventProducer membershipEvents = + new AccountMembershipAuthorityEventProducer( + joinOperations, accounts, pairs, memberships, roles, generations, outbox, sources); + AccountCanonicalFirstJoinTerminalCoordinator firstJoin = + new AccountCanonicalFirstJoinTerminalCoordinator( + accounts, + joinOperations, + memberships, + roles, + outbox, + pairs, + new AccountAuditOutboxRepository(dsl), + membershipEvents); + inTransaction( + harness.context(), + () -> { + long accountRowId = + Objects.requireNonNull( + accounts.findByAccountUuid(harness.accountId()).orElseThrow().getId()); + connectScopes.insertCanonical(accountRowId, scope, provenance); + joinOperations.insertCanonicalIntent(requestId, scope, callerBinding); + joinOperations.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, true, entitlement.entitlementVersion()); + firstJoin.commitCanonicalFirstJoin(scope, requestId, callerBinding); + return null; + }); + + AccountMembershipRoleSourceReader membershipReader = + new AccountMembershipRoleSourceReader( + sources, generations, memberships, pairs, roles, outbox, tenantAuthorityEvents); + AccountGameplayPublicAdmissionSourceReader admissionReader = + new AccountGameplayPublicAdmissionSourceReader( + membershipReader, accounts, entitlements, tokenFences); + return new AdmissionSourceFixture( + harness, + tenantId, + tenantEvidence, + provenance, + membershipReader, + admissionReader, + entitlements, + entitlement, + tokenFences, + memberships, + roles, + identity); + } + + private static FreshTenantCreationEvidence freshAdmissionTenantEvidence(UUID tenantId) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sourceTenantKey = + "admission-" + UUID.randomUUID().toString().replace("-", "").substring(0, 28); + String requestDigest = + GameTenantCreationDigest.requestDigest( + GAME_DESIGN_NAMESPACE, + requestId, + sourceTenantKey, + "Account admission source proof", + null); + long sourceGameRowId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + if (sourceGameRowId == 0L) sourceGameRowId = 1L; + String provenanceKind = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + GAME_DESIGN_NAMESPACE, + requestId, + operationId, + requestDigest, + tenantId, + sourceGameRowId, + sourceTenantKey, + provenanceKind, + GameTenantCreationDigest.evidenceDigest( + GAME_DESIGN_NAMESPACE, + requestId, + operationId, + requestDigest, + tenantId, + sourceGameRowId, + sourceTenantKey, + provenanceKind)); + } + + private static CanonicalJoinScopeV2 canonicalAdmissionJoinScope(UUID accountId, UUID tenantId) { + long evaluatedAtEpochSecond = Instant.now().getEpochSecond(); + String evaluatedAt = Instant.ofEpochSecond(evaluatedAtEpochSecond).toString(); + String expiresAt = Instant.ofEpochSecond(evaluatedAtEpochSecond + 120L).toString(); + return new CanonicalJoinScopeV2( + "admission-scope-" + UUID.randomUUID(), + accountId, + tenantId, + UUID.randomUUID(), + "tenant", + "world", + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 7L, + 3L, + evaluatedAt, + expiresAt); + } + + private static T inRepeatableReadTransaction( + TestContext context, java.util.function.Supplier operation) { + TransactionTemplate transaction = new TransactionTemplate(context.manager()); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + transaction.setReadOnly(false); + return transaction.execute(status -> operation.get()); + } + private static TokenIdentity tokenFenceIdentity(CommitHarness harness) { Record row = Objects.requireNonNull( @@ -2503,6 +2896,20 @@ private record CommitHarness( AccountGameplayCanonicalLoginOwner loginOwner, CanonicalGameplayLoginRequest loginRequest) {} + private record AdmissionSourceFixture( + CommitHarness harness, + UUID tenantId, + FreshTenantCreationEvidence tenantEvidence, + VerifiedTenantProvenance provenance, + AccountMembershipRoleSourceReader membershipReader, + AccountGameplayPublicAdmissionSourceReader admissionReader, + AccountDemoTenantEntitlementRepository entitlements, + DemoTenantEntitlementSnapshot entitlement, + AccountGameplayTokenIdentityFenceRepository tokenFences, + AccountTenantMembershipRepository memberships, + AccountTenantMembershipRoleSnapshotRepository roles, + TokenIdentity identity) {} + private static final class TransactionHookManager implements PlatformTransactionManager { private final PlatformTransactionManager delegate; private final AtomicReference beforeTargetTransaction = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java new file mode 100644 index 0000000000..10355449da --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java @@ -0,0 +1,264 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.startsWith; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Modifier; +import java.sql.Connection; +import java.util.Arrays; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Foundation storage proof; deliberately supplies no authenticated admission source. */ +class AccountGameplayAdmissionLeaseRepositoryTest { + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void remainsUnregisteredWithNoPublicMutationOrAuthorizationFacade() { + assertThat(AccountGameplayAdmissionLeaseRepository.class.isAnnotationPresent(Repository.class)) + .isFalse(); + assertThat( + Arrays.stream(AccountGameplayAdmissionLeaseRepository.class.getDeclaredMethods()) + .filter(method -> !method.isSynthetic()) + .anyMatch( + method -> + Modifier.isPublic(method.getModifiers()) + || Modifier.isProtected(method.getModifiers()))) + .isFalse(); + } + + @Test + void requiresWritableSerializableAccountTransactionBeforeReadingOrWriting() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountGameplayAdmissionLeaseRepository(dsl); + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + assertThatThrownBy(() -> repository.allocate(account, request, lease)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.allocate(account, request, lease)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.allocate(account, request, lease)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + @Test + void rejectsNonV4AccountIdentityBeforeAnyStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountGameplayAdmissionLeaseRepository(dsl); + assertThatThrownBy( + () -> + repository.allocate( + UUID.fromString("11111111-1111-1111-8111-111111111111"), + UUID.randomUUID(), + UUID.randomUUID())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("UUIDv4"); + verifyNoInteractions(dsl); + } + + @Test + void missingCounterReadbackCannotPersistAnAllocation() { + assertCounterReadbackRejected(null, "unavailable"); + } + + @ParameterizedTest + @NullSource + @ValueSource(longs = {0L, -1L}) + void nullOrNonpositiveCounterCannotPersistAnAllocation(Long fence) { + Record counter = mock(Record.class); + when(counter.get("last_fence", Long.class)).thenReturn(fence); + assertCounterReadbackRejected(counter, "invalid"); + } + + @Test + void insertedAllocationMustBeReadBackBeforeItCanBeReturned() { + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + Record row = allocationRow(account, request, lease, 1L); + DSLContext dsl = allocationDsl(row, 1); + assertThat(new AccountGameplayAdmissionLeaseRepository(dsl).allocate(account, request, lease)) + .isEqualTo( + new AccountGameplayAdmissionLeaseRepository.Allocation(account, request, lease, 1L)); + } + + @Test + void missingInsertedAllocationReadbackIsNotReturnedAsAnInMemoryIdentity() { + DSLContext dsl = allocationDsl(null, 1); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseRepository(dsl) + .allocate(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())) + .hasMessage("Account admission lease allocation readback unavailable"); + } + + @ParameterizedTest + @ValueSource(ints = {0, 2}) + void allocationInsertRequiresExactlyOneStoredRow(int insertCount) { + DSLContext dsl = allocationDsl(null, insertCount); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseRepository(dsl) + .allocate(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())) + .hasMessage("Account admission lease allocation insert unavailable"); + } + + @ParameterizedTest + @ValueSource(strings = {"account_uuid", "request_id", "lease_id", "lease_fence"}) + void changedInsertedAllocationIdentityFailsClosed(String field) { + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + Record row = allocationRow(account, request, lease, 1L); + if (field.equals("lease_fence")) when(row.get(field, Long.class)).thenReturn(2L); + else when(row.get(field, UUID.class)).thenReturn(UUID.randomUUID()); + DSLContext dsl = allocationDsl(row, 1); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseRepository(dsl).allocate(account, request, lease)) + .hasMessageContaining("identity conflict"); + } + + @Test + void allocationRecoveryReturnsOnlyOriginalStoredIdentity() { + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + DSLContext dsl = recoveryDsl(allocationRow(account, request, lease, 17L)); + assertThat(new AccountGameplayAdmissionLeaseRepository(dsl).findAllocation(account, request)) + .contains( + new AccountGameplayAdmissionLeaseRepository.Allocation(account, request, lease, 17L)); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @ParameterizedTest + @ValueSource(strings = {"account_uuid", "request_id"}) + void allocationRecoveryRejectsDifferentStoredOwnerOrRequest(String field) { + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + Record row = allocationRow(account, request, UUID.randomUUID(), 1L); + when(row.get(field, UUID.class)).thenReturn(UUID.randomUUID()); + DSLContext dsl = recoveryDsl(row); + assertThatThrownBy( + () -> new AccountGameplayAdmissionLeaseRepository(dsl).findAllocation(account, request)) + .hasMessageContaining("identity conflict"); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void missingRecoveryRowsRemainEmptyStorageWithoutAllocating() { + DSLContext allocationDsl = recoveryDsl(null); + assertThat( + new AccountGameplayAdmissionLeaseRepository(allocationDsl) + .findAllocation(UUID.randomUUID(), UUID.randomUUID())) + .isEmpty(); + verify(allocationDsl, never()).execute(anyString(), any(Object[].class)); + DSLContext operationDsl = recoveryDsl(null); + assertThat( + new AccountGameplayAdmissionLeaseRepository(operationDsl) + .findByRequest( + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://firemud/ns/test/sa/game-session-service")) + .isEmpty(); + verify(operationDsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void operationRecoveryRejectsMalformedStoredCarrierWithoutWrites() { + Record row = mock(Record.class); + when(row.get("evidence_json", String.class)).thenReturn("{}"); + DSLContext dsl = recoveryDsl(row); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseRepository(dsl) + .findByRequest( + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://firemud/ns/test/sa/game-session-service")) + .isInstanceOf(IllegalArgumentException.class); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + private static Record allocationRow(UUID account, UUID request, UUID lease, Long fence) { + Record row = mock(Record.class); + when(row.get("account_uuid", UUID.class)).thenReturn(account); + when(row.get("request_id", UUID.class)).thenReturn(request); + when(row.get("lease_id", UUID.class)).thenReturn(lease); + when(row.get("lease_fence", Long.class)).thenReturn(fence); + return row; + } + + private static DSLContext allocationDsl(Record readback, int insertCount) { + DSLContext dsl = mock(DSLContext.class); + Record owner = mock(Record.class); + Record counter = mock(Record.class); + when(counter.get("last_fence", Long.class)).thenReturn(1L); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(owner, null, counter, readback); + when(dsl.execute( + startsWith("INSERT INTO account_gameplay_admission_lease_allocations "), + any(Object[].class))) + .thenReturn(insertCount); + serializableTransaction(); + return dsl; + } + + private static DSLContext recoveryDsl(Record readback) { + DSLContext dsl = mock(DSLContext.class); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(mock(Record.class), readback); + serializableTransaction(); + return dsl; + } + + private static void serializableTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + } + + /** Mocked storage failure only; this does not establish PostgreSQL or source authority proof. */ + private static void assertCounterReadbackRejected(Record counter, String failureKind) { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, null, counter); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + var repository = new AccountGameplayAdmissionLeaseRepository(dsl); + assertThatThrownBy( + () -> repository.allocate(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account admission lease counter readback " + failureKind); + verify(dsl, never()) + .execute( + startsWith("INSERT INTO account_gameplay_admission_lease_allocations "), + any(Object[].class)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java index f31b0d6f1e..8333d0f944 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java @@ -21,7 +21,9 @@ import net.firedevops.firemud.accountservice.dto.AccountMembershipRoleSourceSnapshot.MembershipSource; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; @@ -36,6 +38,7 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; import net.firedevops.firemud.accountservice.service.AccountGameplayPublicAdmissionSourceReader; import net.firedevops.firemud.accountservice.service.AccountMembershipRoleSourceReader; @@ -74,14 +77,58 @@ void composesExactExistingOwnerReadsInAccountFirstOrder() { AccountGameplayPublicAdmissionSourceSnapshot result = fixture.read(); assertThat(result.membershipSource()).isSameAs(fixture.membership); + assertThat(result.accountLifecycleState()).isEqualTo(AccountLifecycleState.ACTIVE); assertThat(result.entitlementSource()).isEqualTo(fixture.entitlement); assertThat(result.tokenIdentityFence()).isEqualTo(fixture.activeFence); - var ordered = inOrder(fixture.memberships, fixture.entitlements, fixture.tokenFences); + var ordered = + inOrder(fixture.memberships, fixture.accounts, fixture.entitlements, fixture.tokenFences); ordered.verify(fixture.memberships).readCurrent(ACCOUNT, TENANT); + ordered.verify(fixture.accounts).findByAccountUuid(ACCOUNT); ordered.verify(fixture.entitlements).readCurrent(TENANT); ordered.verify(fixture.entitlements).revalidate(fixture.entitlement); ordered.verify(fixture.tokenFences).requireActiveForUpdate(fixture.identity); - verifyNoMoreInteractions(fixture.memberships, fixture.entitlements, fixture.tokenFences); + verifyNoMoreInteractions( + fixture.memberships, fixture.accounts, fixture.entitlements, fixture.tokenFences); + } + + @Test + void nonActiveAccountLifecycleStatesDenyBeforeEntitlementOrTokenReads() { + for (AccountLifecycleState state : + List.of( + AccountLifecycleState.SECURITY_LOCKED, + AccountLifecycleState.DEACTIVATED_PENDING_DELETE, + AccountLifecycleState.DELETED)) { + Fixture fixture = new Fixture(); + fixture.account.setLifecycleState(state); + + assertThatThrownBy(fixture::read) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Current Account lifecycle does not allow gameplay admission"); + verifyNoInteractions(fixture.entitlements, fixture.tokenFences); + } + } + + @Test + void missingOrMismatchedPersistedAccountIdentityAndProvenanceDeny() { + List> changes = + List.of( + f -> when(f.accounts.findByAccountUuid(ACCOUNT)).thenReturn(Optional.empty()), + f -> f.account.setAccountUuid(UUID.randomUUID()), + f -> f.account.setId(99L), + f -> f.account.setAccountUuidProvenance(null), + f -> + f.account.setAccountUuidProvenance( + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT), + f -> f.account.setAccountUuidSourceNumericId(99L), + f -> f.account.setAccountUuidSourceNumericId(null)); + + for (Consumer change : changes) { + Fixture fixture = new Fixture(); + change.accept(fixture); + + assertDenied(fixture); + verifyNoInteractions(fixture.entitlements, fixture.tokenFences); + } } @Test @@ -191,7 +238,8 @@ void transactionAndIsolationGuardRunsBeforeAnyOwnerRead() { Fixture fixture = new Fixture(); invalidTransaction.accept(fixture); assertDenied(fixture); - verifyNoInteractions(fixture.memberships, fixture.entitlements, fixture.tokenFences); + verifyNoInteractions( + fixture.memberships, fixture.accounts, fixture.entitlements, fixture.tokenFences); TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( @@ -205,7 +253,8 @@ void onlyExactCanonicalAccountAndTenantSelectorsAreAccepted() { assertThatThrownBy( () -> fixture.reader.readCurrent(UUID.randomUUID(), TENANT, fixture.identity)) .isInstanceOf(IllegalArgumentException.class); - verifyNoInteractions(fixture.memberships, fixture.entitlements, fixture.tokenFences); + verifyNoInteractions( + fixture.memberships, fixture.accounts, fixture.entitlements, fixture.tokenFences); } @Test @@ -279,12 +328,15 @@ private static AccountMembershipRoleSourceSnapshot copyMember( private static final class Fixture { final AccountMembershipRoleSourceReader memberships = mock(AccountMembershipRoleSourceReader.class); + final AccountRepository accounts = mock(AccountRepository.class); final AccountDemoTenantEntitlementRepository entitlements = mock(AccountDemoTenantEntitlementRepository.class); final AccountGameplayTokenIdentityFenceRepository tokenFences = mock(AccountGameplayTokenIdentityFenceRepository.class); + final Account account = account(); final AccountGameplayPublicAdmissionSourceReader reader = - new AccountGameplayPublicAdmissionSourceReader(memberships, entitlements, tokenFences); + new AccountGameplayPublicAdmissionSourceReader( + memberships, accounts, entitlements, tokenFences); TokenIdentity identity = new TokenIdentity( ACCOUNT, @@ -303,11 +355,21 @@ private static final class Fixture { Fixture() { when(memberships.readCurrent(ACCOUNT, TENANT)).thenReturn(membership); + when(accounts.findByAccountUuid(ACCOUNT)).thenReturn(Optional.of(account)); when(entitlements.readCurrent(TENANT)).thenReturn(entitlement); when(entitlements.revalidate(entitlement)).thenReturn(entitlement); when(tokenFences.requireActiveForUpdate(identity)).thenReturn(activeFence); } + private static Account account() { + Account account = new Account(); + account.setId(4L); + account.setAccountUuid(ACCOUNT); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setAccountUuidSourceNumericId(4L); + return account; + } + AccountGameplayPublicAdmissionSourceSnapshot read() { return reader.readCurrent(ACCOUNT, TENANT, identity); } From 0d4ddb396faaa8d3d642acb0cffb25af470ddbc9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 09:01:39 +1300 Subject: [PATCH 03/16] Authenticate initial admission evidence and capture owned sources --- .../player-access-and-session.md | 8 +- ...layAdmissionInitialTokenAuthenticator.java | 269 +++++++++ ...ameplayAuthenticatedPublicSourceOwner.java | 185 +++++++ ...ionIssuancePersistenceIntegrationTest.java | 2 +- ...dmissionInitialTokenAuthenticatorTest.java | 509 ++++++++++++++++++ ...layAuthenticatedPublicSourceOwnerTest.java | 343 ++++++++++++ 6 files changed, 1313 insertions(+), 3 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticator.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticatedPublicSourceOwner.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticatorTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticatedPublicSourceOwnerTest.java 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 c54207568c..1d2d927995 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,11 +12,15 @@ The isolated Account candidate adds an unregistered same-transaction source read The shared admission-lease evidence value preserves the complete unchanged baseline, public-target tuple, ordered authority checkpoints, exact token metadata, caller workload, binding identity, absolute expiry and applicable resume/prior-generation fields. It is a bounded canonical shape/digest codec, not authenticated Account evidence or a lease issuer. Its tuple and baseline validation currently inherits the existing public-delegation validator's signed-long source range; unsupported values are denied rather than substituted. Billing cutoff evidence refers to the tenant authority stream; the demo entitlement's separate availability receipt is not invented as another authority checkpoint. +The unregistered initial-token authenticator verifies the concrete same-namespace Game Session peer, the real asymmetric signature and initial unscoped profile, and exact current committed-issuance evidence through the existing SQL/Redis owner before opening a source transaction. It compares the original token hash, signer, Account identity, issuance times, generation, fence and global authority rather than trusting a supplied workload string or a post-admission player context. The composed source owner then opens its own writable SERIALIZABLE transaction and compares the current Account sources with that candidate, preserving the target membership baseline independently of the initial token's empty membership map. Expiry before, during and after source capture denies the observation. Fifteen signed-token tests and eight composition tests cover the bounded seam; owner and transaction doubles do not prove live mTLS, PostgreSQL/Redis currentness or admission through physical commit. The observation is non-authorizing and must not be reused as a later acquire or finalization decision. + V87 adds unregistered Account-owned allocation and exact operation storage. Its independent per-Account lease fence and immutable request/lease identity are read back before returning; lost-response lookup recovers the original allocation and canonical operation by request without generating another identity. Writable SERIALIZABLE transactions lock Account first. Terminal storage preserves the original carrier and absolute deadline; `ABORTED` atomically retains an exact pending orphan-cleanup identity. Storage `COMMITTED` is not an authenticated finalization result. Workload equality is storage correlation, and empty lookup proves neither authoritative absence nor token retirement. The six PostgreSQL storage definitions cover fresh and retained-account migration, changed evidence, terminal conflicts, rollback, expiry, concurrent allocation and lost-response readback. Their carriers are explicitly fabricated shape fixtures, not admission authority. PostgreSQL-specific constraints remain enforced by the migration even where narrowly excluded from jOOQ's schema simulator. -This prerequisite does not supply protected acquire/finalize/abort/reconcile RPCs, authenticated target or token-registry verification, Account safety-restriction sources, pending-invalidation enforcement, physical COMMIT-time expiry proof, committed-binding orphan reconciliation or delivered cleanup, private-grant or paid-entitlement support, or executed PostgreSQL/fresh-image LOGIN → PLAY → LOOK proof. Construction of source capture, carrier or operation storage grants no admission, and the runtime path remains denied. The owning target contract is [Session Behavior](../../architecture/system-architecture-session-behavior.md), with Account's predicate and caller obligations in [Authentication](../../architecture/system-architecture-authentication.md). Local consolidated proof is recorded below; compilation and simulated schema generation do not establish physical PostgreSQL locks, migration execution or lease finalization. +This prerequisite does not supply protected acquire/finalize/abort/reconcile RPCs, authenticated target authority, Account safety-restriction sources, pending-invalidation enforcement, physical COMMIT-time expiry proof, committed-binding orphan reconciliation or delivered cleanup, private-grant or paid-entitlement support, or executed PostgreSQL/fresh-image LOGIN → PLAY → LOOK proof. In particular, no current Account-owned `platform_access_ban` producer/projection proves restriction absence; an `ACTIVE` lifecycle, an empty restriction lookup or the per-token fence cannot replace that source. Construction of source capture, carrier or operation storage grants no admission, and the runtime path remains denied. The owning target contract is [Session Behavior](../../architecture/system-architecture-session-behavior.md), with Account's predicate and caller obligations in [Authentication](../../architecture/system-architecture-authentication.md). Local consolidated proof is recorded below; compilation and simulated schema generation do not establish physical PostgreSQL locks, migration execution or lease finalization. + +The consolidated authentication/source/storage checkpoint executes 147 Common Security and 1,094 Account unit cases without failures or errors; three Account unit cases skip. Two non-database integration cases execute, while 134 integration cases skip without authorized local PostgreSQL infrastructure. Account and Common Security checks, integration-source compilation, formatting, static analysis, links and Markdown pass; the inherited migration/source stage also passed jOOQ generation. Skipped database definitions are not runtime or migration proof. -The consolidated storage/source checkpoint executes 147 Common Security and 1,071 Account unit cases without failures or errors; three Account unit cases skip. Two non-database integration cases execute, while 134 integration cases skip without authorized local PostgreSQL infrastructure. Account and Common Security checks, jOOQ generation, integration-source compilation, formatting, static analysis, links and Markdown are the selected local gates; skipped database definitions are not runtime or migration proof. +Exact-head CI run `37674706914` for `9e6bb64d29a6a38320d52accdce64382446596ed` reports six new lease-storage PostgreSQL cases executed and passed. Its Account HTML report contains 144 integration cases, four failures and four skips: all four new source-capture cases executed but failed during fixture setup because their tenant source key exceeded the existing 36-character owner bound. The corrected fixture retains that bound and the identity/digest assertions; its PostgreSQL rerun remains pending, and the new authentication/source composition has no executed database/Redis claim. The runner artifact identifies merge tree `335f663cdaad82f242bb94ad7ab714298ad2f4dd`; Account JUnit XML was unavailable, so these execution counts come from the Gradle HTML report and logs. The same run failed Game Session dependency resolution and World generated-gRPC compilation; those are distinct failures, with their underlying ownership not yet established. Aggregate CI is not green and this checkpoint is not merge-ready. ### Credential-Bound Account LOGIN Owner diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticator.java new file mode 100644 index 0000000000..45ec68e7bb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticator.java @@ -0,0 +1,269 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.util.HexFormat; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, read-only authentication of an initial Game Session Account delegation token. + * + *

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

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

JWT/JWKS and committed SQL/Redis authentication finish before this owner opens its SQL source + * transaction. Only the real Account source reader runs inside that transaction. Its captured + * sources are valid at that transaction alone; every later commit must revalidate. This does not + * supply platform_access_ban, World, restriction, deadline, lease, or physical commit proof. The + * absent platform_access_ban source keeps gameplay admission denied. + */ +public final class AccountGameplayAuthenticatedPublicSourceOwner { + private final AccountGameplayAdmissionInitialTokenAuthenticator authenticator; + private final AccountGameplayPublicAdmissionSourceReader sources; + private final TransactionTemplate sourceTransaction; + private final Clock clock; + + /** The timeout is trusted operational SQL configuration, never an authorization deadline. */ + public AccountGameplayAuthenticatedPublicSourceOwner( + AccountGameplayAdmissionInitialTokenAuthenticator authenticator, + AccountGameplayPublicAdmissionSourceReader sources, + PlatformTransactionManager transactionManager, + Clock clock, + int sourceReadTimeoutSeconds) { + this.authenticator = Objects.requireNonNull(authenticator); + this.sources = Objects.requireNonNull(sources); + this.clock = Objects.requireNonNull(clock); + if (sourceReadTimeoutSeconds <= 0) { + throw new IllegalArgumentException("Positive Account source transaction timeout is required"); + } + sourceTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + sourceTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + sourceTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + sourceTransaction.setReadOnly(false); + sourceTransaction.setTimeout(sourceReadTimeoutSeconds); + } + + /** Target tenant is only a subject-bound owner lookup selector, never caller authority. */ + public CurrentPublicSourceObservation observeCurrent(String compactJwt, UUID tenantId) { + try { + requireNoAmbientTransaction(); + if (tenantId == null || tenantId.version() != 4 || tenantId.variant() != 2) throw denied(); + var authenticated = authenticator.authenticateInitialToken(compactJwt); + var candidate = Objects.requireNonNull(authenticated).candidate(); + var pending = Objects.requireNonNull(candidate).identity(); + var authority = candidate.authoritySnapshot(); + if (!pending.accountId().equals(authority.accountId())) throw denied(); + TokenIdentity identity = + new TokenIdentity( + pending.accountId(), + pending.operationId(), + pending.requestId(), + candidate.tokenSha256(), + pending.tokenJti(), + pending.notBeforeEpochSecond(), + 1L, + authority.issuanceFence()); + requireTokenTime(candidate); + requireNoAmbientTransaction(); + CurrentPublicSourceObservation result = + sourceTransaction.execute( + status -> { + requireSourceTransaction(); + requireTokenTime(candidate); + var snapshot = sources.readCurrent(identity.accountId(), tenantId, identity); + requireMatchingSources(candidate, tenantId, identity, snapshot); + long capturedAt = requireTokenTime(candidate); + return new CurrentPublicSourceObservation( + identity, + pending.issuedAtEpochSecond(), + pending.expiresAtEpochSecond(), + snapshot, + capturedAt); + }); + // A delayed transaction completion must not return an already-expired observation. + requireTokenTime(candidate); + return Objects.requireNonNull(result); + } catch (RuntimeException failure) { + throw denied(); + } + } + + private static void requireMatchingSources( + CommittedCandidateVerificationData candidate, + UUID tenantId, + TokenIdentity identity, + AccountGameplayPublicAdmissionSourceSnapshot snapshot) { + var membership = Objects.requireNonNull(snapshot).membershipSource(); + var member = membership.membership(); + var current = membership.currentAuthority(); + var ownerSources = membership.issuerAccountSources(); + var signed = candidate.authoritySnapshot(); + var issuerScope = AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER); + var accountScope = AuthorityScope.account(identity.accountId()); + if (!identity.accountId().equals(member.accountId()) + || !tenantId.equals(member.tenantId()) + || snapshot.accountLifecycleState() != AccountLifecycleState.ACTIVE + || !issuerScope.equals(ownerSources.issuer().scope()) + || !accountScope.equals(ownerSources.account().scope()) + || !issuerScope.equals(current.issuer().scope()) + || !accountScope.equals(current.account().scope()) + || current.issuer().generation() != signed.issuerGeneration() + || current.account().generation() != signed.accountGeneration() + || ownerSources.issuer().generation() != signed.issuerGeneration() + || ownerSources.account().generation() != signed.accountGeneration() + || !ownerSources.account().accountSecurityCutoff().equals(signed.accountSecurityCutoff()) + || !identity.accountId().equals(current.issuanceFence().accountId()) + || current.issuanceFence().value() != identity.issuanceFence() + || !current.issuanceFence().equals(ownerSources.issuanceFence()) + || !current.issuanceFence().equals(ownerSources.account().issuanceFence()) + || !identity.equals(snapshot.tokenIdentityFence().identity()) + || snapshot.tokenIdentityFence().state() != State.ACTIVE + || snapshot.tokenIdentityFence().tokenIdentityFence() != 1L) { + throw denied(); + } + // The initial JWT's empty membershipVersion is not a target membership baseline. Preserve + // the reader's current membership, tenant/billing and source-event evidence unchanged. + } + + private long requireTokenTime(CommittedCandidateVerificationData candidate) { + var identity = candidate.identity(); + long now = clock.instant().getEpochSecond(); + if (now < identity.issuedAtEpochSecond() + || now < identity.notBeforeEpochSecond() + || now >= identity.expiresAtEpochSecond()) throw denied(); + return now; + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw denied(); + } + + private static void requireSourceTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_SERIALIZABLE) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw denied(); + } + } + + private static PublicSourceObservationException denied() { + return new PublicSourceObservationException(); + } + + public static final class PublicSourceObservationException extends SecurityException { + private PublicSourceObservationException() { + super("Current Account public source observation failed"); + } + } + + /** Immutable captured evidence; cannot authorize admission, minting, or a later SQL commit. */ + public record CurrentPublicSourceObservation( + TokenIdentity tokenIdentity, + long tokenIssuedAtEpochSecond, + long tokenExpiresAtEpochSecond, + AccountGameplayPublicAdmissionSourceSnapshot sourceSnapshot, + long capturedAtEpochSecond) { + public CurrentPublicSourceObservation { + Objects.requireNonNull(tokenIdentity); + Objects.requireNonNull(sourceSnapshot); + } + + @Override + public String toString() { + return "CurrentPublicSourceObservation[non-authorizing, redacted]"; + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java index e635ca3662..999212d481 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -1478,7 +1478,7 @@ private static FreshTenantCreationEvidence freshAdmissionTenantEvidence(UUID ten UUID requestId = UUID.randomUUID(); UUID operationId = UUID.randomUUID(); String sourceTenantKey = - "admission-" + UUID.randomUUID().toString().replace("-", "").substring(0, 28); + "admission-" + UUID.randomUUID().toString().replace("-", "").substring(0, 26); String requestDigest = GameTenantCreationDigest.requestDigest( GAME_DESIGN_NAMESPACE, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticatorTest.java new file mode 100644 index 0000000000..b5657e4550 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticatorTest.java @@ -0,0 +1,509 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.RSAKeyGenParameterSpec; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Focused signature/profile tests; owner evidence is mocked and is not DB/Redis runtime proof. */ +class AccountGameplayAdmissionInitialTokenAuthenticatorTest { + private static final Instant NOW = Instant.parse("2026-10-08T00:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final String NAMESPACE = "firemud-test"; + private static final String KID = "account-key-42"; + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID TOKEN_JTI = UUID.fromString("1a7c3d0c-ab15-4f86-b5af-9e29bc7d3543"); + private static final UUID OPERATION_ID = UUID.fromString("c5c31332-e560-41c8-a55a-97674e7a317c"); + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("e16fdce5-96eb-49e1-a9bd-3f429816cbf0"); + private static final String PEER_URI = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; + private static final GrpcPeerIdentity GAME_SESSION_PEER = + new GrpcPeerIdentity(PEER_URI, NAMESPACE, "game-session-service"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void acceptsCorrectlySignedInitialTokenAndExactCommittedMetadata() throws Exception { + Fixture fixture = fixture(Map.of(), null, KID); + + var observation = + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt())); + + assertThat(observation.candidate()).isSameAs(fixture.candidate()); + assertThat(observation.observedAtEpochSecond()).isEqualTo(NOW.getEpochSecond()); + assertThat(observation.toString()).doesNotContain(fixture.compactJwt()); + verify(fixture.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void rejectsAbsentPeerBeforeReadingJwksOrOwnerState() throws Exception { + Fixture fixture = fixture(Map.of(), null, KID); + + assertDenied( + () -> + withRootContext( + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + assertThat(fixture.jwksLoads().get()).isZero(); + verifyNoInteractions(fixture.owner()); + } + + @Test + void rejectsWrongPeerBeforeReadingJwksOrOwnerState() throws Exception { + Fixture fixture = fixture(Map.of(), null, KID); + GrpcPeerIdentity wrongService = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", + NAMESPACE, + "account-service"); + + assertDenied( + () -> + withPeer( + wrongService, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + assertThat(fixture.jwksLoads().get()).isZero(); + verifyNoInteractions(fixture.owner()); + } + + @Test + void rejectsInvalidSignatureOnOtherwiseValidInitialTokenBeforeOwnerRead() throws Exception { + Fixture fixture = fixture(Map.of(), null, KID); + String invalidSignature = corruptSignature(fixture.compactJwt()); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(invalidSignature))); + + assertThat(fixture.jwksLoads().get()).isEqualTo(1); + verifyNoInteractions(fixture.owner()); + } + + @Test + void rejectsWrongTrustedNamespaceBeforeReadingJwksOrOwnerState() throws Exception { + Fixture fixture = fixture(Map.of(), null, KID); + GrpcPeerIdentity otherNamespace = + new GrpcPeerIdentity( + "spiffe://firemud/ns/other-test/sa/game-session-service", + "other-test", + "game-session-service"); + + assertDenied( + () -> + withPeer( + otherNamespace, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + assertThat(fixture.jwksLoads().get()).isZero(); + verifyNoInteractions(fixture.owner()); + } + + @Test + void rejectsAValidlySignedTenantBoundTokenAtTheInitialOnlyPolicy() throws Exception { + String tenantId = "fb71a28c-b82f-4f79-9aaf-472324a0011e"; + Map tenantAuthority = new LinkedHashMap<>(initialAuthorityTuple()); + tenantAuthority.put("tenantAuthorityGeneration", Map.of(tenantId, "1")); + tenantAuthority.put("membershipAuthorityGeneration", Map.of(tenantId, "1")); + Map tenantClaims = + Map.of( + "tenantId", tenantId, + "authorityTuple", tenantAuthority, + "membershipVersion", Map.of(tenantId, "1")); + Fixture fixture = fixture(tenantClaims, null, KID); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + assertThat(fixture.jwksLoads().get()).isZero(); + verifyNoInteractions(fixture.owner()); + } + + @Test + void rejectsAnyRoleClaimsAtInitialAcquire() throws Exception { + Fixture fixture = fixture(Map.of("globalRoles", List.of("admin")), null, KID); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + verifyNoInteractions(fixture.owner()); + } + + @Test + void rejectsCompactHashThatDiffersFromCommittedCandidate() throws Exception { + Fixture fixture = fixture(Map.of(), "a".repeat(64), KID); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + verify(fixture.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void rejectsGenerationOrFenceClaimsThatDifferFromCommittedInitialState() throws Exception { + Fixture wrongGeneration = fixture(Map.of("tokenGeneration", "2"), null, KID); + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> + wrongGeneration + .authenticator() + .authenticateInitialToken(wrongGeneration.compactJwt()))); + verify(wrongGeneration.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + + Fixture wrongFence = fixture(Map.of("issuanceFence", "2"), null, KID); + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> + wrongFence.authenticator().authenticateInitialToken(wrongFence.compactJwt()))); + verify(wrongFence.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void rejectsAuthorityTupleThatDoesNotMatchCommittedGlobalVersions() throws Exception { + Map differentAuthority = + GameSessionAccountDelegationProfile.authorityTuple(2L, 1L); + Fixture fixture = fixture(Map.of("authorityTuple", differentAuthority), null, KID); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + verify(fixture.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void rejectsSignerIdentityOrDurableTimeMismatch() throws Exception { + Fixture wrongSigner = fixture(Map.of(), null, "different-key"); + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> + wrongSigner + .authenticator() + .authenticateInitialToken(wrongSigner.compactJwt()))); + verify(wrongSigner.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + + Fixture wrongExpiry = fixture(Map.of("exp", NOW.getEpochSecond() + 121L), null, KID); + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> + wrongExpiry + .authenticator() + .authenticateInitialToken(wrongExpiry.compactJwt()))); + verify(wrongExpiry.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void rejectsExpiredButOtherwiseValidSignedTokenBeforeOwnerRead() throws Exception { + long issuedAt = NOW.getEpochSecond() - 120L; + Fixture fixture = + fixture( + Map.of( + "iat", issuedAt, + "nbf", issuedAt, + "exp", NOW.getEpochSecond() - 1L), + null, + KID); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + verifyNoInteractions(fixture.owner()); + } + + @Test + void rejectsChangedSubjectAndAccountAgainstOriginalCandidateWithSameJtiAndPresentedHash() + throws Exception { + UUID otherAccountId = UUID.fromString("751eb539-3238-4aa6-b86c-15d037a765c3"); + Fixture fixture = + fixture( + Map.of("sub", otherAccountId.toString(), "accountId", otherAccountId.toString()), + null, + KID); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + assertThat(fixture.candidate().tokenSha256()).isEqualTo(sha256(fixture.compactJwt())); + verify(fixture.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void ownerFailureIsRedactedAndDenied() throws Exception { + Fixture fixture = fixture(Map.of(), null, KID); + when(fixture.owner().requireCurrentActiveCommittedCandidateByJti(any())) + .thenThrow(new IllegalStateException("storage detail must not escape")); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + verify(fixture.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void refusesAmbientSqlTransactionBeforeJwksOrOwnerAccess() throws Exception { + Fixture fixture = fixture(Map.of(), null, KID); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + assertThat(fixture.jwksLoads().get()).isZero(); + verifyNoInteractions(fixture.owner()); + } + + private static Fixture fixture( + Map claimOverrides, String storedHash, String committedSignerKid) + throws Exception { + KeyPair keyPair = rsa3072(); + AtomicInteger jwksLoads = new AtomicInteger(); + AccountPublicJwksCache.SourceIdentity sourceIdentity = sourceIdentity(); + byte[] jwks = jwks(KID, (RSAPublicKey) keyPair.getPublic()); + AccountPublicJwksCache cache = + new AccountPublicJwksCache( + () -> { + jwksLoads.incrementAndGet(); + return new AccountPublicJwksCache.PublicJwksSnapshot(sourceIdentity, jwks); + }, + sourceIdentity, + CLOCK, + Duration.ofSeconds(30)); + AccountAsymmetricJwtVerifier verifier = new AccountAsymmetricJwtVerifier(cache, CLOCK); + AccountGameplayDelegationCommittedIssuanceOwner owner = + mock(AccountGameplayDelegationCommittedIssuanceOwner.class); + + Map claims = initialClaims(); + claims.putAll(claimOverrides); + String compactJwt = sign(claims, keyPair); + AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + PEER_URI, + CALLER_CONTEXT_ID, + AccountGameplayCredentialRequestBindingFixture.binding(), + "b".repeat(64), + TOKEN_JTI, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.plusSeconds(120L).getEpochSecond()); + AccountAuthoritySnapshot authority = + new AccountAuthoritySnapshot(ACCOUNT_ID, 1L, 1L, 1L, 1L, 1L, 1L, Optional.empty()); + CommittedCandidateVerificationData candidate = mock(CommittedCandidateVerificationData.class); + when(candidate.identity()).thenReturn(identity); + when(candidate.authoritySnapshot()).thenReturn(authority); + when(candidate.tokenSha256()).thenReturn(storedHash == null ? sha256(compactJwt) : storedHash); + when(candidate.signerKid()).thenReturn(committedSignerKid); + when(candidate.signerGeneration()).thenReturn("42"); + when(owner.requireCurrentActiveCommittedCandidateByJti(any())).thenReturn(candidate); + + return new Fixture( + new AccountGameplayAdmissionInitialTokenAuthenticator(verifier, owner, NAMESPACE, CLOCK), + owner, + candidate, + compactJwt, + jwksLoads); + } + + private static Map initialClaims() { + Map claims = new LinkedHashMap<>(); + claims.put("iss", GameSessionAccountDelegationProfile.ISSUER); + claims.put("sub", ACCOUNT_ID.toString()); + claims.put("jti", TOKEN_JTI.toString()); + claims.put("accountId", ACCOUNT_ID.toString()); + claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); + claims.put("iat", NOW.getEpochSecond()); + claims.put("nbf", NOW.getEpochSecond()); + claims.put("exp", NOW.plusSeconds(120L).getEpochSecond()); + claims.put("tokenGeneration", "1"); + claims.put("authorityTuple", initialAuthorityTuple()); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", "1"); + return claims; + } + + private static Map initialAuthorityTuple() { + return GameSessionAccountDelegationProfile.authorityTuple(1L, 1L); + } + + private static AccountPublicJwksCache.SourceIdentity sourceIdentity() { + return new AccountPublicJwksCache.SourceIdentity( + "prod", + "prod-cluster-1", + "11111111-1111-4111-8111-111111111111", + "firemud-test", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "account-api-r1", + "https://kubernetes.example:6443", + "9".repeat(64)); + } + + private static byte[] jwks(String kid, RSAPublicKey key) { + String jwk = + "{\"keys\":[{\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\",\"kid\":\"" + + kid + + "\",\"n\":\"" + + encode(unsigned(key.getModulus())) + + "\",\"e\":\"" + + encode(unsigned(key.getPublicExponent())) + + "\"}]}"; + return jwk.getBytes(StandardCharsets.UTF_8); + } + + private static String sign(Map claims, KeyPair keyPair) throws Exception { + Map header = Map.of("alg", "RS256", "kid", KID, "typ", "JWT"); + String signingInput = + encode(JSON.writeValueAsBytes(header)) + + "." + + encode(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(claims))); + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(keyPair.getPrivate()); + signature.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + return signingInput + "." + encode(signature.sign()); + } + + private static byte[] unsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + if (bytes.length > 1 && bytes[0] == 0) { + return java.util.Arrays.copyOfRange(bytes, 1, bytes.length); + } + return bytes; + } + + private static String encode(byte[] bytes) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private static String sha256(String value) throws Exception { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.US_ASCII))); + } + + private static KeyPair rsa3072() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(new RSAKeyGenParameterSpec(3072, RSAKeyGenParameterSpec.F4)); + return generator.generateKeyPair(); + } + + private static void assertDenied(Runnable attempt) { + assertThatThrownBy(attempt::run) + .isInstanceOf( + AccountGameplayAdmissionInitialTokenAuthenticator.InitialTokenAuthenticationException + .class) + .hasNoCause() + .hasMessage("Initial Account token authentication failed"); + } + + private static T withPeer(GrpcPeerIdentity peer, java.util.function.Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + return withContext(context, action); + } + + private static T withRootContext(java.util.function.Supplier action) { + return withContext(Context.ROOT, action); + } + + private static T withContext(Context context, java.util.function.Supplier action) { + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static String corruptSignature(String compactJwt) { + String[] parts = compactJwt.split("\\.", -1); + byte[] signature = Base64.getUrlDecoder().decode(parts[2]); + signature[0] ^= 0x01; + return parts[0] + "." + parts[1] + "." + encode(signature); + } + + private record Fixture( + AccountGameplayAdmissionInitialTokenAuthenticator authenticator, + AccountGameplayDelegationCommittedIssuanceOwner owner, + CommittedCandidateVerificationData candidate, + String compactJwt, + AtomicInteger jwksLoads) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticatedPublicSourceOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticatedPublicSourceOwnerTest.java new file mode 100644 index 0000000000..f0114b0dc8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticatedPublicSourceOwnerTest.java @@ -0,0 +1,343 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Consumer; +import net.firedevops.firemud.accountservice.dto.AccountGameplayPublicAdmissionSourceSnapshot; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.service.AccountGameplayPublicAdmissionSourceReader; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionInitialTokenAuthenticator; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionInitialTokenAuthenticator.CurrentInitialTokenObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAuthenticatedPublicSourceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAuthenticatedPublicSourceOwner.PublicSourceObservationException; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.DefaultTransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner doubles prove composition only; signed-token and PostgreSQL/Redis proof are separate. */ +class AccountGameplayAuthenticatedPublicSourceOwnerTest { + private static final UUID ACCOUNT = UUID.randomUUID(); + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID OPERATION = UUID.randomUUID(); + private static final UUID REQUEST = UUID.randomUUID(); + private static final UUID JTI = UUID.randomUUID(); + private static final String TOKEN = "compact-secret-token"; + private static final long NOW = 1_800_000_000L; + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesBeforeOwnedWritableSerializableSnapshotAndPreservesSources() { + Fixture f = new Fixture(); + + var result = f.observe(); + + assertThat(f.events).containsExactly("authenticate", "begin", "source", "commit"); + assertThat(f.transactions.definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(f.transactions.definition.isReadOnly()).isFalse(); + assertThat(f.transactions.definition.getTimeout()).isEqualTo(3); + assertThat(result.tokenIdentity()).isEqualTo(f.identity); + assertThat(result.tokenIssuedAtEpochSecond()).isEqualTo(NOW - 5); + assertThat(result.tokenExpiresAtEpochSecond()).isEqualTo(NOW + 20); + assertThat(result.capturedAtEpochSecond()).isEqualTo(NOW); + assertThat(result.sourceSnapshot()).isSameAs(f.snapshot); + assertThat(result.toString()).contains("non-authorizing", "redacted").doesNotContain(TOKEN); + verify(f.sources).readCurrent(ACCOUNT, TENANT, f.identity); + // No comparison with the initial token's empty membershipVersion: current evidence is kept. + } + + @Test + void ambientTransactionRejectsBeforeAuthentication() { + Fixture f = new Fixture(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertDenied(f); + + verifyNoInteractions(f.authenticator, f.sources); + assertThat(f.events).isEmpty(); + } + + @Test + void authenticationFailureNeverStartsSourceTransaction() { + Fixture f = new Fixture(); + doThrow(new IllegalStateException(TOKEN)).when(f.authenticator).authenticateInitialToken(TOKEN); + + assertDenied(f); + + assertThat(f.events).isEmpty(); + verifyNoInteractions(f.sources); + } + + @Test + void rejectsWrongSubjectsTenantLifecycleGlobalGenerationFenceCutoffAndSqlIdentity() { + List> changes = + List.of( + f -> when(f.snapshot.membershipSource().membership().accountId()).thenReturn(TENANT), + f -> when(f.snapshot.membershipSource().membership().tenantId()).thenReturn(ACCOUNT), + f -> when(f.snapshot.accountLifecycleState()).thenReturn(AccountLifecycleState.DELETED), + f -> + when(f.snapshot.membershipSource().currentAuthority().issuer().generation()) + .thenReturn(2L), + f -> + when(f.snapshot.membershipSource().currentAuthority().account().generation()) + .thenReturn(2L), + f -> + when(f.snapshot.membershipSource().issuerAccountSources().issuer().generation()) + .thenReturn(2L), + f -> + when(f.snapshot.membershipSource().issuerAccountSources().account().generation()) + .thenReturn(2L), + f -> + when(f.snapshot.membershipSource().issuerAccountSources().account().scope()) + .thenReturn(AuthorityScope.account(TENANT)), + f -> + when(f.snapshot.membershipSource().currentAuthority().issuanceFence()) + .thenReturn(new IssuanceFence(ACCOUNT, 2, 2)), + f -> + when(f.snapshot + .membershipSource() + .issuerAccountSources() + .account() + .accountSecurityCutoff()) + .thenReturn(null), + f -> + when(f.snapshot.tokenIdentityFence()) + .thenReturn( + new AccountGameplayTokenIdentityFence( + new TokenIdentity( + ACCOUNT, OPERATION, REQUEST, "b".repeat(64), JTI, NOW - 5, 1, 1), + 1, + State.ACTIVE, + null, + null)), + f -> + when(f.snapshot.tokenIdentityFence()) + .thenReturn( + new AccountGameplayTokenIdentityFence( + f.identity, 2, State.PENDING, UUID.randomUUID(), "c".repeat(64)))); + for (Consumer change : changes) { + Fixture f = new Fixture(); + change.accept(f); + + assertDenied(f); + + assertThat(f.events).containsExactly("authenticate", "begin", "source", "rollback"); + } + } + + @Test + void changedApplicableAccountCutoffRejects() { + Fixture f = new Fixture(); + AccountAuthoritySnapshot signed = mock(AccountAuthoritySnapshot.class); + when(signed.accountId()).thenReturn(ACCOUNT); + when(signed.issuerGeneration()).thenReturn(1L); + when(signed.accountGeneration()).thenReturn(1L); + when(signed.issuanceFence()).thenReturn(1L); + when(signed.accountSecurityCutoff()) + .thenReturn( + Optional.of(mock(GameSessionAccountDelegationProfile.AccountSecurityCutoff.class))); + when(f.candidate.authoritySnapshot()).thenReturn(signed); + + assertDenied(f); + } + + @Test + void expiryBeforeSourceReadAndDuringReadRejects() { + Fixture before = new Fixture(); + when(before.clock.instant()).thenReturn(Instant.ofEpochSecond(NOW + 20)); + assertDenied(before); + verifyNoInteractions(before.sources); + + Fixture during = new Fixture(); + when(during.clock.instant()) + .thenReturn( + Instant.ofEpochSecond(NOW), + Instant.ofEpochSecond(NOW), + Instant.ofEpochSecond(NOW + 20)); + assertDenied(during); + assertThat(during.events).containsExactly("authenticate", "begin", "source", "rollback"); + } + + @Test + void expiryDuringTransactionCompletionRejectsReturnedObservation() { + Fixture f = new Fixture(); + when(f.clock.instant()) + .thenReturn( + Instant.ofEpochSecond(NOW), + Instant.ofEpochSecond(NOW), + Instant.ofEpochSecond(NOW), + Instant.ofEpochSecond(NOW + 20)); + + assertDenied(f); + + assertThat(f.events).containsExactly("authenticate", "begin", "source", "commit"); + } + + @Test + void unavailableSourcesAndIncorrectTransactionContextFailClosed() { + Fixture unavailable = new Fixture(); + doThrow(new IllegalStateException(TOKEN)) + .when(unavailable.sources) + .readCurrent(ACCOUNT, TENANT, unavailable.identity); + assertDenied(unavailable); + + Fixture missing = new Fixture(); + doReturn(null).when(missing.sources).readCurrent(ACCOUNT, TENANT, missing.identity); + assertDenied(missing); + + Fixture wrongIsolation = new Fixture(); + wrongIsolation.transactions.establishedIsolation = + TransactionDefinition.ISOLATION_READ_COMMITTED; + assertDenied(wrongIsolation); + verifyNoInteractions(wrongIsolation.sources); + } + + private static void assertDenied(Fixture f) { + assertThatThrownBy(f::observe) + .isInstanceOf(PublicSourceObservationException.class) + .hasMessage("Current Account public source observation failed") + .hasNoCause(); + } + + private static final class Fixture { + private final List events = new ArrayList<>(); + private final AccountGameplayAdmissionInitialTokenAuthenticator authenticator = + mock(AccountGameplayAdmissionInitialTokenAuthenticator.class); + private final AccountGameplayPublicAdmissionSourceReader sources = + mock(AccountGameplayPublicAdmissionSourceReader.class); + private final CommittedCandidateVerificationData candidate = + mock(CommittedCandidateVerificationData.class); + private final AccountGameplayPublicAdmissionSourceSnapshot snapshot = + mock(AccountGameplayPublicAdmissionSourceSnapshot.class, RETURNS_DEEP_STUBS); + private final Clock clock = mock(Clock.class); + private final RecordingTransactions transactions = new RecordingTransactions(events); + private final TokenIdentity identity = + new TokenIdentity(ACCOUNT, OPERATION, REQUEST, "a".repeat(64), JTI, NOW - 5, 1, 1); + private final AccountGameplayAuthenticatedPublicSourceOwner owner; + + private Fixture() { + when(clock.instant()).thenReturn(Instant.ofEpochSecond(NOW)); + var pending = mock(AccountGameplayDelegationPendingIdentity.class); + when(pending.accountId()).thenReturn(ACCOUNT); + when(pending.operationId()).thenReturn(OPERATION); + when(pending.requestId()).thenReturn(REQUEST); + when(pending.tokenJti()).thenReturn(JTI); + when(pending.issuedAtEpochSecond()).thenReturn(NOW - 5); + when(pending.notBeforeEpochSecond()).thenReturn(NOW - 5); + when(pending.expiresAtEpochSecond()).thenReturn(NOW + 20); + when(candidate.identity()).thenReturn(pending); + when(candidate.tokenSha256()).thenReturn("a".repeat(64)); + when(candidate.authoritySnapshot()) + .thenReturn(new AccountAuthoritySnapshot(ACCOUNT, 1, 1, 1, 1, 1, 1, Optional.empty())); + var observation = mock(CurrentInitialTokenObservation.class); + when(observation.candidate()).thenReturn(candidate); + when(authenticator.authenticateInitialToken(TOKEN)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + events.add("authenticate"); + return observation; + }); + when(snapshot.accountLifecycleState()).thenReturn(AccountLifecycleState.ACTIVE); + when(snapshot.membershipSource().membership().accountId()).thenReturn(ACCOUNT); + when(snapshot.membershipSource().membership().tenantId()).thenReturn(TENANT); + var issuerScope = AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER); + var accountScope = AuthorityScope.account(ACCOUNT); + var current = snapshot.membershipSource().currentAuthority(); + when(current.issuer().scope()).thenReturn(issuerScope); + when(current.account().scope()).thenReturn(accountScope); + when(current.issuer().generation()).thenReturn(1L); + when(current.account().generation()).thenReturn(1L); + var fence = new IssuanceFence(ACCOUNT, 1, 1); + when(current.issuanceFence()).thenReturn(fence); + var source = snapshot.membershipSource().issuerAccountSources(); + when(source.issuer().scope()).thenReturn(issuerScope); + when(source.account().scope()).thenReturn(accountScope); + when(source.issuer().generation()).thenReturn(1L); + when(source.account().generation()).thenReturn(1L); + when(source.account().accountSecurityCutoff()).thenReturn(Optional.empty()); + when(source.issuanceFence()).thenReturn(fence); + when(source.account().issuanceFence()).thenReturn(fence); + when(snapshot.tokenIdentityFence()) + .thenReturn(new AccountGameplayTokenIdentityFence(identity, 1, State.ACTIVE, null, null)); + when(sources.readCurrent(ACCOUNT, TENANT, identity)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + events.add("source"); + return snapshot; + }); + owner = + new AccountGameplayAuthenticatedPublicSourceOwner( + authenticator, sources, transactions, clock, 3); + } + + private AccountGameplayAuthenticatedPublicSourceOwner.CurrentPublicSourceObservation observe() { + return owner.observeCurrent(TOKEN, TENANT); + } + } + + private static final class RecordingTransactions implements PlatformTransactionManager { + private final List events; + private TransactionDefinition definition; + private int establishedIsolation = TransactionDefinition.ISOLATION_SERIALIZABLE; + + private RecordingTransactions(List events) { + this.events = events; + } + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + this.definition = definition == null ? new DefaultTransactionDefinition() : definition; + events.add("begin"); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(this.definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(establishedIsolation); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + events.add("commit"); + TransactionSynchronizationManager.clear(); + } + + @Override + public void rollback(TransactionStatus status) { + events.add("rollback"); + TransactionSynchronizationManager.clear(); + } + } +} From 475949f3ba86b1c8c024dfee12d143ef1f7e1c6a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 09:57:48 +1300 Subject: [PATCH 04/16] Prove fresh Account restriction sources and exact admission recovery --- .../account-service/api-contracts.md | 2 + design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 14 +- .../v1/account_gameplay_admission_lease.proto | 160 +++++++++ ...ccountGameplayAdmissionLeaseOperation.java | 7 +- ...AccountPlatformRestrictionBirthSource.java | 197 +++++++++++ ...ountAuthoritySourceEvidenceRepository.java | 8 +- ...countGameplayAdmissionLeaseRepository.java | 3 +- ...untPlatformRestrictionBirthRepository.java | 325 +++++++++++++++++ ...countMembershipAuthorityEventProducer.java | 42 ++- ...unt_platform_restriction_birth_sources.sql | 261 ++++++++++++++ ...count_admission_unknown_decision_abort.sql | 31 ++ ...issionLeasePersistenceIntegrationTest.java | 89 ++++- ...ionIssuancePersistenceIntegrationTest.java | 10 +- ...strictionBirthPostgresIntegrationTest.java | 328 ++++++++++++++++++ ...anonicalFirstJoinEventIntegrationTest.java | 82 ++++- ...untPlatformRestrictionBirthSourceTest.java | 110 ++++++ ...tGameplayAdmissionLeaseRepositoryTest.java | 48 +++ ...latformRestrictionBirthRepositoryTest.java | 174 ++++++++++ ...thorityEventProducerCanonicalJoinTest.java | 98 +++++- ...ccountGameplayAdmissionLeaseWireCodec.java | 119 +++++++ ...untGameplayAdmissionLeaseEvidenceTest.java | 2 +- ...ntGameplayAdmissionLeaseWireCodecTest.java | 238 +++++++++++++ 23 files changed, 2326 insertions(+), 27 deletions(-) create mode 100644 protos/account/v1/account_gameplay_admission_lease.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSource.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepository.java create mode 100644 services/account-service/src/main/resources/db/migration/V88__account_platform_restriction_birth_sources.sql create mode 100644 services/account-service/src/main/resources/db/migration/V89__account_admission_unknown_decision_abort.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSourceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepositoryTest.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseWireCodec.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseWireCodecTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 405163d842..5a226f3461 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -48,6 +48,8 @@ Account is the sole enforcement owner for the two global safety categories defin Every Account restriction transition (create, extend, expiry, removal, security recovery clearance, or correction) is an immutable monotonic revision keyed by exact `{accountId, category}`. The revision carries normalized scope, effective/expiry time, actor, case or security-event identity, source request, safe notice/reason, owner enforcement epoch, idempotency identity, and payload digest. Account atomically commits the revision, current projection, authority-generation effects, and idempotent result. Same-identity/same-digest retries replay; a changed digest conflicts; delayed or reordered revisions cannot resurrect older state. +Genuinely new Accounts receive explicit Account-owned nonrestricted birth evidence for both global categories automatically, in the same transaction as the proven Account insert, category revision/current projection, immutable result, authority generation/fence initialization and durable outbox. Exact readback binds the Account identity and fresh-insert provenance to that evidence; neither an `ACTIVE` lifecycle nor a missing category row proves nonrestriction. This enrollment must not apply to retained or unmapped Accounts, which remain denied until authoritative reconciliation proves their category state. Birth evidence and its captured generation/fence remain immutable historical evidence: independently advancing Account authority is captured and validated separately and does not rewrite or fabricate a category revision. Birth enrollment alone proves neither a later restriction transition nor its delivery, current authorization or gameplay admission. + For a moderation action or appeal outcome, Logging & Admin records durable intent first and sends one typed digest-bound command under [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md). Account independently validates current authorization and account facts, redeems its Account authorization reference when required, commits the local state and result, and returns the owner outcome. Logging & Admin does not own or mutate Account restriction tables and Account does not own the moderation appeal case. Account exposes only a safe denial category/next-step projection to players; protected evidence and moderator notes remain in Logging & Admin. This target contract is not complete in the current service. The existing `security_locked` lifecycle and auth foundations do not prove the separate punitive platform-ban lifecycle, revision/tombstone ordering, generation propagation, owner command/idempotency, recovery-clearance isolation, or end-to-end player-safe outcomes. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 2c080f2b81..f83e325ea4 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -61,3 +61,8 @@ Entry format: - Expected pattern: retain remote output and payload suppression while reporting trusted static phase, timeout versus nonzero exit, and secondary cleanup failure labels. - Current status: safe backup diagnostics are being added; fresh backup and isolated restore proof remain unavailable. Publishing and backup root causes are unresolved. - Reconsideration trigger: update the outcome after an authorized exact-phase failure capture and successful fresh backup/isolated restore verification; do not treat host health or a single successful SFTP listing as recovery proof. + +- `2026-10-08`: Keep migration simulation and Java fixture repairs narrow + - Observation: jOOQ's H2-backed DDL interpreter maps PostgreSQL `TEXT` to CLOB, which cannot be indexed there. Closed category/kind/state vocabulary and fixed-format stream keys can use appropriately bounded `VARCHAR` while retaining the actual PostgreSQL checks, foreign keys and triggers; simulator success is not physical migration proof. + - Expected pattern: build Mockito-returned fixtures before starting an outer `when(...).thenReturn(...)` call, because nested stubbing leaves that outer call unfinished. Give generic transaction readbacks an explicit typed local before overloaded AssertJ assertions, and check nullable fetched rows or fields explicitly rather than suppressing null-boundary warnings. + - Reconsideration trigger: apply these bounded patterns to the next migration or transaction-fixture change without broad constraint exclusions, weaker assertions or a new validator family. 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 1d2d927995..7e1ff8b5c8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -14,13 +14,19 @@ The shared admission-lease evidence value preserves the complete unchanged basel The unregistered initial-token authenticator verifies the concrete same-namespace Game Session peer, the real asymmetric signature and initial unscoped profile, and exact current committed-issuance evidence through the existing SQL/Redis owner before opening a source transaction. It compares the original token hash, signer, Account identity, issuance times, generation, fence and global authority rather than trusting a supplied workload string or a post-admission player context. The composed source owner then opens its own writable SERIALIZABLE transaction and compares the current Account sources with that candidate, preserving the target membership baseline independently of the initial token's empty membership map. Expiry before, during and after source capture denies the observation. Fifteen signed-token tests and eight composition tests cover the bounded seam; owner and transaction doubles do not prove live mTLS, PostgreSQL/Redis currentness or admission through physical commit. The observation is non-authorizing and must not be reused as a later acquire or finalization decision. -V87 adds unregistered Account-owned allocation and exact operation storage. Its independent per-Account lease fence and immutable request/lease identity are read back before returning; lost-response lookup recovers the original allocation and canonical operation by request without generating another identity. Writable SERIALIZABLE transactions lock Account first. Terminal storage preserves the original carrier and absolute deadline; `ABORTED` atomically retains an exact pending orphan-cleanup identity. Storage `COMMITTED` is not an authenticated finalization result. Workload equality is storage correlation, and empty lookup proves neither authoritative absence nor token retirement. The six PostgreSQL storage definitions cover fresh and retained-account migration, changed evidence, terminal conflicts, rollback, expiry, concurrent allocation and lost-response readback. Their carriers are explicitly fabricated shape fixtures, not admission authority. PostgreSQL-specific constraints remain enforced by the migration even where narrowly excluded from jOOQ's schema simulator. +V87 adds unregistered Account-owned allocation and exact operation storage. Its independent per-Account lease fence and immutable request/lease identity are read back before returning; lost-response lookup recovers the original allocation and canonical operation by request without generating another identity. Writable SERIALIZABLE transactions lock Account first. Terminal storage preserves the original carrier and absolute deadline; `ABORTED` atomically retains an exact pending orphan-cleanup identity. V89 permits an unknown decision identity on that aborted receipt, without fabricating a UUID or proving absence; an exact retry preserves the original presence or absence, and `COMMITTED` still requires a decision identity. Storage `COMMITTED` is not an authenticated finalization result. Workload equality is storage correlation, and empty lookup proves neither authoritative absence nor token retirement. The PostgreSQL storage definitions cover fresh and retained-account migration, changed evidence, terminal conflicts, rollback, expiry, concurrent allocation and lost-response readback. Their carriers are explicitly fabricated shape fixtures, not admission authority. PostgreSQL-specific constraints remain enforced by the migration even where narrowly excluded from jOOQ's schema simulator. -This prerequisite does not supply protected acquire/finalize/abort/reconcile RPCs, authenticated target authority, Account safety-restriction sources, pending-invalidation enforcement, physical COMMIT-time expiry proof, committed-binding orphan reconciliation or delivered cleanup, private-grant or paid-entitlement support, or executed PostgreSQL/fresh-image LOGIN → PLAY → LOOK proof. In particular, no current Account-owned `platform_access_ban` producer/projection proves restriction absence; an `ACTIVE` lifecycle, an empty restriction lookup or the per-token fence cannot replace that source. Construction of source capture, carrier or operation storage grants no admission, and the runtime path remains denied. The owning target contract is [Session Behavior](../../architecture/system-architecture-session-behavior.md), with Account's predicate and caller obligations in [Authentication](../../architecture/system-architecture-authentication.md). Local consolidated proof is recorded below; compilation and simulated schema generation do not establish physical PostgreSQL locks, migration execution or lease finalization. +The additive Account lease protobuf and Common Security wire codec wrap the existing canonical lease bytes and digest unchanged. Method-specific outcomes distinguish retained operations, domain denials and storage-only nonobservation; the wire does not register an RPC, authenticate a receipt or supply authorization. Unknown fields, malformed UTF-8, changed bytes/digest, unsupported counters and contradictory terminal presence are rejected. Game Session's separate exact lease-bound decision callback remains its owner boundary, not a pointer-read substitute. -The consolidated authentication/source/storage checkpoint executes 147 Common Security and 1,094 Account unit cases without failures or errors; three Account unit cases skip. Two non-database integration cases execute, while 134 integration cases skip without authorized local PostgreSQL infrastructure. Account and Common Security checks, integration-source compilation, formatting, static analysis, links and Markdown pass; the inherited migration/source stage also passed jOOQ generation. Skipped database definitions are not runtime or migration proof. +V88 and the actual fresh `AccountRepository.save` source initialization now create explicit birth-only category revisions, current projections, immutable results and distinct restriction outbox records in the same transaction as a genuinely new Account. The owner readback verifies the insert provenance, exact result identities and recomputed closed payload digests. Retained or unmapped Accounts are not enrolled. Historical birth generation/fence remains unchanged when unrelated current Account authority advances; current authority is read separately. This bounded source does not implement later moderation transitions or prove current protective-lock absence, and no admission path consumes it yet. PostgreSQL-specific completeness, immutability and digest guards remain active in the real migration; bounded fixed-vocabulary columns also support jOOQ generation. -Exact-head CI run `37674706914` for `9e6bb64d29a6a38320d52accdce64382446596ed` reports six new lease-storage PostgreSQL cases executed and passed. Its Account HTML report contains 144 integration cases, four failures and four skips: all four new source-capture cases executed but failed during fixture setup because their tenant source key exceeded the existing 36-character owner bound. The corrected fixture retains that bound and the identity/digest assertions; its PostgreSQL rerun remains pending, and the new authentication/source composition has no executed database/Redis claim. The runner artifact identifies merge tree `335f663cdaad82f242bb94ad7ab714298ad2f4dd`; Account JUnit XML was unavailable, so these execution counts come from the Gradle HTML report and logs. The same run failed Game Session dependency resolution and World generated-gRPC compilation; those are distinct failures, with their underlying ownership not yet established. Aggregate CI is not green and this checkpoint is not merge-ready. +The canonical first-JOIN producer now permits advanced tenant authority only after exact current Account-owned tenant event readback matches the captured generation, source version and fresh Game Design provenance. The genuine sequence-zero fresh tenant baseline and committed JOIN replay remain unchanged. A new PostgreSQL case provisions the real demo entitlement before the JOIN intent, binds its actual policy evidence and verifies the advanced event and exact retry; missing or substituted owner evidence remains denied. Definitions and unit collaborators are not physical execution proof. + +This prerequisite does not supply registered protected acquire/finalize/abort/reconcile RPCs, authenticated target authority, complete current safety-restriction transition enforcement, pending-invalidation enforcement, physical COMMIT-time expiry proof, committed-binding orphan reconciliation or delivered cleanup, private-grant or paid-entitlement support, or fresh-image LOGIN → PLAY → LOOK proof. Explicit fresh category birth evidence is not full current safety authority; an `ACTIVE` lifecycle, an empty restriction lookup or the per-token fence cannot substitute for the missing owner predicates. Construction of source capture, carrier or operation storage grants no admission, and the runtime path remains denied. The owning target contract is [Session Behavior](../../architecture/system-architecture-session-behavior.md), with Account's predicate and caller obligations in [Authentication](../../architecture/system-architecture-authentication.md). Local consolidated proof is recorded below; compilation and simulated schema generation do not establish physical PostgreSQL locks, migration execution or lease finalization. + +The consolidated authentication/source/storage/birth/wire correction gate passes Account and Common Security checks, integration-source compilation, formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown. Account executes 1,107 unit cases without failures or errors; three unit cases skip. Two non-database integration cases execute, while 144 integration cases skip without authorized local PostgreSQL infrastructure. The 155 Common Security cases passed on unchanged inputs and their outputs are reused by the final gate. Account jOOQ and protobuf generation pass; narrowly excluded PostgreSQL constraint functions still require physical database proof. Skipped definitions and simulated schema generation are not runtime or migration execution evidence. + +Exact-head CI run `37678981014` for `0d4ddb396faaa8d3d642acb0cffb25af470ddbc9` executed 1,094 Account unit cases without failures or errors, with three unit skips. Its JUnit reports contain 144 integration cases, four failures and four skips; all six lease-storage PostgreSQL cases passed. After the earlier tenant-key fixture correction, the four source-capture cases exposed a real first-JOIN owner gap: the producer rejected the tenant's actual provisioned authority `2/2` because it allowed only the fresh `1/1` baseline. The correction described above uses current owner-event proof rather than moving provisioning after JOIN or fabricating authority. Its PostgreSQL rerun and the new V88/V89 database cases remain pending. The runner merge is `70760de9e0b668f8b9022c89ddbfde168e9fe7dd` on the exact published base; World, Game Session and dev-tool validation passed. Prior run `37674706914` exposed the now-corrected 38-character fixture key and separate World compilation/Game Session resolution failures; the latter did not reproduce in the newer run, without an established root-cause attribution. Aggregate CI is not green and this checkpoint is not merge-ready. ### Credential-Bound Account LOGIN Owner diff --git a/protos/account/v1/account_gameplay_admission_lease.proto b/protos/account/v1/account_gameplay_admission_lease.proto new file mode 100644 index 0000000000..e94e7e7a7a --- /dev/null +++ b/protos/account/v1/account_gameplay_admission_lease.proto @@ -0,0 +1,160 @@ +syntax = "proto3"; + +package account.v1; + +import "shared/v1/errors.proto"; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Planned owner transport only; this schema registers no runtime admission surface. +// Exact same-namespace Game Session mTLS is required. Produced domain denials use typed +// outcomes; validation/authentication, dependency outages and other pre-domain failures use +// canonical non-OK gRPC status with bounded details, never an OK availability result. +service AccountGameplayAdmissionLeaseService { + rpc AcquirePublicGameplayAdmissionLease(AcquirePublicGameplayAdmissionLeaseRequest) + returns (AcquirePublicGameplayAdmissionLeaseResponse); + rpc FinalizeGameplayAdmissionLease(FinalizeGameplayAdmissionLeaseRequest) + returns (FinalizeGameplayAdmissionLeaseResponse); + rpc ReadGameplayAdmissionLease(ReadGameplayAdmissionLeaseRequest) + returns (ReadGameplayAdmissionLeaseResponse); + rpc AbortGameplayAdmissionLease(AbortGameplayAdmissionLeaseRequest) + returns (AbortGameplayAdmissionLeaseResponse); + rpc ReconcileGameplayAdmissionLease(ReconcileGameplayAdmissionLeaseRequest) + returns (ReconcileGameplayAdmissionLeaseResponse); +} + +message AcquirePublicGameplayAdmissionLeaseRequest { + string request_id = 1; + // Initial unscoped LOGIN delegation token, never an admitted PlayerExecutionContext. + // Account verifies the concrete peer and token before any owner SQL source transaction. + string initial_auth_token = 2; + PublicGameplayAdmissionCandidate candidate = 3; + GameplayAdmissionLeaseKind lease_kind = 4; + // Decimal counters retain exact precision; absence is distinct from a default value. + optional string expected_old_binding_generation = 5; + // Required with expected_old_binding_generation for RESUME; absent for NEW_BINDING. + // Presence of RESUME in this schema does not establish implemented resume authority. + optional string resume_episode_id = 6; +} + +enum GameplayAdmissionLeaseKind { + GAMEPLAY_ADMISSION_LEASE_KIND_UNSPECIFIED = 0; + GAMEPLAY_ADMISSION_LEASE_KIND_NEW_BINDING = 1; + GAMEPLAY_ADMISSION_LEASE_KIND_RESUME = 2; +} + +// Selectors and expected correlation only. Account must obtain protected actual target-owner +// evidence; caller values are never World, route, character, coordination or admission proof. +// Account derives the subject, peer, lease ID/fence/deadline and current Account predicates. +message PublicGameplayAdmissionCandidate { + string tenant_id = 1; + string world_slug = 2; + string realm_slug = 3; + string realm_id = 4; + string playable_state_namespace_id = 5; + string playable_state_scope = 6; + string game_instance_id = 7; + string character_id = 8; + string session_id = 9; + string binding_generation = 10; + string catalog_revision = 11; + string pointer_version = 12; + string region_id = 13; + string region_epoch = 14; +} + +// One unchanged closed AccountGameplayAdmissionLeaseEvidence carrier, not a second tuple schema. +// Bytes must be canonical UTF-8 JSON, nonempty and <=64 KiB. Digest is lowercase hexadecimal +// SHA-256 of those exact bytes. request_id must equal the carrier's original requestId. +// Shape/digest validation alone establishes no authenticated receipt or authorization. +message GameplayAdmissionLeaseReference { + string request_id = 1; + bytes evidence_canonical_json = 2; + string evidence_sha256 = 3; +} + +message FinalizeGameplayAdmissionLeaseRequest { + GameplayAdmissionLeaseReference lease = 1; + // Lookup selector only. Account obtains the exact lease-bound PROVISIONAL decision through + // Gameplay's protected CanonicalGameplayAdmissionDecisionOwner transport before finalizing. + string binding_decision_id = 2; +} + +message ReadGameplayAdmissionLeaseRequest { + string request_id = 1; + optional GameplayAdmissionLeaseReference expected_lease = 2; +} + +message AbortGameplayAdmissionLeaseRequest { + GameplayAdmissionLeaseReference lease = 1; + // Absent means no supplied observation/unknown, never proved absence. Never fabricate an ID. + optional string binding_decision_id = 2; +} + +message ReconcileGameplayAdmissionLeaseRequest { + string request_id = 1; + optional GameplayAdmissionLeaseReference expected_lease = 2; + optional string binding_decision_id = 3; +} + +enum GameplayAdmissionLeaseState { + GAMEPLAY_ADMISSION_LEASE_STATE_UNSPECIFIED = 0; + GAMEPLAY_ADMISSION_LEASE_STATE_PENDING = 1; + GAMEPLAY_ADMISSION_LEASE_STATE_COMMITTED = 2; + GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED = 3; +} + +// Reject unspecified/unknown states. COMMITTED requires the exact decision ID. ABORTED requires +// a retained cleanup ID but may have an unknown decision. PENDING has neither ID; COMMITTED has +// no cleanup ID. pending_orphan_cleanup is true exactly for ABORTED, not completed cleanup. +// Storage shape is not authenticated finalization; only the protected real owner supplies that. +message GameplayAdmissionLeaseOperationReadback { + GameplayAdmissionLeaseReference lease = 1; + GameplayAdmissionLeaseState state = 2; + optional string binding_decision_id = 3; + optional string orphan_cleanup_id = 4; + bool pending_orphan_cleanup = 5; +} + +// Storage observation only: never authoritative absence, token retirement, completed cleanup, +// or permission to start a replacement mutation after an uncertain original outcome. +message GameplayAdmissionLeaseNotObserved { + string request_id = 1; +} + +message AcquirePublicGameplayAdmissionLeaseResponse { + oneof outcome { + GameplayAdmissionLeaseOperationReadback operation = 1; + shared.v1.ErrorDetail denied = 2; + } +} + +message FinalizeGameplayAdmissionLeaseResponse { + oneof outcome { + GameplayAdmissionLeaseOperationReadback operation = 1; + shared.v1.ErrorDetail denied = 2; + } +} + +message ReadGameplayAdmissionLeaseResponse { + oneof outcome { + GameplayAdmissionLeaseOperationReadback operation = 1; + GameplayAdmissionLeaseNotObserved not_observed = 2; + } +} + +message AbortGameplayAdmissionLeaseResponse { + oneof outcome { + GameplayAdmissionLeaseOperationReadback operation = 1; + shared.v1.ErrorDetail denied = 2; + } +} + +message ReconcileGameplayAdmissionLeaseResponse { + oneof outcome { + GameplayAdmissionLeaseOperationReadback operation = 1; + GameplayAdmissionLeaseNotObserved not_observed = 2; + shared.v1.ErrorDetail denied = 3; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java index 97324a505a..11805e3eef 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java @@ -21,7 +21,7 @@ public record AccountGameplayAdmissionLeaseOperation( } if ((state == State.PENDING && (bindingDecisionId != null || orphanCleanupId != null)) || (state == State.COMMITTED && (bindingDecisionId == null || orphanCleanupId != null)) - || (state == State.ABORTED && (bindingDecisionId == null || orphanCleanupId == null))) { + || (state == State.ABORTED && orphanCleanupId == null)) { throw new IllegalArgumentException("Incomplete admission operation storage state"); } } @@ -32,7 +32,10 @@ public enum State { ABORTED } - /** ABORTED retains exact binding/token evidence as pending work, never completed cleanup. */ + /** + * ABORTED retains exact binding/token evidence as pending work, never completed cleanup. A null + * decision is unknown or unobserved, never authoritative proof that no decision exists. + */ public boolean hasPendingOrphanCleanup() { return state == State.ABORTED; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSource.java new file mode 100644 index 0000000000..e5f1b42d60 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSource.java @@ -0,0 +1,197 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; + +/** Exact owner-local fresh-birth evidence; this value grants no admission or activation. */ +public record AccountPlatformRestrictionBirthSource( + UUID accountId, + long accountSourceNumericId, + long accountInsertTransactionId, + ScopeState birthAuthority, + ScopeState currentAuthority, + CategorySource accountSecurityLock, + CategorySource platformAccessBan) { + public AccountPlatformRestrictionBirthSource { + Objects.requireNonNull(accountId, "Account UUID is required"); + if (accountId.version() != 4 + || accountId.variant() != 2 + || accountSourceNumericId <= 0 + || accountInsertTransactionId <= 0) { + throw new IllegalArgumentException("Exact fresh Account identity is required"); + } + requireAccountAuthority(accountId, birthAuthority); + requireAccountAuthority(accountId, currentAuthority); + if (birthAuthority.generation() != 1 + || birthAuthority.sourceVersion() != 1 + || birthAuthority.issuanceFence().value() != 1 + || birthAuthority.issuanceFence().sourceVersion() != 1) { + throw new IllegalArgumentException("Fresh birth requires the initial Account authority"); + } + requireCategory(accountId, accountSecurityLock, Category.ACCOUNT_SECURITY_LOCK); + requireCategory(accountId, platformAccessBan, Category.PLATFORM_ACCESS_BAN); + for (CategorySource source : new CategorySource[] {accountSecurityLock, platformAccessBan}) { + if (!source + .payloadDigest() + .equals( + birthDigest( + accountId, + accountSourceNumericId, + accountInsertTransactionId, + birthAuthority, + source.category(), + source.operationId(), + source.resultId(), + source.eventId()))) { + throw new IllegalArgumentException("Restriction birth payload digest differs"); + } + } + if (accountSecurityLock.operationId().equals(platformAccessBan.operationId()) + || accountSecurityLock.resultId().equals(platformAccessBan.resultId()) + || accountSecurityLock.eventId().equals(platformAccessBan.eventId())) { + throw new IllegalArgumentException("Category birth identities must be independent"); + } + } + + private static void requireAccountAuthority(UUID accountId, ScopeState authority) { + Objects.requireNonNull(authority, "Account authority is required"); + if (!AuthorityScope.account(accountId).equals(authority.scope()) + || authority.issuanceFence() == null + || !accountId.equals(authority.issuanceFence().accountId())) { + throw new IllegalArgumentException("Account authority identity differs"); + } + } + + private static void requireCategory(UUID accountId, CategorySource source, Category expected) { + Objects.requireNonNull(source, "Explicit category source is required"); + if (source.category() != expected + || !source.outboxStreamKey().equals(streamKey(accountId, expected))) { + throw new IllegalArgumentException("Exact category scope is required"); + } + } + + public static String streamKey(UUID accountId, Category category) { + return "account:restriction-birth:v1:" + accountId + "/" + category.storageValue(); + } + + /** + * Closed UTF-8 newline-separated birth preimage, with one final newline. Exact order: schema, + * account UUID, private numeric source ID, provenance, insert txid, category, source kind, + * restriction state, revision, enforcement epoch, birth generation, generation source version, + * fence, fence source version, operation ID, result ID, event ID, stream key, outbox sequence. + * Every variable field is a canonical UUID, positive decimal, or fixed closed vocabulary. + */ + public static String birthDigest( + UUID accountId, + long numericId, + long transactionId, + ScopeState birth, + Category category, + UUID operationId, + UUID resultId, + UUID eventId) { + String preimage = + String.join( + "\n", + "account-restriction-birth/v1", + accountId.toString(), + Long.toString(numericId), + "ACCOUNT_REPOSITORY_INSERT", + Long.toString(transactionId), + category.storageValue(), + "CATEGORY", + "NONRESTRICTED", + "1", + "1", + Long.toString(birth.generation()), + Long.toString(birth.sourceVersion()), + Long.toString(birth.issuanceFence().value()), + Long.toString(birth.issuanceFence().sourceVersion()), + operationId.toString(), + resultId.toString(), + eventId.toString(), + streamKey(accountId, category), + "1") + + "\n"; + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(preimage.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("Required SHA-256 digest is unavailable", unavailable); + } + } + + public enum Category { + ACCOUNT_SECURITY_LOCK("account_security_lock"), + PLATFORM_ACCESS_BAN("platform_access_ban"); + + private final String storageValue; + + Category(String storageValue) { + this.storageValue = storageValue; + } + + public String storageValue() { + return storageValue; + } + } + + public enum SourceKind { + CATEGORY + } + + public enum RestrictionState { + NONRESTRICTED + } + + /** A positive, explicit category revision/result, never inferred from absent rows. */ + public record CategorySource( + Category category, + SourceKind sourceKind, + RestrictionState restrictionState, + long revision, + long enforcementEpoch, + UUID operationId, + UUID resultId, + UUID eventId, + String payloadDigest, + String outboxStreamKey, + long outboxSequence) { + public CategorySource { + Objects.requireNonNull(category, "Category is required"); + Objects.requireNonNull(sourceKind, "Explicit source kind is required"); + Objects.requireNonNull(restrictionState, "Explicit restriction state is required"); + requireUuid(operationId); + requireUuid(resultId); + requireUuid(eventId); + if (payloadDigest == null || !payloadDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical restriction birth digest is required"); + } + Objects.requireNonNull(outboxStreamKey, "Restriction outbox stream is required"); + if (revision != 1 + || enforcementEpoch != 1 + || outboxSequence != 1 + || operationId.equals(resultId) + || operationId.equals(eventId) + || resultId.equals(eventId)) { + throw new IllegalArgumentException( + "Exact independent birth result and outbox are required"); + } + } + + private static void requireUuid(UUID value) { + Objects.requireNonNull(value, "Server-generated birth identity is required"); + if (value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Canonical version-four birth identity is required"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java index d6e461059f..34f9e93da8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java @@ -87,14 +87,20 @@ public CurrentSourceEvidence initializeIssuerIfAbsent(String exactIssuerId) { @Transactional(propagation = Propagation.MANDATORY) public void initializeFreshAccount(AccountRepository.FreshAccountInsert proof) { Objects.requireNonNull(proof, "fresh Account repository insert proof is required"); - initializeIssuerIfAbsent(ACCOUNT_ISSUER); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new SourceEvidenceUnavailableException(); + } long accountInsertTransactionId = requireFreshAccountReadback(proof); + initializeIssuerIfAbsent(ACCOUNT_ISSUER); ScopeState accountState = generations.initializeAccountForFreshRepositoryInsert(proof); insertFreshBaseline( AuthorityScope.account(proof.accountUuid()), accountState, new AccountIdentitySource(proof.accountId(), accountInsertTransactionId)); readCurrentSource(AuthorityScope.account(proof.accountUuid()), accountState); + new AccountPlatformRestrictionBirthRepository(dsl) + .initializeFreshAccount(proof, accountInsertTransactionId, accountState); } /** diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java index 183c061635..f9d314bdba 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java @@ -194,6 +194,7 @@ AccountGameplayAdmissionLeaseOperation recordCommitted( return terminal(evidence, State.COMMITTED, bindingDecisionId, null); } + /** A missing decision remains unknown; the original cleanup identity is always required. */ AccountGameplayAdmissionLeaseOperation recordAborted( AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId, @@ -204,7 +205,7 @@ AccountGameplayAdmissionLeaseOperation recordAborted( private AccountGameplayAdmissionLeaseOperation terminal( AccountGameplayAdmissionLeaseEvidence evidence, State state, UUID decision, UUID cleanup) { - requireUuidV4(decision); + if (state == State.COMMITTED || decision != null) requireUuidV4(decision); AccountGameplayAdmissionLeaseOperation prior = readExact(evidence) .orElseThrow( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepository.java new file mode 100644 index 0000000000..abb4585c1a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepository.java @@ -0,0 +1,325 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.Category; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.CategorySource; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.RestrictionState; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.SourceKind; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Fresh source prerequisite only. Retained Accounts and later moderation writes are not enrolled. + */ +@Repository +public class AccountPlatformRestrictionBirthRepository { + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = "Preserve required DSLContext; Spring must proxy this repository.") + public AccountPlatformRestrictionBirthRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** Called only after the existing fresh-insert capability and sequence-zero source readback. */ + @Transactional(propagation = Propagation.MANDATORY) + void initializeFreshAccount( + AccountRepository.FreshAccountInsert proof, long insertTransactionId, ScopeState birth) { + requireTransaction(); + Objects.requireNonNull(proof, "Fresh Account insert proof is required"); + Record account = lockAccount(proof.accountUuid()); + if (positive(account, "id") != proof.accountId() + || positive(account, "account_repository_insert_transaction_id") != insertTransactionId + || positive(account, "current_xid") != insertTransactionId + || !"active".equals(account.get("lifecycle_state", String.class))) { + throw new BirthSourceUnavailableException(); + } + ScopeState current = currentAuthority(proof.accountUuid()); + if (!current.equals(birth) + || birth.generation() != 1 + || birth.sourceVersion() != 1 + || birth.issuanceFence() == null + || birth.issuanceFence().value() != 1 + || birth.issuanceFence().sourceVersion() != 1) { + throw new BirthSourceUnavailableException(); + } + CategorySource lock = + insertCategory( + proof.accountUuid(), + proof.accountId(), + insertTransactionId, + birth, + Category.ACCOUNT_SECURITY_LOCK); + CategorySource ban = + insertCategory( + proof.accountUuid(), + proof.accountId(), + insertTransactionId, + birth, + Category.PLATFORM_ACCESS_BAN); + AccountPlatformRestrictionBirthSource expected = + new AccountPlatformRestrictionBirthSource( + proof.accountUuid(), proof.accountId(), insertTransactionId, birth, current, lock, ban); + if (!expected.equals(readCurrentBirthSource(proof.accountUuid()))) { + throw new BirthSourceUnavailableException(); + } + } + + /** + * Locks Account first and requires both explicit CATEGORY projections, exact immutable birth + * results and their distinct restriction outbox evidence. Missing or changed evidence denies. + * NONRESTRICTED is the historical birth result, not proof of current protective-lock absence. + * This source read does not authorize a player or manufacture an auth-authority event. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountPlatformRestrictionBirthSource readCurrentBirthSource(UUID accountId) { + requireTransaction(); + Record account = lockAccount(accountId); + ScopeState current = currentAuthority(accountId); + CategoryReadback lock = readCategory(accountId, Category.ACCOUNT_SECURITY_LOCK, account); + CategoryReadback ban = readCategory(accountId, Category.PLATFORM_ACCESS_BAN, account); + if (!lock.birthAuthority().equals(ban.birthAuthority())) { + throw new BirthSourceUnavailableException(); + } + try { + return new AccountPlatformRestrictionBirthSource( + accountId, + positive(account, "id"), + positive(account, "account_repository_insert_transaction_id"), + lock.birthAuthority(), + current, + lock.source(), + ban.source()); + } catch (IllegalArgumentException malformed) { + throw new BirthSourceUnavailableException(); + } + } + + private CategorySource insertCategory( + UUID accountId, long numericId, long transactionId, ScopeState birth, Category category) { + // No upsert or retry minting: this method is reachable only inside the exact new row's tx. + // Committed readback always returns the original retained identities. + UUID operationId = UUID.randomUUID(); + UUID resultId = UUID.randomUUID(); + UUID eventId = UUID.randomUUID(); + String stream = AccountPlatformRestrictionBirthSource.streamKey(accountId, category); + String digest = + AccountPlatformRestrictionBirthSource.birthDigest( + accountId, numericId, transactionId, birth, category, operationId, resultId, eventId); + int inserted = + dsl.execute( + "INSERT INTO account_platform_restriction_births (account_uuid, category, revision, " + + "enforcement_epoch, source_kind, restriction_state, operation_id, result_id, event_id, payload_digest, " + + "account_source_numeric_id, account_insert_transaction_id, account_generation, " + + "account_source_version, issuance_fence, fence_source_version) " + + "VALUES (?, ?, 1, 1, 'CATEGORY', 'NONRESTRICTED', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + accountId, + category.storageValue(), + operationId, + resultId, + eventId, + digest, + numericId, + transactionId, + birth.generation(), + birth.sourceVersion(), + birth.issuanceFence().value(), + birth.issuanceFence().sourceVersion()); + int projected = + dsl.execute( + "INSERT INTO account_platform_restriction_projections " + + "(account_uuid, category, revision, enforcement_epoch, result_id) VALUES (?, ?, 1, 1, ?)", + accountId, + category.storageValue(), + resultId); + int emitted = + dsl.execute( + "INSERT INTO account_platform_restriction_birth_outbox " + + "(account_uuid, category, revision, enforcement_epoch, operation_id, result_id, " + + "event_id, payload_digest, outbox_stream_key, outbox_sequence, source_kind, restriction_state) " + + "VALUES (?, ?, 1, 1, ?, ?, ?, ?, ?, 1, 'CATEGORY', 'NONRESTRICTED')", + accountId, + category.storageValue(), + operationId, + resultId, + eventId, + digest, + stream); + if (inserted != 1 || projected != 1 || emitted != 1) { + throw new BirthSourceUnavailableException(); + } + return new CategorySource( + category, + SourceKind.CATEGORY, + RestrictionState.NONRESTRICTED, + 1, + 1, + operationId, + resultId, + eventId, + digest, + stream, + 1); + } + + private CategoryReadback readCategory(UUID accountId, Category category, Record account) { + Record birth = + dsl.fetchOne( + "SELECT * FROM account_platform_restriction_births " + + "WHERE account_uuid = ? AND category = ? FOR SHARE", + accountId, + category.storageValue()); + Record projection = + dsl.fetchOne( + "SELECT * FROM account_platform_restriction_projections " + + "WHERE account_uuid = ? AND category = ? FOR SHARE", + accountId, + category.storageValue()); + Record event = + dsl.fetchOne( + "SELECT * FROM account_platform_restriction_birth_outbox " + + "WHERE account_uuid = ? AND category = ? FOR SHARE", + accountId, + category.storageValue()); + if (birth == null + || projection == null + || event == null + || positive(birth, "account_source_numeric_id") != positive(account, "id") + || positive(birth, "account_insert_transaction_id") + != positive(account, "account_repository_insert_transaction_id")) { + throw new BirthSourceUnavailableException(); + } + for (String field : + new String[] {"account_uuid", "category", "revision", "enforcement_epoch", "result_id"}) { + if (!Objects.equals(birth.get(field), projection.get(field)) + || !Objects.equals(birth.get(field), event.get(field))) { + throw new BirthSourceUnavailableException(); + } + } + for (String field : + new String[] { + "operation_id", "event_id", "payload_digest", "source_kind", "restriction_state" + }) { + if (!Objects.equals(birth.get(field), event.get(field))) { + throw new BirthSourceUnavailableException(); + } + } + if (!accountId.equals(birth.get("account_uuid", UUID.class)) + || !category.storageValue().equals(birth.get("category", String.class)) + || !"CATEGORY".equals(birth.get("source_kind", String.class)) + || !"NONRESTRICTED".equals(birth.get("restriction_state", String.class)) + || positive(birth, "revision") != 1 + || positive(birth, "enforcement_epoch") != 1 + || positive(event, "outbox_sequence") != 1 + || !AccountPlatformRestrictionBirthSource.streamKey(accountId, category) + .equals(event.get("outbox_stream_key", String.class))) { + throw new BirthSourceUnavailableException(); + } + try { + var fence = + new AccountAuthorityGenerationRepository.IssuanceFence( + accountId, + positive(birth, "issuance_fence"), + positive(birth, "fence_source_version")); + var authority = + new ScopeState( + AuthorityScope.account(accountId), + positive(birth, "account_generation"), + positive(birth, "account_source_version"), + fence); + if (authority.generation() != 1 + || authority.sourceVersion() != 1 + || fence.value() != 1 + || fence.sourceVersion() != 1) { + throw new BirthSourceUnavailableException(); + } + UUID operationId = birth.get("operation_id", UUID.class); + UUID resultId = birth.get("result_id", UUID.class); + UUID eventId = event.get("event_id", UUID.class); + if (operationId == null || resultId == null || eventId == null) { + throw new BirthSourceUnavailableException(); + } + return new CategoryReadback( + authority, + new CategorySource( + category, + SourceKind.CATEGORY, + RestrictionState.NONRESTRICTED, + 1, + 1, + operationId, + resultId, + eventId, + birth.get("payload_digest", String.class), + event.get("outbox_stream_key", String.class), + 1)); + } catch (IllegalArgumentException malformed) { + throw new BirthSourceUnavailableException(); + } + } + + private Record lockAccount(UUID accountId) { + if (accountId == null || accountId.version() != 4 || accountId.variant() != 2) { + throw new BirthSourceUnavailableException(); + } + Record account = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id, lifecycle_state, " + + "account_repository_insert_transaction_id, txid_current() AS current_xid " + + "FROM accounts WHERE account_uuid = ? FOR UPDATE", + accountId); + if (account == null + || !accountId.equals(account.get("account_uuid", UUID.class)) + || !AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + .name() + .equals(account.get("account_uuid_provenance", String.class)) + || positive(account, "id") != positive(account, "account_uuid_source_numeric_id")) { + throw new BirthSourceUnavailableException(); + } + positive(account, "account_repository_insert_transaction_id"); + return account; + } + + private ScopeState currentAuthority(UUID accountId) { + ScopeState state = + new AccountAuthorityGenerationRepository(dsl).read(AuthorityScope.account(accountId)); + if (state.issuanceFence() == null || !accountId.equals(state.issuanceFence().accountId())) { + throw new BirthSourceUnavailableException(); + } + return state; + } + + private static long positive(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0) throw new BirthSourceUnavailableException(); + return value; + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Restriction birth source requires an Account transaction"); + } + } + + private record CategoryReadback(ScopeState birthAuthority, CategorySource source) {} + + public static final class BirthSourceUnavailableException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public BirthSourceUnavailableException() { + super("Exact Account restriction birth source is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index b5bd710108..927cc9437e 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 @@ -32,6 +32,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 +60,7 @@ public class AccountMembershipAuthorityEventProducer { private final AccountAuthorityGenerationRepository authorityGenerationRepository; private final AccountAuthorityOutboxRepository authorityOutboxRepository; private final AccountAuthoritySourceEvidenceRepository sourceEvidenceRepository; + private final AccountTenantAuthorityEventRepository tenantAuthorityEventRepository; @SuppressFBWarnings( value = {"CT_CONSTRUCTOR_THROW", "EI_EXPOSE_REP2"}, @@ -73,7 +75,8 @@ public AccountMembershipAuthorityEventProducer( AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository, AccountAuthorityGenerationRepository authorityGenerationRepository, AccountAuthorityOutboxRepository authorityOutboxRepository, - AccountAuthoritySourceEvidenceRepository sourceEvidenceRepository) { + AccountAuthoritySourceEvidenceRepository sourceEvidenceRepository, + AccountTenantAuthorityEventRepository tenantAuthorityEventRepository) { this.joinOperationRepository = Objects.requireNonNull(joinOperationRepository); this.accountRepository = Objects.requireNonNull(accountRepository); this.pairAuthorityRepository = Objects.requireNonNull(pairAuthorityRepository); @@ -82,6 +85,7 @@ public AccountMembershipAuthorityEventProducer( this.authorityGenerationRepository = Objects.requireNonNull(authorityGenerationRepository); this.authorityOutboxRepository = Objects.requireNonNull(authorityOutboxRepository); this.sourceEvidenceRepository = Objects.requireNonNull(sourceEvidenceRepository); + this.tenantAuthorityEventRepository = Objects.requireNonNull(tenantAuthorityEventRepository); } /** @@ -171,7 +175,13 @@ public Checkpoint publishCanonicalFirstJoinMembershipChange( IssuerAccountSourceSnapshot sourceSnapshot = sourceEvidenceRepository.readCurrentIssuerAccountSources(ACCOUNT_JWT_ISSUER, accountUuid); requireCurrentAuthority( - authority, sourceSnapshot, account.getId(), accountUuid, tenantUuid, membership); + authority, + sourceSnapshot, + account.getId(), + accountUuid, + tenantUuid, + membership, + provenance); if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) { throw new IllegalStateException( "Canonical first JOIN cannot publish over retained membership-event history"); @@ -521,17 +531,14 @@ private void requireCurrentAuthority( long accountRowId, UUID accountUuid, UUID tenantUuid, - AccountTenantMembership membership) { + AccountTenantMembership membership, + VerifiedTenantProvenance provenance) { ScopeState member = only(snapshot.memberships(), "membership"); ScopeState tenant = only(snapshot.tenants(), "tenant"); + requireCurrentTenantAuthority(tenant, tenantUuid, provenance); 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 || !AuthorityScope.membership(accountUuid, tenantUuid).equals(member.scope()) || member.generation() != membership.getMembershipAuthorityGeneration() || !accountUuid.equals(snapshot.issuanceFence().accountId()) @@ -563,6 +570,25 @@ private void requireCurrentAuthority( } } + private void requireCurrentTenantAuthority( + ScopeState tenant, UUID tenantUuid, VerifiedTenantProvenance provenance) { + // The fresh association retains the original sequence-zero baseline. An advanced authority + // must instead be proved by Account's exact current entitlement and authenticated owner event. + if (tenant.generation() == 1L && tenant.sourceVersion() == 1L) { + return; + } + var current = tenantAuthorityEventRepository.readCurrentByTenant(tenantUuid); + if (current == null + || !tenantUuid.equals(current.tenantId()) + || current.tenantAuthorityGeneration() != tenant.generation() + || current.tenantAuthoritySourceVersion() != tenant.sourceVersion() + || !provenance.sourceOperationId().equals(current.sourceEvidence().operationId()) + || !provenance.digest().equals(current.sourceEvidence().evidenceDigest())) { + throw new IllegalStateException( + "Canonical first JOIN requires exact current Account, source, and tenant authority evidence"); + } + } + private static PairAuthority requirePositiveFirstJoinPair( PairAuthority pair, AccountTenantMembership membership) { if (!pair.membershipExists() diff --git a/services/account-service/src/main/resources/db/migration/V88__account_platform_restriction_birth_sources.sql b/services/account-service/src/main/resources/db/migration/V88__account_platform_restriction_birth_sources.sql new file mode 100644 index 0000000000..eb6d9daf0d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V88__account_platform_restriction_birth_sources.sql @@ -0,0 +1,261 @@ +-- Explicit birth-only CATEGORY evidence for genuinely new repository-created Accounts. +-- Historical birth generation/fence values are independent of current Account authority. +-- No retained enrollment, moderation mutation API, current-lock proof, or activation is added. +CREATE TABLE account_platform_restriction_births ( + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + category VARCHAR(32) NOT NULL, + revision BIGINT NOT NULL, + enforcement_epoch BIGINT NOT NULL, + source_kind VARCHAR(16) NOT NULL, + restriction_state VARCHAR(16) NOT NULL, + operation_id UUID NOT NULL UNIQUE, + result_id UUID NOT NULL UNIQUE, + event_id UUID NOT NULL UNIQUE, + payload_digest VARCHAR(64) NOT NULL, + account_source_numeric_id BIGINT NOT NULL REFERENCES accounts(id), + account_insert_transaction_id BIGINT NOT NULL, + account_generation BIGINT NOT NULL, + account_source_version BIGINT NOT NULL, + issuance_fence BIGINT NOT NULL, + fence_source_version BIGINT NOT NULL, + CONSTRAINT account_restriction_birth_pk PRIMARY KEY (account_uuid, category), + CONSTRAINT account_restriction_birth_category CHECK ( + category IN ('account_security_lock', 'platform_access_ban')), + CONSTRAINT account_restriction_birth_baseline CHECK ( + revision = 1 AND enforcement_epoch = 1 + AND source_kind = 'CATEGORY' AND restriction_state = 'NONRESTRICTED' + AND account_source_numeric_id > 0 AND account_insert_transaction_id > 0 + AND account_generation = 1 AND account_source_version = 1 + AND issuance_fence = 1 AND fence_source_version = 1), + CONSTRAINT account_restriction_birth_digest_shape CHECK ( + payload_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_restriction_birth_uuid_shape CHECK ( + account_uuid::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND result_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND event_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_restriction_birth_distinct_ids CHECK ( + operation_id <> result_id AND operation_id <> event_id AND result_id <> event_id), + CONSTRAINT account_restriction_birth_projection_identity UNIQUE ( + account_uuid, category, revision, enforcement_epoch, result_id), + CONSTRAINT account_restriction_birth_event_identity UNIQUE ( + account_uuid, category, revision, enforcement_epoch, operation_id, + result_id, event_id, payload_digest, source_kind, restriction_state) +); + +CREATE TABLE account_platform_restriction_projections ( + account_uuid UUID NOT NULL, + category VARCHAR(32) NOT NULL, + revision BIGINT NOT NULL CHECK (revision > 0), + enforcement_epoch BIGINT NOT NULL CHECK (enforcement_epoch > 0), + result_id UUID NOT NULL, + CONSTRAINT account_restriction_projection_pk PRIMARY KEY (account_uuid, category), + CONSTRAINT account_restriction_projection_exact_result FOREIGN KEY ( + account_uuid, category, revision, enforcement_epoch, result_id) + REFERENCES account_platform_restriction_births ( + account_uuid, category, revision, enforcement_epoch, result_id) +); + +CREATE TABLE account_platform_restriction_birth_outbox ( + account_uuid UUID NOT NULL, + category VARCHAR(32) NOT NULL, + revision BIGINT NOT NULL, + enforcement_epoch BIGINT NOT NULL, + operation_id UUID NOT NULL, + result_id UUID NOT NULL, + event_id UUID NOT NULL UNIQUE, + payload_digest VARCHAR(64) NOT NULL, + outbox_stream_key VARCHAR(160) NOT NULL UNIQUE, + outbox_sequence BIGINT NOT NULL, + source_kind VARCHAR(16) NOT NULL, + restriction_state VARCHAR(16) NOT NULL, + CONSTRAINT account_restriction_birth_outbox_pk PRIMARY KEY (account_uuid, category), + CONSTRAINT account_restriction_birth_outbox_stream CHECK ( + outbox_sequence = 1 + AND outbox_stream_key = + 'account:restriction-birth:v1:' || account_uuid::text || '/' || category), + CONSTRAINT account_restriction_birth_outbox_exact_result FOREIGN KEY ( + account_uuid, category, revision, enforcement_epoch, operation_id, + result_id, event_id, payload_digest, source_kind, restriction_state) + REFERENCES account_platform_restriction_births ( + account_uuid, category, revision, enforcement_epoch, operation_id, + result_id, event_id, payload_digest, source_kind, restriction_state) +); + +-- Closed UTF-8 preimage matches AccountPlatformRestrictionBirthSource.birthDigest exactly. +-- PostgreSQL proof must verify these checks; jOOQ's schema simulation does not execute them. +-- [jooq ignore start] +CREATE FUNCTION account_restriction_birth_digest( + birth account_platform_restriction_births) +RETURNS TEXT LANGUAGE SQL IMMUTABLE STRICT AS $$ + SELECT encode(sha256(convert_to( + concat_ws(E'\n', + 'account-restriction-birth/v1', + birth.account_uuid::text, + birth.account_source_numeric_id::text, + 'ACCOUNT_REPOSITORY_INSERT', + birth.account_insert_transaction_id::text, + birth.category, + birth.source_kind, + birth.restriction_state, + birth.revision::text, + birth.enforcement_epoch::text, + birth.account_generation::text, + birth.account_source_version::text, + birth.issuance_fence::text, + birth.fence_source_version::text, + birth.operation_id::text, + birth.result_id::text, + birth.event_id::text, + 'account:restriction-birth:v1:' || birth.account_uuid::text || '/' || birth.category, + '1') || E'\n', 'UTF8')), 'hex') +$$; + +ALTER TABLE account_platform_restriction_births + ADD CONSTRAINT account_restriction_birth_exact_digest + CHECK (payload_digest = account_restriction_birth_digest( + ROW(account_uuid, category, revision, enforcement_epoch, source_kind, + restriction_state, operation_id, result_id, event_id, payload_digest, + account_source_numeric_id, account_insert_transaction_id, + account_generation, account_source_version, issuance_fence, + fence_source_version)::account_platform_restriction_births)); + +CREATE FUNCTION account_restriction_birth_storage_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + account_row RECORD; +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Restriction source evidence cannot be removed' + USING ERRCODE = '23514', + CONSTRAINT = 'account_restriction_birth_no_remove'; + END IF; + + IF TG_OP = 'UPDATE' + AND TG_TABLE_NAME <> 'account_platform_restriction_projections' THEN + RAISE EXCEPTION 'Restriction birth result and outbox are immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'account_restriction_birth_immutable'; + END IF; + + SELECT * INTO account_row FROM accounts + WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Restriction source requires exact Account' + USING ERRCODE = '23514', + CONSTRAINT = 'account_restriction_birth_account_required'; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.category IS DISTINCT FROM OLD.category + OR NEW.revision <> OLD.revision + 1 + OR NEW.enforcement_epoch <> OLD.enforcement_epoch + 1 + OR NEW.result_id IS NOT DISTINCT FROM OLD.result_id THEN + RAISE EXCEPTION 'Restriction projection requires next exact revision' + USING ERRCODE = '23514', + CONSTRAINT = 'account_restriction_projection_monotonic'; + END IF; + -- The exact-result FK remains birth-only, so no later revision is supported here. + ELSIF TG_TABLE_NAME = 'account_platform_restriction_births' THEN + IF account_row.account_uuid_provenance IS DISTINCT FROM 'ACCOUNT_REPOSITORY_INSERT' + OR account_row.lifecycle_state IS DISTINCT FROM 'active' + OR account_row.id IS DISTINCT FROM NEW.account_source_numeric_id + OR account_row.account_uuid_source_numeric_id + IS DISTINCT FROM NEW.account_source_numeric_id + OR account_row.account_repository_insert_transaction_id + IS DISTINCT FROM txid_current() + OR NEW.account_insert_transaction_id IS DISTINCT FROM txid_current() + OR NOT EXISTS ( + SELECT 1 FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND generation = 1 AND source_version = 1 + AND created_transaction_id = txid_current()) + OR NOT EXISTS ( + SELECT 1 FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + AND issuance_fence = 1 AND source_version = 1) + OR NOT EXISTS ( + SELECT 1 FROM account_authority_source_records + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND initialization_provenance = 'ACCOUNT_REPOSITORY_INSERT' + AND initialization_transaction_id = txid_current() + AND account_repository_insert_transaction_id = txid_current() + AND account_source_numeric_id = NEW.account_source_numeric_id + AND current_generation = 1 AND current_source_version = 1 + AND current_issuance_fence = 1 + AND current_issuance_fence_source_version = 1 + AND last_outbox_sequence = 0 + AND last_event_id IS NULL AND last_event_digest IS NULL) THEN + RAISE EXCEPTION 'Restriction birth requires genuine fresh Account source' + USING ERRCODE = '23514', + CONSTRAINT = 'account_restriction_birth_fresh_provenance'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_restriction_birth_storage + BEFORE INSERT OR UPDATE OR DELETE ON account_platform_restriction_births + FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_storage_guard(); +CREATE TRIGGER account_restriction_projection_storage + BEFORE INSERT OR UPDATE OR DELETE ON account_platform_restriction_projections + FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_storage_guard(); +CREATE TRIGGER account_restriction_birth_outbox_storage + BEFORE INSERT OR UPDATE OR DELETE ON account_platform_restriction_birth_outbox + FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_storage_guard(); +CREATE TRIGGER account_restriction_birth_no_truncate + BEFORE TRUNCATE ON account_platform_restriction_births + FOR EACH STATEMENT EXECUTE FUNCTION account_restriction_birth_storage_guard(); +CREATE TRIGGER account_restriction_projection_no_truncate + BEFORE TRUNCATE ON account_platform_restriction_projections + FOR EACH STATEMENT EXECUTE FUNCTION account_restriction_birth_storage_guard(); +CREATE TRIGGER account_restriction_birth_outbox_no_truncate + BEFORE TRUNCATE ON account_platform_restriction_birth_outbox + FOR EACH STATEMENT EXECUTE FUNCTION account_restriction_birth_storage_guard(); + +CREATE FUNCTION account_restriction_birth_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + -- Existing/unmapped rows are not enrolled. This branch uses only the accounts row type. + IF TG_TABLE_NAME = 'accounts' THEN + IF NEW.account_uuid_provenance IS DISTINCT FROM 'ACCOUNT_REPOSITORY_INSERT' + OR NEW.id IS DISTINCT FROM NEW.account_uuid_source_numeric_id + OR NEW.account_repository_insert_transaction_id IS DISTINCT FROM txid_current() THEN + RETURN NEW; + END IF; + END IF; + + IF (SELECT count(*) + FROM account_platform_restriction_births b + JOIN account_platform_restriction_projections p + USING (account_uuid, category, revision, enforcement_epoch, result_id) + JOIN account_platform_restriction_birth_outbox o + USING (account_uuid, category, revision, enforcement_epoch, + operation_id, result_id, event_id, payload_digest, + source_kind, restriction_state) + WHERE b.account_uuid = NEW.account_uuid) <> 2 THEN + RAISE EXCEPTION 'Fresh Account restriction birth must be complete' + USING ERRCODE = '23514', + CONSTRAINT = 'account_restriction_birth_complete'; + END IF; + RETURN NEW; +END; +$$; + +CREATE CONSTRAINT TRIGGER account_restriction_account_birth_complete + AFTER INSERT ON accounts DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_complete_guard(); +CREATE CONSTRAINT TRIGGER account_restriction_birth_complete + AFTER INSERT ON account_platform_restriction_births DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_complete_guard(); +CREATE CONSTRAINT TRIGGER account_restriction_projection_complete + AFTER INSERT OR UPDATE ON account_platform_restriction_projections + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_complete_guard(); +CREATE CONSTRAINT TRIGGER account_restriction_birth_outbox_complete + AFTER INSERT ON account_platform_restriction_birth_outbox + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_complete_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V89__account_admission_unknown_decision_abort.sql b/services/account-service/src/main/resources/db/migration/V89__account_admission_unknown_decision_abort.sql new file mode 100644 index 0000000000..20ed2b8443 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V89__account_admission_unknown_decision_abort.sql @@ -0,0 +1,31 @@ +-- An aborted attempt may have an unknown binding decision. Its exact cleanup identity remains +-- mandatory pending work, never proof of decision absence, cleanup delivery or token retirement. +-- V87's existing rows, immutable evidence, deadline, digest and allocation guards are unchanged. + +-- V87 declared this table-level CHECK without an explicit name. Resolve only its exact three +-- constrained columns; fail rather than removing an unrelated or ambiguous constraint. +-- PostgreSQL catalog lookup is excluded only from jOOQ's schema simulation, not runtime proof. +-- [jooq ignore start] +DO $$ +DECLARE + original_shape_constraint TEXT; +BEGIN + SELECT c.conname INTO STRICT original_shape_constraint + FROM pg_constraint c + WHERE c.conrelid = 'account_gameplay_admission_lease_operations'::regclass + AND c.contype = 'c' + AND ARRAY(SELECT a.attname::text + FROM pg_attribute a + WHERE a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey) + ORDER BY a.attname) = ARRAY['binding_decision_id', 'orphan_cleanup_id', 'status']; + EXECUTE format('ALTER TABLE account_gameplay_admission_lease_operations DROP CONSTRAINT %I', + original_shape_constraint); +END; +$$; +-- [jooq ignore stop] + +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_lease_operation_shape_check + CHECK ((status = 'PENDING' AND binding_decision_id IS NULL AND orphan_cleanup_id IS NULL) + OR (status = 'COMMITTED' AND binding_decision_id IS NOT NULL AND orphan_cleanup_id IS NULL) + OR (status = 'ABORTED' AND orphan_cleanup_id IS NOT NULL)); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index 27376bea74..654912fb47 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -264,6 +264,90 @@ void commitsExactDecisionAndAtomicallyRetainsAbortedOrphanIntentWithTerminalConf .hasMessageContaining("identity conflict"); } + @Test + void forwardMigrationPreservesRetainedReceiptsAndAllowsUnknownDecisionAbort() { + var context = context("88"); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var retainedPending = pending(context, account); + var retainedKnown = pending(context, account); + UUID decision = UUID.randomUUID(); + UUID knownCleanup = UUID.randomUUID(); + var known = tx(context, () -> repository.recordAborted(retainedKnown, decision, knownCleanup)); + var retainedCommitted = pending(context, account); + var committed = tx(context, () -> repository.recordCommitted(retainedCommitted, decision)); + + migrate(context, null); + + assertThat(tx(context, () -> repository.readExact(retainedKnown))).contains(known); + assertThat(tx(context, () -> repository.readExact(retainedCommitted))).contains(committed); + UUID cleanup = UUID.randomUUID(); + var unknown = tx(context, () -> repository.recordAborted(retainedPending, null, cleanup)); + assertThat(unknown.state()).isEqualTo(State.ABORTED); + assertThat(unknown.bindingDecisionId()).isNull(); + assertThat(unknown.orphanCleanupId()).isEqualTo(cleanup); + assertThat(unknown.hasPendingOrphanCleanup()).isTrue(); + assertThat(unknown.evidence()).isEqualTo(retainedPending); + assertThat(tx(context, () -> repository.recordAborted(retainedPending, null, cleanup))) + .isEqualTo(unknown); + assertThat(tx(context, () -> repository.readExact(retainedPending))).contains(unknown); + assertThatThrownBy( + () -> + tx( + context, + () -> repository.recordAborted(retainedPending, UUID.randomUUID(), cleanup))) + .hasMessageContaining("identity conflict"); + assertThatThrownBy( + () -> + tx( + context, + () -> repository.recordAborted(retainedPending, null, UUID.randomUUID()))) + .hasMessageContaining("identity conflict"); + // The unchanged V87 trigger prevents a direct rewrite of the unknown terminal observation. + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_operations SET binding_decision_id = ? WHERE request_id = ?", + UUID.randomUUID(), + UUID.fromString( + (String) retainedPending.carrier().get("requestId"))))) + .isInstanceOf(RuntimeException.class); + } + + @Test + void relaxedAbortShapeStillRejectsMissingCleanupAndCommittedWithoutDecision() { + var context = context(null); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var original = pending(context, account); + UUID request = UUID.fromString((String) original.carrier().get("requestId")); + assertThatThrownBy(() -> tx(context, () -> repository.recordAborted(original, null, null))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> tx(context, () -> repository.recordCommitted(original, null))) + .isInstanceOf(IllegalArgumentException.class); + for (String state : List.of("ABORTED", "COMMITTED")) { + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_operations SET status = ? WHERE request_id = ?", + state, + request))) + .isInstanceOf(RuntimeException.class); + } + assertThat(tx(context, () -> repository.readExact(original).orElseThrow()).state()) + .isEqualTo(State.PENDING); + } + @Test void expiredPendingCannotCommitOrRenewButKeepsExactReadbackAndCanAbort() { var context = context(null); @@ -283,10 +367,7 @@ void expiredPendingCannotCommitOrRenewButKeepsExactReadbackAndCanAbort() { assertThatThrownBy(() -> tx(context, () -> repository.beginPending(renewed))) .hasMessageContaining("identity conflict"); assertThat( - tx( - context, - () -> repository.recordAborted(evidence, UUID.randomUUID(), UUID.randomUUID())) - .state()) + tx(context, () -> repository.recordAborted(evidence, null, UUID.randomUUID())).state()) .isEqualTo(State.ABORTED); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java index 999212d481..bd72915823 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -1428,7 +1428,15 @@ private AdmissionSourceFixture newAdmissionSourceFixture() throws Exception { new AccountJoinOperationRepository(dsl, connectScopes); AccountMembershipAuthorityEventProducer membershipEvents = new AccountMembershipAuthorityEventProducer( - joinOperations, accounts, pairs, memberships, roles, generations, outbox, sources); + joinOperations, + accounts, + pairs, + memberships, + roles, + generations, + outbox, + sources, + tenantAuthorityEvents); AccountCanonicalFirstJoinTerminalCoordinator firstJoin = new AccountCanonicalFirstJoinTerminalCoordinator( accounts, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthPostgresIntegrationTest.java new file mode 100644 index 0000000000..53334aa088 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthPostgresIntegrationTest.java @@ -0,0 +1,328 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionBirthRepository; +import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionBirthRepository.BirthSourceUnavailableException; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; + +/** Dedicated fresh-birth PostgreSQL fixture exercising the real AccountRepository.save boundary. */ +class AccountPlatformRestrictionBirthPostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void startFixture() { + POSTGRES.start(); + } + + @AfterAll + static void stopFixture() { + POSTGRES.stop(); + } + + @Test + void freshSaveAtomicallyRetainsIndependentExactBirthResultsWithoutAuthEvent() { + Context context = context(null); + Account account = account(); + AccountPlatformRestrictionBirthSource birth = + context + .transaction() + .execute( + status -> { + new AccountRepository(context.dsl()).save(account); + return new AccountPlatformRestrictionBirthRepository(context.dsl()) + .readCurrentBirthSource(account.getAccountUuid()); + }); + AccountPlatformRestrictionBirthSource replay = + context + .transaction() + .execute( + status -> + new AccountPlatformRestrictionBirthRepository(context.dsl()) + .readCurrentBirthSource(account.getAccountUuid())); + assertThat(replay).isEqualTo(birth); + assertThat(Objects.requireNonNull(birth).accountSourceNumericId()).isEqualTo(account.getId()); + assertThat(birth.birthAuthority()).isEqualTo(birth.currentAuthority()); + assertThat(birth.accountSecurityLock().operationId()) + .isNotEqualTo(birth.platformAccessBan().operationId()); + assertThat(birth.accountSecurityLock().resultId()) + .isNotEqualTo(birth.platformAccessBan().resultId()); + assertThat(context.dsl().fetchCount(DSL.table("account_platform_restriction_births"))) + .isEqualTo(2); + assertThat(context.dsl().fetchCount(DSL.table("account_platform_restriction_projections"))) + .isEqualTo(2); + assertThat(context.dsl().fetchCount(DSL.table("account_platform_restriction_birth_outbox"))) + .isEqualTo(2); + assertThat(context.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT last_outbox_sequence FROM account_authority_source_records WHERE account_uuid = ?", + account.getAccountUuid())) + .get(0, Long.class)) + .isZero(); + } + + @Test + void independentAccountAdvancePreservesBirthEvidenceAndReadsCurrentAuthoritySeparately() { + Context context = context(null); + Account account = account(); + AccountPlatformRestrictionBirthSource birth = + context + .transaction() + .execute( + status -> { + new AccountRepository(context.dsl()).save(account); + return new AccountPlatformRestrictionBirthRepository(context.dsl()) + .readCurrentBirthSource(account.getAccountUuid()); + }); + context + .transaction() + .executeWithoutResult( + status -> { + account.setPasswordHash("changed-birth-test-hash"); + new AccountRepository(context.dsl()).save(account); + }); + AccountPlatformRestrictionBirthSource later = + context + .transaction() + .execute( + status -> + new AccountPlatformRestrictionBirthRepository(context.dsl()) + .readCurrentBirthSource(account.getAccountUuid())); + assertThat(Objects.requireNonNull(later).birthAuthority()) + .isEqualTo(Objects.requireNonNull(birth).birthAuthority()); + assertThat(later.accountSecurityLock()).isEqualTo(birth.accountSecurityLock()); + assertThat(later.platformAccessBan()).isEqualTo(birth.platformAccessBan()); + assertThat(later.currentAuthority().generation()).isEqualTo(2); + assertThat(later.currentAuthority().issuanceFence().value()).isEqualTo(2); + } + + @Test + void nonActiveFreshSaveRollsBackWithoutInventingNonrestrictedBirthEvidence() { + Context context = context(null); + for (AccountLifecycleState lifecycle : + new AccountLifecycleState[] { + AccountLifecycleState.SECURITY_LOCKED, + AccountLifecycleState.DEACTIVATED_PENDING_DELETE, + AccountLifecycleState.DELETED + }) { + Account account = account(); + account.setLifecycleState(lifecycle); + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> new AccountRepository(context.dsl()).save(account))) + .as("fresh %s Account must not acquire NONRESTRICTED birth evidence", lifecycle) + .isInstanceOf(IllegalStateException.class); + for (String table : + new String[] { + "accounts", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_source_records", + "account_authority_outbox_events", + "account_platform_restriction_births", + "account_platform_restriction_projections", + "account_platform_restriction_birth_outbox" + }) { + assertThat(context.dsl().fetchCount(DSL.table(table))) + .as("%s after failed fresh %s save", table, lifecycle) + .isZero(); + } + } + } + + @Test + void rollbackLeavesNoAccountCategoryResultProjectionOrOutbox() { + Context context = context(null); + Account account = account(); + context + .transaction() + .executeWithoutResult( + status -> { + new AccountRepository(context.dsl()).save(account); + new AccountPlatformRestrictionBirthRepository(context.dsl()) + .readCurrentBirthSource(account.getAccountUuid()); + status.setRollbackOnly(); + }); + for (String table : + new String[] { + "accounts", + "account_platform_restriction_births", + "account_platform_restriction_projections", + "account_platform_restriction_birth_outbox" + }) { + assertThat(context.dsl().fetchCount(DSL.table(table))).isZero(); + } + assertThatThrownBy( + () -> + context + .transaction() + .execute( + status -> + new AccountPlatformRestrictionBirthRepository(context.dsl()) + .readCurrentBirthSource(account.getAccountUuid()))) + .isInstanceOf(BirthSourceUnavailableException.class); + } + + @Test + void retainedPreSourceAccountIsNeverEnrolledByReadback() { + Context context = context("39"); + String suffix = UUID.randomUUID().toString(); + Long retainedId = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "INSERT INTO accounts (username, email, password_hash, role) VALUES (?, ?, ?, 'player') RETURNING id", + suffix, + suffix + "@example.test", + "retained-test-hash")) + .get(0, Long.class); + migrate(context, null); + UUID retainedUuid = + new AccountRepository(context.dsl()).findById(retainedId).orElseThrow().getAccountUuid(); + assertThatThrownBy( + () -> + context + .transaction() + .execute( + status -> + new AccountPlatformRestrictionBirthRepository(context.dsl()) + .readCurrentBirthSource(retainedUuid))) + .isInstanceOf(BirthSourceUnavailableException.class); + assertThat(context.dsl().fetchCount(DSL.table("account_platform_restriction_births"))).isZero(); + assertThat(context.dsl().fetchCount(DSL.table("account_platform_restriction_birth_outbox"))) + .isZero(); + } + + @Test + void immutableIdentityAndDigestSubstitutionsAreRejected() { + Context context = context(null); + Account account = account(); + context + .transaction() + .executeWithoutResult(status -> new AccountRepository(context.dsl()).save(account)); + for (String mutation : + new String[] { + "UPDATE account_platform_restriction_births SET payload_digest = repeat('0', 64)", + "UPDATE account_platform_restriction_birth_outbox SET result_id = '10203040-5060-4070-8090-a0b0c0d0e0f0'", + "DELETE FROM account_platform_restriction_projections", + "TRUNCATE account_platform_restriction_birth_outbox" + }) { + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult(status -> context.dsl().execute(mutation))) + .isInstanceOf(DataAccessException.class); + } + AccountPlatformRestrictionBirthSource readback = + context + .transaction() + .execute( + status -> + new AccountPlatformRestrictionBirthRepository(context.dsl()) + .readCurrentBirthSource(account.getAccountUuid())); + assertThat(readback).isNotNull(); + } + + @Test + void incompleteBirthCannotCommitAndFailedSaveCannotRetainPartialAuthority() { + Context context = context(null); + // Fault injection after birth insertion forces the mandatory exact readback to fail. + context + .dsl() + .execute( + "CREATE FUNCTION reject_restriction_birth_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ " + + "BEGIN RAISE EXCEPTION 'fixture rejects outbox' USING ERRCODE = '23514'; END; $$"); + context + .dsl() + .execute( + "CREATE TRIGGER reject_restriction_birth_outbox BEFORE INSERT " + + "ON account_platform_restriction_birth_outbox FOR EACH ROW EXECUTE FUNCTION reject_restriction_birth_outbox()"); + Account account = account(); + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> new AccountRepository(context.dsl()).save(account))) + .isInstanceOf(DataAccessException.class); + for (String table : + new String[] { + "accounts", + "account_authority_generations", + "account_platform_restriction_births", + "account_platform_restriction_projections", + "account_platform_restriction_birth_outbox" + }) { + assertThat(context.dsl().fetchCount(DSL.table(table))).isZero(); + } + } + + private static Account account() { + Account account = new Account(); + String suffix = UUID.randomUUID().toString(); + account.setUsername(suffix); + account.setEmail(suffix + "@example.test"); + account.setPasswordHash("birth-test-hash"); + account.setRole("player"); + return account; + } + + private static Context context(String target) { + String schema = "restriction_birth_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = POSTGRES.dataSource(schema); + Context context = + new Context( + schema, + dataSource, + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES), + new TransactionTemplate(new DataSourceTransactionManager(dataSource))); + migrate(context, target); + return context; + } + + private static void migrate(Context context, String target) { + var configuration = + Flyway.configure() + .dataSource(context.dataSource()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", context.schema())); + if (target != null) configuration.target(target); + configuration.load().migrate(); + } + + private record Context( + String schema, + org.springframework.jdbc.datasource.DriverManagerDataSource dataSource, + DSLContext dsl, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/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..9c78809f68 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,14 @@ 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.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 +26,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; @@ -80,6 +84,32 @@ void dropRunOwnedSchemas() { runOwnedSchemas.clear(); } + @Test + void commitsFirstJoinAfterActualDemoProvisioningAdvancesTenantAuthority() { + Fixture fixture = new Fixture(newTestContext(), true); + + var proof = fixture.commitFirstJoin(); + var event = + fixture.inTransaction( + () -> + fixture + .outbox + .findEvent(fixture.membershipStream(), fixture.requestId) + .orElseThrow()); + var decoded = + MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8)); + var current = + fixture.inTransaction(() -> fixture.tenantEvents.readCurrentByTenant(fixture.tenantUuid)); + + assertThat(current.tenantAuthorityGeneration()).isEqualTo(2L); + assertThat(current.tenantAuthoritySourceVersion()).isEqualTo(2L); + assertThat(current.outboxSequence()).isEqualTo(1L); + assertThat(decoded.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid.toString(), "2")); + assertThat(proof.eventSequence()).isEqualTo(1L); + assertThat(fixture.commitFirstJoin()).isEqualTo(proof); + } + @Test void commitsExactEventAndPairAndReplaysOnlyTheSameCallerOperation() { Fixture fixture = newFixture(); @@ -287,6 +317,8 @@ private static final class Fixture { private final AccountAuthorityGenerationRepository generations; private final AccountAuthorityOutboxRepository outbox; private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final AccountTenantAuthorityEventRepository tenantEvents; + private final AccountDemoTenantEntitlementRepository entitlements; private final AccountAuditOutboxRepository auditOutbox; private final AccountJoinOperationRepository operations; private final AccountMembershipAuthorityEventProducer producer; @@ -302,6 +334,10 @@ private static final class Fixture { private Long membershipId; private Fixture(TestContext context) { + this(context, false); + } + + private Fixture(TestContext context, boolean provisionDemo) { this.dsl = context.dsl(); this.transaction = context.transaction(); this.accounts = new AccountRepository(dsl); @@ -312,6 +348,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.tenantEvents = + new AccountTenantAuthorityEventRepository( + dsl, outbox, billingOutbox, freshTenants, generations); + this.entitlements = + new AccountDemoTenantEntitlementRepository( + dsl, freshTenants, generations, billingOutbox, tenantEvents); this.auditOutbox = new AccountAuditOutboxRepository(dsl); var legacyAssociationRepository = org.mockito.Mockito.mock(ApprovedLegacyTenantAssociationRepository.class); @@ -322,7 +365,15 @@ 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, + tenantEvents); this.terminalCoordinator = new AccountCanonicalFirstJoinTerminalCoordinator( accounts, operations, memberships, roles, outbox, pairs, auditOutbox, producer); @@ -335,7 +386,7 @@ private Fixture(TestContext context) { tenantEvidence.operationId(), tenantEvidence.evidenceDigest()); this.scope = canonicalScope(account.getAccountUuid(), tenantUuid); - seedOwnerRowsAndOperation(); + seedOwnerRowsAndOperation(provisionDemo); } private Account createAccount() { @@ -348,7 +399,7 @@ private Account createAccount() { return inTransaction(() -> accounts.save(input)); } - private void seedOwnerRowsAndOperation() { + private void seedOwnerRowsAndOperation(boolean provisionDemo) { inTransaction( () -> { freshTenants.importVerified(tenantEvidence); @@ -357,9 +408,16 @@ private void seedOwnerRowsAndOperation() { generations.initialize( AccountAuthorityGenerationRepository.AuthorityScope.membership( account.getAccountUuid(), tenantUuid)); + var entitlement = + provisionDemo ? entitlements.provision(demoRequest(), tenantEvidence) : null; connectScopes.insertCanonical(account.getId(), scope, provenance); operations.insertCanonicalIntent(requestId, scope, callerBinding); - operations.bindCanonicalPolicyEvidence(requestId, scope, callerBinding, true, 5L); + operations.bindCanonicalPolicyEvidence( + requestId, + scope, + callerBinding, + entitlement == null || entitlement.allowPublicJoin(), + entitlement == null ? 5L : entitlement.entitlementVersion()); return null; }); } @@ -382,6 +440,22 @@ private AccountAuthorityOutboxRepository.Checkpoint writeAndPublish() { }); } + private DemoTenantEntitlementRequest demoRequest() { + return new DemoTenantEntitlementRequest( + UUID.randomUUID(), + tenantUuid, + tenantEvidence.creationRequestId(), + tenantEvidence.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + } + private AccountJoinOperationRepository.CanonicalJoinTerminalProof commitFirstJoin() { return inTransaction( () -> terminalCoordinator.commitCanonicalFirstJoin(scope, requestId, callerBinding)); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSourceTest.java new file mode 100644 index 0000000000..fe4ee8cfd9 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSourceTest.java @@ -0,0 +1,110 @@ +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.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.Category; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.CategorySource; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.RestrictionState; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.SourceKind; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import org.junit.jupiter.api.Test; + +class AccountPlatformRestrictionBirthSourceTest { + private static final UUID ACCOUNT = UUID.fromString("10203040-5060-4070-8090-a0b0c0d0e0f0"); + private static final ScopeState BIRTH = + new ScopeState(AuthorityScope.account(ACCOUNT), 1, 1, new IssuanceFence(ACCOUNT, 1, 1)); + + @Test + void explicitIndependentCategoryEvidenceHasStableExactDigests() { + CategorySource lock = category(Category.ACCOUNT_SECURITY_LOCK); + CategorySource ban = category(Category.PLATFORM_ACCESS_BAN); + var source = source(lock, ban); + assertThat(source.accountSecurityLock().sourceKind()).isEqualTo(SourceKind.CATEGORY); + assertThat(source.platformAccessBan().restrictionState()) + .isEqualTo(RestrictionState.NONRESTRICTED); + assertThat(source.platformAccessBan().payloadDigest()) + .isEqualTo( + AccountPlatformRestrictionBirthSource.birthDigest( + ACCOUNT, + 7, + 19, + BIRTH, + ban.category(), + ban.operationId(), + ban.resultId(), + ban.eventId())); + assertThat(lock.outboxStreamKey()).doesNotContain("auth-authority"); + assertThat(lock.payloadDigest()).isNotEqualTo(ban.payloadDigest()); + } + + @Test + void absenceCategorySubstitutionAndChangedDigestDeny() { + CategorySource lock = category(Category.ACCOUNT_SECURITY_LOCK); + CategorySource ban = category(Category.PLATFORM_ACCESS_BAN); + assertThatThrownBy(() -> source(null, ban)).isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> source(ban, lock)).isInstanceOf(IllegalArgumentException.class); + CategorySource forged = + new CategorySource( + ban.category(), + ban.sourceKind(), + ban.restrictionState(), + 1, + 1, + ban.operationId(), + UUID.randomUUID(), + ban.eventId(), + ban.payloadDigest(), + ban.outboxStreamKey(), + 1); + assertThatThrownBy(() -> source(lock, forged)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest"); + } + + @Test + void changedProvenanceOrBirthFenceCannotReuseOriginalDigest() { + CategorySource lock = category(Category.ACCOUNT_SECURITY_LOCK); + CategorySource ban = category(Category.PLATFORM_ACCESS_BAN); + assertThatThrownBy( + () -> + new AccountPlatformRestrictionBirthSource(ACCOUNT, 8, 19, BIRTH, BIRTH, lock, ban)) + .isInstanceOf(IllegalArgumentException.class); + ScopeState later = + new ScopeState(AuthorityScope.account(ACCOUNT), 2, 2, new IssuanceFence(ACCOUNT, 2, 2)); + assertThatThrownBy( + () -> + new AccountPlatformRestrictionBirthSource(ACCOUNT, 7, 19, later, later, lock, ban)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AccountPlatformRestrictionBirthSource source( + CategorySource lock, CategorySource ban) { + return new AccountPlatformRestrictionBirthSource(ACCOUNT, 7, 19, BIRTH, BIRTH, lock, ban); + } + + private static CategorySource category(Category category) { + UUID operation = UUID.randomUUID(); + UUID result = UUID.randomUUID(); + UUID event = UUID.randomUUID(); + String digest = + AccountPlatformRestrictionBirthSource.birthDigest( + ACCOUNT, 7, 19, BIRTH, category, operation, result, event); + return new CategorySource( + category, + SourceKind.CATEGORY, + RestrictionState.NONRESTRICTED, + 1, + 1, + operation, + result, + event, + digest, + AccountPlatformRestrictionBirthSource.streamKey(ACCOUNT, category), + 1); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java index 10355449da..d882831428 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java @@ -15,6 +15,9 @@ import java.sql.Connection; import java.util.Arrays; import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import org.jooq.DSLContext; import org.jooq.Record; import org.junit.jupiter.api.AfterEach; @@ -207,6 +210,51 @@ void operationRecoveryRejectsMalformedStoredCarrierWithoutWrites() { verify(dsl, never()).execute(anyString(), any(Object[].class)); } + @Test + void abortedStorageShapeRetainsUnknownDecisionAndMandatoryPendingCleanup() { + var evidence = mock(AccountGameplayAdmissionLeaseEvidence.class); + UUID cleanup = UUID.randomUUID(); + var unknown = + new AccountGameplayAdmissionLeaseOperation(evidence, State.ABORTED, null, cleanup); + assertThat(unknown.bindingDecisionId()).isNull(); + assertThat(unknown.orphanCleanupId()).isEqualTo(cleanup); + assertThat(unknown.evidence()).isSameAs(evidence); + assertThat(unknown.hasPendingOrphanCleanup()).isTrue(); + assertThatThrownBy( + () -> new AccountGameplayAdmissionLeaseOperation(evidence, State.ABORTED, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new AccountGameplayAdmissionLeaseOperation(evidence, State.COMMITTED, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseOperation( + evidence, State.ABORTED, new UUID(0, 0), cleanup)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseOperation( + evidence, State.ABORTED, null, new UUID(0, 0))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void invalidTerminalPresenceAndPresentUuidsRejectBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountGameplayAdmissionLeaseRepository(dsl); + var evidence = mock(AccountGameplayAdmissionLeaseEvidence.class); + UUID cleanup = UUID.randomUUID(); + assertThatThrownBy(() -> repository.recordCommitted(evidence, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.recordAborted(evidence, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.recordAborted(evidence, new UUID(0, 0), cleanup)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.recordAborted(evidence, null, new UUID(0, 0))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(dsl); + } + private static Record allocationRow(UUID account, UUID request, UUID lease, Long fence) { Record row = mock(Record.class); when(row.get("account_uuid", UUID.class)).thenReturn(account); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepositoryTest.java new file mode 100644 index 0000000000..d88907895a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepositoryTest.java @@ -0,0 +1,174 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.Category; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionBirthRepository; +import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionBirthRepository.BirthSourceUnavailableException; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountPlatformRestrictionBirthRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountPlatformRestrictionBirthRepository repository = + new AccountPlatformRestrictionBirthRepository(dsl); + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactReadRequiresWritableMandatoryTransaction() { + assertThatThrownBy(() -> repository.readCurrentBirthSource(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("transaction"); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.readCurrentBirthSource(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("transaction"); + verifyNoInteractions(dsl); + } + + @Test + void missingAccountAndUnmappedIdentityDenyWithoutEnrollment() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> repository.readCurrentBirthSource(new UUID(0, 0))) + .isInstanceOf(BirthSourceUnavailableException.class); + verifyNoInteractions(dsl); + assertThatThrownBy(() -> repository.readCurrentBirthSource(UUID.randomUUID())) + .isInstanceOf(BirthSourceUnavailableException.class); + } + + @Test + void missingProjectionChangedRevisionAndDigestSubstitutionDenyExactReadback() { + for (String defect : + new String[] {"missing", "revision", "eventDigest", "bothDigests", "nullResult"}) { + TransactionSynchronizationManager.setActualTransactionActive(true); + UUID account = UUID.randomUUID(); + DSLContext ownerDsl = mock(DSLContext.class); + Map> births = new HashMap<>(); + Map> projections = new HashMap<>(); + Map> events = new HashMap<>(); + for (Category category : Category.values()) { + Map birth = birth(account, category); + births.put(category, birth); + projections.put(category, new HashMap<>(birth)); + events.put(category, new HashMap<>(birth)); + } + Category lock = Category.ACCOUNT_SECURITY_LOCK; + if (defect.equals("missing")) projections.remove(lock); + if (defect.equals("revision")) projections.get(lock).put("revision", 2L); + if (defect.equals("eventDigest") || defect.equals("bothDigests")) { + events.get(lock).put("payload_digest", "0".repeat(64)); + } + if (defect.equals("bothDigests")) births.get(lock).put("payload_digest", "0".repeat(64)); + if (defect.equals("nullResult")) { + births.get(lock).put("result_id", null); + projections.get(lock).put("result_id", null); + events.get(lock).put("result_id", null); + } + doAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM accounts")) + return record( + Map.of( + "id", + 7L, + "account_uuid", + account, + "account_uuid_provenance", + "ACCOUNT_REPOSITORY_INSERT", + "account_uuid_source_numeric_id", + 7L, + "account_repository_insert_transaction_id", + 19L, + "current_xid", + 23L)); + if (sql.contains("FROM account_authority_generations")) + return record(Map.of("generation", 1L, "source_version", 1L)); + if (sql.contains("FROM account_authority_issuance_fences")) + return record(Map.of("issuance_fence", 1L, "source_version", 1L)); + Object[] arguments = (Object[]) invocation.getRawArguments()[1]; + Category category = + Category.ACCOUNT_SECURITY_LOCK.storageValue().equals(arguments[1]) + ? Category.ACCOUNT_SECURITY_LOCK + : Category.PLATFORM_ACCESS_BAN; + if (sql.contains("FROM account_platform_restriction_births")) + return record(births.get(category)); + if (sql.contains("FROM account_platform_restriction_projections")) + return record(projections.get(category)); + if (sql.contains("FROM account_platform_restriction_birth_outbox")) + return record(events.get(category)); + throw new AssertionError("Unexpected source read: " + sql); + }) + .when(ownerDsl) + .fetchOne(anyString(), any(Object[].class)); + assertThatThrownBy( + () -> + new AccountPlatformRestrictionBirthRepository(ownerDsl) + .readCurrentBirthSource(account)) + .as(defect) + .isInstanceOf(BirthSourceUnavailableException.class); + } + } + + private static Map birth(UUID account, Category category) { + UUID operation = UUID.randomUUID(); + UUID result = UUID.randomUUID(); + UUID event = UUID.randomUUID(); + ScopeState authority = + new ScopeState(AuthorityScope.account(account), 1, 1, new IssuanceFence(account, 1, 1)); + Map row = new HashMap<>(); + row.put("account_uuid", account); + row.put("category", category.storageValue()); + row.put("revision", 1L); + row.put("enforcement_epoch", 1L); + row.put("result_id", result); + row.put("operation_id", operation); + row.put("event_id", event); + row.put("source_kind", "CATEGORY"); + row.put("restriction_state", "NONRESTRICTED"); + row.put("account_source_numeric_id", 7L); + row.put("account_insert_transaction_id", 19L); + row.put("account_generation", 1L); + row.put("account_source_version", 1L); + row.put("issuance_fence", 1L); + row.put("fence_source_version", 1L); + row.put("outbox_sequence", 1L); + row.put( + "outbox_stream_key", AccountPlatformRestrictionBirthSource.streamKey(account, category)); + row.put( + "payload_digest", + AccountPlatformRestrictionBirthSource.birthDigest( + account, 7, 19, authority, category, operation, result, event)); + return row; + } + + private static Record record(Map values) { + if (values == null) return null; + Record row = mock(Record.class); + doAnswer(invocation -> values.get(invocation.getArgument(0))).when(row).get(anyString()); + doAnswer(invocation -> values.get(invocation.getArgument(0))) + .when(row) + .get(anyString(), any(Class.class)); + return row; + } +} 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..4aadc2686d 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,7 @@ 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.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; @@ -50,6 +51,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 +59,7 @@ 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 org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -145,6 +148,7 @@ void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence() { .isEqualTo(Map.of(TENANT_UUID.toString(), "1")); assertThat(event.authorityTuple().accountSecurityCutoff()).isEmpty(); assertThat(event.authorityTuple().tenantBillingCutoff()).isEmpty(); + verifyNoInteractions(fixture.tenantEvents); var order = inOrder(fixture.accounts, fixture.joinOperations, fixture.memberships); order.verify(fixture.accounts).findByAccountUuid(ACCOUNT_UUID); @@ -189,6 +193,7 @@ void exactPositiveReplayReturnsTheExistingCheckpointWithoutAnotherAppendOrCas() fixture.scope, REQUEST_ID, CALLER_BINDING); assertThat(replay).isEqualTo(checkpoint); + verifyNoInteractions(fixture.tenantEvents); verify(fixture.outbox, never()) .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); verify(fixture.pairs, never()).commitTransition(any(), any()); @@ -293,6 +298,87 @@ void firstJoinDeniesAdvancedTenantAuthorityWithoutTenantSourceEventReadback() { .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact current Account, source, and tenant authority evidence"); + verify(fixture.tenantEvents).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 firstJoinDeniesStaleCurrentTenantEventReadback() { + Fixture fixture = advancedTenantFixture(); + var event = tenantEvent(TENANT_UUID, 1L, 1L, TENANT_OPERATION_ID, DIGEST); + when(fixture.tenantEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(event); + assertTenantReadbackDenied(fixture); + } + + @Test + void firstJoinDeniesCurrentTenantEventWithDifferentSourceVersion() { + Fixture fixture = advancedTenantFixture(); + var event = tenantEvent(TENANT_UUID, 2L, 3L, TENANT_OPERATION_ID, DIGEST); + when(fixture.tenantEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(event); + assertTenantReadbackDenied(fixture); + } + + @Test + void firstJoinDeniesCurrentTenantEventForDifferentTenant() { + Fixture fixture = advancedTenantFixture(); + var event = tenantEvent(UUID.randomUUID(), 2L, 2L, TENANT_OPERATION_ID, DIGEST); + when(fixture.tenantEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(event); + assertTenantReadbackDenied(fixture); + } + + @Test + void firstJoinDeniesCurrentTenantEventWithDifferentFreshSource() { + Fixture fixture = advancedTenantFixture(); + var event = tenantEvent(TENANT_UUID, 2L, 2L, UUID.randomUUID(), DIGEST); + when(fixture.tenantEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(event); + assertTenantReadbackDenied(fixture); + } + + @Test + void firstJoinDeniesCurrentTenantEventWithDifferentFreshSourceDigest() { + Fixture fixture = advancedTenantFixture(); + var event = tenantEvent(TENANT_UUID, 2L, 2L, TENANT_OPERATION_ID, "sha256:" + "b".repeat(64)); + when(fixture.tenantEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(event); + assertTenantReadbackDenied(fixture); + } + + private Fixture advancedTenantFixture() { + 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)); + fixture.startWritableTransaction(); + return fixture; + } + + private TenantAuthorityEventV1Codec.Event tenantEvent( + UUID tenantId, + long generation, + long sourceVersion, + UUID sourceOperationId, + String sourceDigest) { + var event = mock(TenantAuthorityEventV1Codec.Event.class); + var source = mock(FreshTenantCreationEvidence.class); + when(event.tenantId()).thenReturn(tenantId); + when(event.tenantAuthorityGeneration()).thenReturn(generation); + when(event.tenantAuthoritySourceVersion()).thenReturn(sourceVersion); + when(event.sourceEvidence()).thenReturn(source); + when(source.operationId()).thenReturn(sourceOperationId); + when(source.evidenceDigest()).thenReturn(sourceDigest); + return event; + } + + private void assertTenantReadbackDenied(Fixture fixture) { + assertThatThrownBy( + () -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact current Account, source, and tenant authority evidence"); + verify(fixture.tenantEvents).readCurrentByTenant(TENANT_UUID); verify(fixture.outbox, never()) .append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class)); verify(fixture.pairs, never()).commitTransition(any(), any()); @@ -397,9 +483,19 @@ private static final class Fixture { mock(AccountAuthorityOutboxRepository.class); private final AccountAuthoritySourceEvidenceRepository sourceEvidence = mock(AccountAuthoritySourceEvidenceRepository.class); + private final AccountTenantAuthorityEventRepository tenantEvents = + mock(AccountTenantAuthorityEventRepository.class); private final AccountMembershipAuthorityEventProducer producer = new AccountMembershipAuthorityEventProducer( - joinOperations, accounts, pairs, memberships, roles, authority, outbox, sourceEvidence); + joinOperations, + accounts, + pairs, + memberships, + roles, + authority, + outbox, + sourceEvidence, + tenantEvents); private final CanonicalJoinScopeV2 scope = scopeValue(); private final VerifiedTenantProvenance provenance = provenanceValue(); private final Account account = accountValue(); diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseWireCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseWireCodec.java new file mode 100644 index 0000000000..854d42e15c --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseWireCodec.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.common.account.admission; + +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import net.firedevops.firemud.account.v1.GameplayAdmissionLeaseOperationReadback; +import net.firedevops.firemud.account.v1.GameplayAdmissionLeaseReference; +import net.firedevops.firemud.account.v1.GameplayAdmissionLeaseState; + +/** + * Non-authorizing protobuf wrapper for the existing closed admission evidence codec. + * + *

No signature, peer, current source, registry, restriction, admission or physical commit is + * established here. Even a valid COMMITTED readback shape is not an authenticated owner receipt. + * Counter strings and the original canonical evidence remain unchanged. + */ +public final class AccountGameplayAdmissionLeaseWireCodec { + private AccountGameplayAdmissionLeaseWireCodec() {} + + public static GameplayAdmissionLeaseReference encodeReference( + AccountGameplayAdmissionLeaseEvidence evidence) { + if (evidence == null) throw invalid(); + var reference = + GameplayAdmissionLeaseReference.newBuilder() + .setRequestId((String) evidence.carrier().get("requestId")) + .setEvidenceCanonicalJson( + ByteString.copyFrom(evidence.canonicalJson(), StandardCharsets.UTF_8)) + .setEvidenceSha256(evidence.sha256()) + .build(); + parseReference(reference); + return reference; + } + + /** Parses exact UTF-8 bytes without repairing, reordering or reconstructing any carrier. */ + public static AccountGameplayAdmissionLeaseEvidence parseReference( + GameplayAdmissionLeaseReference reference) { + if (reference == null || !reference.getUnknownFields().asMap().isEmpty()) throw invalid(); + requireUuid(reference.getRequestId()); + ByteString bytes = reference.getEvidenceCanonicalJson(); + if (bytes.isEmpty() + || bytes.size() > AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + || !bytes.isValidUtf8() + || !reference.getEvidenceSha256().matches("[0-9a-f]{64}")) throw invalid(); + try { + var evidence = AccountGameplayAdmissionLeaseEvidence.parseCanonical(bytes.toStringUtf8()); + if (!reference.getRequestId().equals(evidence.carrier().get("requestId")) + || !reference.getEvidenceSha256().equals(evidence.sha256())) throw invalid(); + return evidence; + } catch (RuntimeException failure) { + // No evidence bytes, token metadata or parser internals are included in wire failures. + throw invalid(); + } + } + + /** Encodes terminal presence exactly; absent decision remains unknown, never fabricated. */ + public static GameplayAdmissionLeaseOperationReadback encodeOperation( + AccountGameplayAdmissionLeaseEvidence evidence, + GameplayAdmissionLeaseState state, + UUID bindingDecisionId, + UUID orphanCleanupId) { + if (state == null + || state == GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_UNSPECIFIED + || state == GameplayAdmissionLeaseState.UNRECOGNIZED) throw invalid(); + var result = + GameplayAdmissionLeaseOperationReadback.newBuilder() + .setLease(encodeReference(evidence)) + .setState(state) + .setPendingOrphanCleanup( + state == GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED); + if (bindingDecisionId != null) result.setBindingDecisionId(bindingDecisionId.toString()); + if (orphanCleanupId != null) result.setOrphanCleanupId(orphanCleanupId.toString()); + var operation = result.build(); + validateOperation(operation); + return operation; + } + + /** Validates storage readback shape only and returns its exact original evidence. */ + public static AccountGameplayAdmissionLeaseEvidence validateOperation( + GameplayAdmissionLeaseOperationReadback operation) { + if (operation == null + || !operation.hasLease() + || !operation.getUnknownFields().asMap().isEmpty()) throw invalid(); + var evidence = parseReference(operation.getLease()); + if (operation.hasBindingDecisionId()) requireUuid(operation.getBindingDecisionId()); + if (operation.hasOrphanCleanupId()) requireUuid(operation.getOrphanCleanupId()); + switch (operation.getState()) { + case GAMEPLAY_ADMISSION_LEASE_STATE_PENDING -> { + if (operation.hasBindingDecisionId() + || operation.hasOrphanCleanupId() + || operation.getPendingOrphanCleanup()) throw invalid(); + } + case GAMEPLAY_ADMISSION_LEASE_STATE_COMMITTED -> { + if (!operation.hasBindingDecisionId() + || operation.hasOrphanCleanupId() + || operation.getPendingOrphanCleanup()) throw invalid(); + } + case GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED -> { + if (!operation.hasOrphanCleanupId() || !operation.getPendingOrphanCleanup()) + throw invalid(); + } + default -> throw invalid(); + } + return evidence; + } + + private static void requireUuid(String text) { + try { + UUID value = UUID.fromString(text); + if (!value.toString().equals(text) || value.version() != 4 || value.variant() != 2) + throw invalid(); + } catch (RuntimeException failure) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Malformed Account admission lease wire evidence"); + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java index 180a77ae0a..1fe597cdc1 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java @@ -280,7 +280,7 @@ private static List> checkpoints(Map value) return (List>) value.get("outboxCheckpoints"); } - private static Map fixture() { + static Map fixture() { Map value = new LinkedHashMap<>(); value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); value.put("schemaVersion", "1"); diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseWireCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseWireCodecTest.java new file mode 100644 index 0000000000..fb6520c78a --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseWireCodecTest.java @@ -0,0 +1,238 @@ +package net.firedevops.firemud.common.account.admission; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.math.BigInteger; +import java.util.List; +import java.util.UUID; +import java.util.function.Consumer; +import net.firedevops.firemud.account.v1.GameplayAdmissionLeaseOperationReadback; +import net.firedevops.firemud.account.v1.GameplayAdmissionLeaseReference; +import net.firedevops.firemud.account.v1.GameplayAdmissionLeaseState; +import org.junit.jupiter.api.Test; + +/** Wire shape proof only; fixtures establish no authenticated receipt or admission authority. */ +class AccountGameplayAdmissionLeaseWireCodecTest { + private static final UUID DECISION = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID CLEANUP = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + + @Test + void preservesOriginalSharedCarrierBytesDigestAndExactCounters() { + var evidence = evidence(); + + var wire = AccountGameplayAdmissionLeaseWireCodec.encodeReference(evidence); + var parsed = AccountGameplayAdmissionLeaseWireCodec.parseReference(wire); + + assertThat(wire.getEvidenceCanonicalJson()) + .isEqualTo(ByteString.copyFromUtf8(evidence.canonicalJson())); + assertThat(wire.getEvidenceSha256()).isEqualTo(evidence.sha256()); + assertThat(wire.getRequestId()).isEqualTo(evidence.carrier().get("requestId")); + assertThat(parsed).isEqualTo(evidence); + assertThat(parsed.leaseFence()).isEqualTo(new BigInteger("9007199254740993")); + assertThat(AccountGameplayAdmissionLeaseWireCodec.encodeReference(parsed)).isEqualTo(wire); + } + + @Test + void preservesResumeCarrierAndOptionalPriorGenerationWithoutClaimingRuntimeSupport() { + var carrier = AccountGameplayAdmissionLeaseEvidenceTest.fixture(); + carrier.put("leaseKind", "RESUME"); + carrier.put("expectedOldBindingGeneration", "9007199254740993"); + carrier.put("resumeEpisodeId", DECISION.toString()); + var value = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + + assertThat( + AccountGameplayAdmissionLeaseWireCodec.parseReference( + AccountGameplayAdmissionLeaseWireCodec.encodeReference(value))) + .isEqualTo(value); + } + + @Test + void rejectsTamperedRequestHashBytesAndUnknownWireFields() { + List> changes = + List.of( + b -> b.setRequestId(DECISION.toString()), + b -> b.setRequestId("not-a-uuid"), + b -> b.setRequestId(DECISION.toString().toUpperCase(java.util.Locale.ROOT)), + b -> b.setEvidenceSha256("0".repeat(64)), + b -> b.setEvidenceSha256(evidence().sha256().toUpperCase(java.util.Locale.ROOT)), + b -> b.setEvidenceSha256(""), + b -> b.setEvidenceCanonicalJson(ByteString.EMPTY), + b -> b.setEvidenceCanonicalJson(ByteString.copyFrom(new byte[] {(byte) 0xc3, 0x28})), + b -> + b.setEvidenceCanonicalJson( + ByteString.copyFrom(new byte[] {(byte) 0xed, (byte) 0xa0, (byte) 0x80})), + b -> + b.setEvidenceCanonicalJson( + ByteString.copyFromUtf8( + " ".repeat(AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + 1))), + b -> + b.setEvidenceCanonicalJson( + ByteString.copyFromUtf8(" " + evidence().canonicalJson())), + b -> + b.setEvidenceCanonicalJson( + ByteString.copyFromUtf8( + evidence().canonicalJson().replace("\"world\"", "\"changed\""))), + b -> b.setUnknownFields(unknownFields())); + for (Consumer change : changes) { + var builder = reference().toBuilder(); + change.accept(builder); + assertInvalid(() -> AccountGameplayAdmissionLeaseWireCodec.parseReference(builder.build())); + } + } + + @Test + void rejectsExtraUnknownInvalidNullAndNoncanonicalJsonThroughExistingCodec() { + String json = evidence().canonicalJson(); + for (String invalid : + List.of( + json.substring(0, json.length() - 1) + ",\"extra\":\"1\"}", + json.replace("\"schemaVersion\":\"1\"", "\"schemaVersion\":\"2\""), + json.replace("\"leaseKind\":\"NEW_BINDING\"", "\"leaseKind\":\"UNKNOWN\""), + json.replace("\"leaseKind\":\"NEW_BINDING\"", "\"leaseKind\":null"), + json.replace("\"leaseFence\":\"9007199254740993\"", "\"leaseFence\":\"01\""), + json.replace( + "\"schemaVersion\":\"1\"", "\"schemaVersion\":\"1\",\"schemaVersion\":\"1\""), + "null")) { + var wire = + reference().toBuilder() + .setEvidenceCanonicalJson(ByteString.copyFromUtf8(invalid)) + .build(); + assertInvalid(() -> AccountGameplayAdmissionLeaseWireCodec.parseReference(wire)); + } + } + + @Test + void rejectsUnsupportedSourceRangeWithoutRoundingOrSubstitution() { + String invalid = evidence().canonicalJson().replace("9007199254740993", "9223372036854775808"); + var wire = + reference().toBuilder().setEvidenceCanonicalJson(ByteString.copyFromUtf8(invalid)).build(); + + assertInvalid(() -> AccountGameplayAdmissionLeaseWireCodec.parseReference(wire)); + } + + @Test + void validOperationShapesPreserveOriginalEvidenceAndUnknownAbortDecision() { + var pending = + operation(GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_PENDING, null, null); + var committed = + operation( + GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_COMMITTED, DECISION, null); + var abortedUnknown = + operation( + GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED, null, CLEANUP); + var abortedKnown = + operation( + GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED, DECISION, CLEANUP); + + for (var operation : List.of(pending, committed, abortedUnknown, abortedKnown)) { + assertThat(AccountGameplayAdmissionLeaseWireCodec.validateOperation(operation)) + .isEqualTo(evidence()); + assertThat(operation.getLease()).isEqualTo(reference()); + } + assertThat(pending.hasBindingDecisionId()).isFalse(); + assertThat(committed.getBindingDecisionId()).isEqualTo(DECISION.toString()); + assertThat(abortedUnknown.hasBindingDecisionId()).isFalse(); + assertThat(abortedUnknown.getPendingOrphanCleanup()).isTrue(); + assertThat(abortedKnown.getOrphanCleanupId()).isEqualTo(CLEANUP.toString()); + } + + @Test + void rejectsUnknownMissingAndContradictoryOperationShapes() { + var pending = + operation(GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_PENDING, null, null); + List> changes = + List.of( + b -> b.clearLease(), + b -> b.setStateValue(99), + b -> b.setState(GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_UNSPECIFIED), + b -> b.setBindingDecisionId(DECISION.toString()), + b -> b.setOrphanCleanupId(CLEANUP.toString()), + b -> b.setPendingOrphanCleanup(true), + b -> b.setState(GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_COMMITTED), + b -> b.setState(GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED), + b -> b.setUnknownFields(unknownFields())); + for (Consumer change : changes) { + var builder = pending.toBuilder(); + change.accept(builder); + assertInvalid( + () -> AccountGameplayAdmissionLeaseWireCodec.validateOperation(builder.build())); + } + var committed = + operation( + GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_COMMITTED, DECISION, null); + assertInvalid( + () -> + AccountGameplayAdmissionLeaseWireCodec.validateOperation( + committed.toBuilder().setOrphanCleanupId(CLEANUP.toString()).build())); + assertInvalid( + () -> + AccountGameplayAdmissionLeaseWireCodec.validateOperation( + committed.toBuilder().setPendingOrphanCleanup(true).build())); + var aborted = + operation( + GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED, null, CLEANUP); + assertInvalid( + () -> + AccountGameplayAdmissionLeaseWireCodec.validateOperation( + aborted.toBuilder().clearOrphanCleanupId().build())); + assertInvalid( + () -> + AccountGameplayAdmissionLeaseWireCodec.validateOperation( + aborted.toBuilder().setPendingOrphanCleanup(false).build())); + assertInvalid( + () -> + AccountGameplayAdmissionLeaseWireCodec.validateOperation( + aborted.toBuilder().setBindingDecisionId("").build())); + assertInvalid( + () -> + AccountGameplayAdmissionLeaseWireCodec.validateOperation( + aborted.toBuilder().setOrphanCleanupId("not-a-uuid").build())); + } + + @Test + void rejectsNullAndMalformedEncoderInputs() { + assertInvalid(() -> AccountGameplayAdmissionLeaseWireCodec.encodeReference(null)); + assertInvalid(() -> AccountGameplayAdmissionLeaseWireCodec.parseReference(null)); + assertInvalid(() -> AccountGameplayAdmissionLeaseWireCodec.validateOperation(null)); + assertInvalid( + () -> AccountGameplayAdmissionLeaseWireCodec.encodeOperation(evidence(), null, null, null)); + assertInvalid(() -> operation(GameplayAdmissionLeaseState.UNRECOGNIZED, null, null)); + assertInvalid( + () -> + operation( + GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_COMMITTED, + new UUID(0, 0), + null)); + } + + private static AccountGameplayAdmissionLeaseEvidence evidence() { + return AccountGameplayAdmissionLeaseEvidence.fromCarrier( + AccountGameplayAdmissionLeaseEvidenceTest.fixture()); + } + + private static GameplayAdmissionLeaseReference reference() { + return AccountGameplayAdmissionLeaseWireCodec.encodeReference(evidence()); + } + + private static GameplayAdmissionLeaseOperationReadback operation( + GameplayAdmissionLeaseState state, UUID decision, UUID cleanup) { + return AccountGameplayAdmissionLeaseWireCodec.encodeOperation( + evidence(), state, decision, cleanup); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + private static void assertInvalid(Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Malformed Account admission lease wire evidence") + .hasNoCause(); + } +} From e52fdee55236f659995a0602db1781f0ae41ee23 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 10:31:46 +1300 Subject: [PATCH 05/16] Add exact Game Session admission readback client and repair historical fixtures --- .../player-access-and-session.md | 6 +- .../v1/game_session_service.proto | 26 + ...essionGameplayAdmissionDecisionClient.java | 228 +++++++ ...tGameplayAdmissionProvisionalDecision.java | 27 + ...StateOperationPostgresIntegrationTest.java | 16 +- ...denceBundlePersistenceIntegrationTest.java | 14 +- ...issionLeasePersistenceIntegrationTest.java | 12 +- ...ionIssuancePersistenceIntegrationTest.java | 16 +- .../AccountRepositoryIntegrationTest.java | 242 ++++--- .../PreRestrictionBirthAccountFixture.java | 182 +++++ ...meplayAdmissionDecisionClientMtlsTest.java | 623 ++++++++++++++++++ ...onGameplayAdmissionDecisionClientTest.java | 402 +++++++++++ ...GrpcServerPeerIdentityCallCredentials.java | 41 ++ 13 files changed, 1719 insertions(+), 116 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionGameplayAdmissionDecisionClient.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionProvisionalDecision.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/PreRestrictionBirthAccountFixture.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionGameplayAdmissionDecisionClientMtlsTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionGameplayAdmissionDecisionClientTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 7e1ff8b5c8..ca801d64e0 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -18,15 +18,17 @@ V87 adds unregistered Account-owned allocation and exact operation storage. Its The additive Account lease protobuf and Common Security wire codec wrap the existing canonical lease bytes and digest unchanged. Method-specific outcomes distinguish retained operations, domain denials and storage-only nonobservation; the wire does not register an RPC, authenticate a receipt or supply authorization. Unknown fields, malformed UTF-8, changed bytes/digest, unsupported counters and contradictory terminal presence are rejected. Game Session's separate exact lease-bound decision callback remains its owner boundary, not a pointer-read substitute. +The unregistered Account `GameSessionGameplayAdmissionDecisionClient` consumes that existing Game Session callback. It requires file-backed mTLS and the exact same-namespace Game Session server identity before releasing request headers or the original lease bytes, then verifies the response identity independently. Its bounded read rejects ambient Account transactions, changed decision IDs, schema/status/unknown fields, bytes and digest. The result remains a point-in-time `PROVISIONAL` observation, not held World or Account authority, a durable Account finalization result, or admission permission. Its socket tests use an explicitly labeled transport-only Game Session double and fabricated lease-shape fixtures; they cannot establish the real owner database or current target predicates. + V88 and the actual fresh `AccountRepository.save` source initialization now create explicit birth-only category revisions, current projections, immutable results and distinct restriction outbox records in the same transaction as a genuinely new Account. The owner readback verifies the insert provenance, exact result identities and recomputed closed payload digests. Retained or unmapped Accounts are not enrolled. Historical birth generation/fence remains unchanged when unrelated current Account authority advances; current authority is read separately. This bounded source does not implement later moderation transitions or prove current protective-lock absence, and no admission path consumes it yet. PostgreSQL-specific completeness, immutability and digest guards remain active in the real migration; bounded fixed-vocabulary columns also support jOOQ generation. The canonical first-JOIN producer now permits advanced tenant authority only after exact current Account-owned tenant event readback matches the captured generation, source version and fresh Game Design provenance. The genuine sequence-zero fresh tenant baseline and committed JOIN replay remain unchanged. A new PostgreSQL case provisions the real demo entitlement before the JOIN intent, binds its actual policy evidence and verifies the advanced event and exact retry; missing or substituted owner evidence remains denied. Definitions and unit collaborators are not physical execution proof. This prerequisite does not supply registered protected acquire/finalize/abort/reconcile RPCs, authenticated target authority, complete current safety-restriction transition enforcement, pending-invalidation enforcement, physical COMMIT-time expiry proof, committed-binding orphan reconciliation or delivered cleanup, private-grant or paid-entitlement support, or fresh-image LOGIN → PLAY → LOOK proof. Explicit fresh category birth evidence is not full current safety authority; an `ACTIVE` lifecycle, an empty restriction lookup or the per-token fence cannot substitute for the missing owner predicates. Construction of source capture, carrier or operation storage grants no admission, and the runtime path remains denied. The owning target contract is [Session Behavior](../../architecture/system-architecture-session-behavior.md), with Account's predicate and caller obligations in [Authentication](../../architecture/system-architecture-authentication.md). Local consolidated proof is recorded below; compilation and simulated schema generation do not establish physical PostgreSQL locks, migration execution or lease finalization. -The consolidated authentication/source/storage/birth/wire correction gate passes Account and Common Security checks, integration-source compilation, formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown. Account executes 1,107 unit cases without failures or errors; three unit cases skip. Two non-database integration cases execute, while 144 integration cases skip without authorized local PostgreSQL infrastructure. The 155 Common Security cases passed on unchanged inputs and their outputs are reused by the final gate. Account jOOQ and protobuf generation pass; narrowly excluded PostgreSQL constraint functions still require physical database proof. Skipped definitions and simulated schema generation are not runtime or migration execution evidence. +The consolidated authentication/source/storage/birth/wire/client correction gate passes Account and Common Security checks, integration-source compilation, formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown. Account executes 1,119 unit cases without failures or errors; three unit cases skip. All seven new decision-client unit cases and five actual socket mTLS cases execute and pass, including wrong-server denial before request release and wrong-caller denial before the transport double returns a result. Two non-database integration cases execute, while 144 integration cases skip without authorized local PostgreSQL infrastructure. Common Security has 155 passing cases; the separate Common Platform Core full check executes 176 cases without failures or skips. Account jOOQ and protobuf generation pass; narrowly excluded PostgreSQL constraint functions still require physical database proof. Skipped definitions and simulated schema generation are not runtime or migration execution evidence. -Exact-head CI run `37678981014` for `0d4ddb396faaa8d3d642acb0cffb25af470ddbc9` executed 1,094 Account unit cases without failures or errors, with three unit skips. Its JUnit reports contain 144 integration cases, four failures and four skips; all six lease-storage PostgreSQL cases passed. After the earlier tenant-key fixture correction, the four source-capture cases exposed a real first-JOIN owner gap: the producer rejected the tenant's actual provisioned authority `2/2` because it allowed only the fresh `1/1` baseline. The correction described above uses current owner-event proof rather than moving provisioning after JOIN or fabricating authority. Its PostgreSQL rerun and the new V88/V89 database cases remain pending. The runner merge is `70760de9e0b668f8b9022c89ddbfde168e9fe7dd` on the exact published base; World, Game Session and dev-tool validation passed. Prior run `37674706914` exposed the now-corrected 38-character fixture key and separate World compilation/Game Session resolution failures; the latter did not reproduce in the newer run, without an established root-cause attribution. Aggregate CI is not green and this checkpoint is not merge-ready. +Predecessor exact-head CI run `37685986902` for `475949f3ba86b1c8c024dfee12d143ef1f7e1c6a` executed 1,107 Account unit cases without failures or errors, with three unit skips. Its JUnit reports contain 154 integration cases: 150 executed, four skipped, and 23 failed. All seven restriction-birth cases, five first-JOIN event cases including real demo provisioning before JOIN, and four public-admission source-capture cases executed and passed. Seven of the eight lease-storage cases passed, including unknown-decision abort and exact recovery. The remaining lease case and sixteen other historical-migration cases used the current Account creator before the V88 tables existed; six generic-update parameter cases attempted fresh non-`ACTIVE` creation instead of seeding an existing lifecycle fixture. The corrective batch preserves those migration targets and assertions through a test-only pre-V88 repository initializer that retains genuine insert provenance and fails if the birth schema is already installed. Generic-update cases first create a real fresh `ACTIVE` Account, then shape the existing lifecycle only inside a rolled-back test transaction; this is not production lifecycle-transition proof. Physical CI rerun of the corrected fixtures remains pending. The predecessor runner merge is `5f32c475bedcd84bffb1352f0dc6e07d91a6b83c` on exact base `7985e8a6f6354587f5c01649ede3d0cecde9fde2`; every other module and substantive validation job passed. Metadata-only run `37686048169` skipped substantive checks and failed gate preservation, so it supplies no execution proof. Aggregate CI is not green and this checkpoint is not merge-ready. Earlier failed runs and their corrections remain recorded in the controller and PR history. ### Credential-Bound Account LOGIN Owner diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index c868ca2163..30f4af5593 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -45,6 +45,10 @@ service GameSessionControlPlaneService { // Read the exact point-in-time published-realm admission owner composition for Entity. rpc GetPublishedRealmAdmissionOwnerRead(GetPublishedRealmAdmissionOwnerReadRequest) returns (GetPublishedRealmAdmissionOwnerReadResponse); + // Read Account's exact Game Session lease-bound PROVISIONAL decision; this is not admission. + rpc GetCanonicalGameplayAdmissionDecision( + GetCanonicalGameplayAdmissionDecisionRequest) + returns (GetCanonicalGameplayAdmissionDecisionResponse); rpc ValidateBuiltInCommandAlias(ValidateBuiltInCommandAliasRequest) returns (ValidateBuiltInCommandAliasResponse); rpc ListAdmissionPointers(ListAdmissionPointersRequest) @@ -555,6 +559,28 @@ message GetPublishedRealmAdmissionOwnerReadResponse { PublishedRealmAdmissionOwnerReadEvidence proof = 1; } +enum CanonicalGameplayAdmissionDecisionStatus { + CANONICAL_GAMEPLAY_ADMISSION_DECISION_STATUS_UNSPECIFIED = 0; + CANONICAL_GAMEPLAY_ADMISSION_DECISION_STATUS_PROVISIONAL = 1; +} + +// Account supplies the exact decision ID and its original canonical, bounded lease evidence. +// Game Session's result remains provisional and is never an admission or finalization receipt. +message GetCanonicalGameplayAdmissionDecisionRequest { + uint32 schema_version = 1; + string binding_decision_uuid = 2; + bytes lease_evidence = 3; +} + +// Echoes the complete request and binds it to the exact strict lease digest and PROVISIONAL state. +message GetCanonicalGameplayAdmissionDecisionResponse { + uint32 schema_version = 1; + string binding_decision_uuid = 2; + bytes lease_evidence = 3; + string lease_evidence_sha256 = 4; + CanonicalGameplayAdmissionDecisionStatus status = 5; +} + message GetGameplayCommandStatusRequest { string command_id = 1; string tenant_id = 2; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionGameplayAdmissionDecisionClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionGameplayAdmissionDecisionClient.java new file mode 100644 index 0000000000..461720ac77 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionGameplayAdmissionDecisionClient.java @@ -0,0 +1,228 @@ +package net.firedevops.firemud.accountservice.client; + +import com.google.protobuf.ByteString; +import io.grpc.ClientInterceptors; +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionProvisionalDecision; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionDecisionStatus; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionResponse; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered Account client for reading the Game Session-owned provisional decision. */ +public final class GameSessionGameplayAdmissionDecisionClient + extends AbstractReloadingBlockingGrpcClient< + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final String workloadNamespace; + private final GrpcServerPeerIdentityClientInterceptor serverPeerIdentityInterceptor; + private final GrpcServerPeerIdentityCallCredentials serverPeerIdentityCallCredentials; + private volatile boolean initialized; + private volatile boolean closed; + + public GameSessionGameplayAdmissionDecisionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireAccountMtls(tlsProps), + channelFactory, + GameSessionGameplayAdmissionDecisionClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Account workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + String gameSessionPeerUri = gameSessionServerPeerUri(workloadNamespace); + this.serverPeerIdentityInterceptor = + new GrpcServerPeerIdentityClientInterceptor(gameSessionPeerUri); + this.serverPeerIdentityCallCredentials = + new GrpcServerPeerIdentityCallCredentials(gameSessionPeerUri); + } + + /** Initializes the file-backed Account workload mTLS client when its owner enables it. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Game Session admission decision client is closed"); + } + if (initialized) { + return; + } + try { + initReloadingClient(); + initialized = true; + } catch (IOException | RuntimeException failure) { + closed = true; + throw failure; + } + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub buildStub( + ManagedChannel channel) { + return GameSessionControlPlaneServiceGrpc.newBlockingStub( + ClientInterceptors.intercept(channel, serverPeerIdentityInterceptor)) + .withCallCredentials(serverPeerIdentityCallCredentials) + .withCompression("gzip"); + } + + /** + * Reads one exact PROVISIONAL observation without authorizing, finalizing, or persisting it. The + * read does not prove durable Account state or current Account/World authority. + */ + public AccountGameplayAdmissionProvisionalDecision read( + UUID bindingDecisionId, AccountGameplayAdmissionLeaseEvidence original) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Session admission decision reads cannot run inside an Account transaction"); + } + requireReady(); + requireCanonicalDecisionId(bindingDecisionId); + if (original == null) { + throw new IllegalArgumentException("Original Account admission lease evidence is required"); + } + if (!workloadNamespace.equals(original.carrier().get("targetNamespace"))) { + throw new IllegalArgumentException( + "Account admission lease evidence does not match the configured workload namespace"); + } + + ByteString originalBytes = + ByteString.copyFrom(original.canonicalJson(), StandardCharsets.UTF_8); + GetCanonicalGameplayAdmissionDecisionResponse response = + stub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getCanonicalGameplayAdmissionDecision( + GetCanonicalGameplayAdmissionDecisionRequest.newBuilder() + .setSchemaVersion(1) + .setBindingDecisionUuid(bindingDecisionId.toString()) + .setLeaseEvidence(originalBytes) + .build()); + + validateResponse(response, bindingDecisionId, originalBytes, original.sha256()); + return new AccountGameplayAdmissionProvisionalDecision(bindingDecisionId, original); + } + + private void requireReady() { + if (closed || !initialized || stub() == null) { + throw new IllegalStateException( + "Game Session admission decision client is not initialized or is closed"); + } + } + + private static void validateResponse( + GetCanonicalGameplayAdmissionDecisionResponse response, + UUID expectedDecisionId, + ByteString expectedEvidence, + String expectedEvidenceSha256) { + if (response == null + || !response.getUnknownFields().asMap().isEmpty() + || response.getSchemaVersion() != 1 + || !expectedDecisionId.equals(parseCanonicalNonNilV4Uuid(response.getBindingDecisionUuid())) + || !expectedEvidence.equals(response.getLeaseEvidence()) + || !expectedEvidenceSha256.equals(response.getLeaseEvidenceSha256()) + || response.getStatus() + != CanonicalGameplayAdmissionDecisionStatus + .CANONICAL_GAMEPLAY_ADMISSION_DECISION_STATUS_PROVISIONAL) { + throw new IllegalStateException("Game Session admission decision response is invalid"); + } + } + + private static UUID parseCanonicalNonNilV4Uuid(String value) { + if (value == null) { + throw invalidResponse(); + } + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) + || parsed.version() != 4 + || parsed.variant() != 2 + || !parsed.toString().equals(value)) { + throw invalidResponse(); + } + return parsed; + } catch (RuntimeException failure) { + throw invalidResponse(); + } + } + + private static void requireCanonicalDecisionId(UUID value) { + if (value == null || NIL_UUID.equals(value) || value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Canonical nonnil UUIDv4 decision ID is required"); + } + } + + private static IllegalStateException invalidResponse() { + return new IllegalStateException("Game Session admission decision response is invalid"); + } + + private static String gameSessionServerPeerUri(String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; + } + + private static CommonGrpcClientProperties requireAccountMtls( + CommonGrpcClientProperties tlsProps) { + if (tlsProps == null) { + throw new IllegalArgumentException("Account gRPC TLS configuration is required"); + } + if (tlsProps.isPlaintext()) { + throw new IllegalArgumentException( + "Gameplay admission decision reads require Account workload mTLS"); + } + if (!isReadableFile(tlsProps.getCertChain()) + || !isReadableFile(tlsProps.getPrivateKey()) + || !isReadableFile(tlsProps.getCaCert())) { + throw new IllegalArgumentException( + "Gameplay admission decision reads require readable file-backed Account certificate, " + + "key, and CA files"); + } + return tlsProps; + } + + private static boolean isReadableFile(String value) { + if (value == null || value.isBlank() || value.trim().startsWith("classpath:")) { + return false; + } + try { + Path path = Path.of(value.trim()); + return Files.isRegularFile(path) && Files.isReadable(path); + } catch (RuntimeException failure) { + return false; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionProvisionalDecision.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionProvisionalDecision.java new file mode 100644 index 0000000000..52429b66f2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionProvisionalDecision.java @@ -0,0 +1,27 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; + +/** + * Exact non-authorizing PROVISIONAL observation returned by the Game Session owner. It proves + * neither durable Account state nor current Account/World authority. + */ +public record AccountGameplayAdmissionProvisionalDecision( + UUID bindingDecisionId, AccountGameplayAdmissionLeaseEvidence evidence) { + public AccountGameplayAdmissionProvisionalDecision { + if (bindingDecisionId == null + || bindingDecisionId.version() != 4 + || bindingDecisionId.variant() != 2 + || new UUID(0L, 0L).equals(bindingDecisionId)) { + throw new IllegalArgumentException("Canonical nonnil UUIDv4 decision ID is required"); + } + Objects.requireNonNull(evidence, "Original Account lease evidence is required"); + } + + @Override + public String toString() { + return "AccountGameplayAdmissionProvisionalDecision[status=PROVISIONAL]"; + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java index 686a7ebe7d..732f1bc931 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java @@ -31,6 +31,7 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository.Capture; +import net.firedevops.firemud.accountservice.repository.PreRestrictionBirthAccountFixture; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader; import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; @@ -921,15 +922,14 @@ private Seed seed(Fixture fixture) { return tx( fixture, () -> { - Account account = new Account(); String id = UUID.randomUUID().toString().substring(0, 12); - account.setUsername("security-" + id); - account.setEmail(id + "@example.test"); - account.setPasswordHash("synthetic-verifier"); - account = new AccountRepository(fixture.dsl()).save(account); - new AccountAuthoritySourceEvidenceRepository( - fixture.dsl(), fixture.generations(), fixture.outbox()) - .initializeIssuerIfAbsent("firemud-account-service"); + Account account = + PreRestrictionBirthAccountFixture.create( + fixture.dsl(), + "security-" + id, + id + "@example.test", + "synthetic-verifier", + AccountLoginAuthModes.DEFAULT_SERIALIZED); ScopeState source = fixture.generations().read(AuthorityScope.account(account.getAccountUuid())); return new Seed(account, source); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java index 0bd30936a1..98fe7f6985 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java @@ -25,6 +25,7 @@ import java.util.concurrent.TimeoutException; import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; @@ -34,6 +35,7 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.PreRestrictionBirthAccountFixture; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; @@ -100,7 +102,17 @@ static void stopOwnedContainer() { void forwardCheckpointRepairRetainsV84OwnersAndCapturesZeroAndPositiveEvidence() { TestContext context = newTestContext(MigrationVersion.fromVersion("84")); DSLContext dsl = context.dsl(); - Account account = createAccount(context); + String accountSuffix = UUID.randomUUID().toString().replace("-", ""); + Account account = + inTransaction( + context, + () -> + PreRestrictionBirthAccountFixture.create( + dsl, + "auth-bundle-" + accountSuffix, + "auth-bundle-" + UUID.randomUUID() + "@example.test", + "integration-test-hash", + AccountLoginAuthModes.DEFAULT_SERIALIZED)); AccountAuthorityGenerationRepository authorities = new AccountAuthorityGenerationRepository(dsl); AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index 654912fb47..d21e4f5875 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -192,7 +192,17 @@ void freshMigrationStoresExactReplayAndRejectsChangedBaselineDigestOrAllocation( @Test void retainedAccountMigrationPreservesAccountAndAddsIndependentFenceDomain() { var context = context("84.4"); - UUID account = account(context); + UUID account = + tx( + context, + () -> + PreRestrictionBirthAccountFixture.create( + context.dsl(), + "lease-" + UUID.randomUUID(), + UUID.randomUUID() + "@example.test", + "storage-fixture-only", + "PASSWORD") + .getAccountUuid()); migrate(context, null); var first = pending(context, account); var second = pending(context, account); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java index bd72915823..3d09ba6ec8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -103,6 +103,7 @@ 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.PreRestrictionBirthAccountFixture; import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; import net.firedevops.firemud.accountservice.service.AccountGameplayPublicAdmissionSourceReader; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; @@ -398,7 +399,7 @@ void credentialBindingMigrationRetainsLegacyEvidenceAndRequiresImmutableBoundRow throws Exception { // V78 is the existing pre-binding schema in this checkout; V79/V80 are reserved elsewhere. TestContext context = newTestContextAtVersion("78"); - Account account = createAccount(context); + Account account = createHistoricalAccount(context, "PASSWORD"); AccountAuthorityGenerationRepository authorities = new AccountAuthorityGenerationRepository(context.dsl()); AccountAuthoritySourceEvidenceRepository sources = sourceEvidence(context.dsl(), authorities); @@ -2312,6 +2313,19 @@ private static Account createAccount(TestContext context, String loginAuthModes) }); } + private static Account createHistoricalAccount(TestContext context, String loginAuthModes) { + String suffix = UUID.randomUUID().toString().replace("-", ""); + return inTransaction( + context, + () -> + PreRestrictionBirthAccountFixture.create( + context.dsl(), + "delegation-" + suffix, + "delegation-" + UUID.randomUUID() + "@example.test", + "integration-test-hash", + loginAuthModes)); + } + private static Account createEmailOtpAccount( TestContext context, AccountAuthoritySourceEvidenceRepository sourceEvidence) { return createAccount(context, "EMAIL_OTP"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index f00f397145..3e6670d172 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -20,6 +20,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; @@ -699,6 +700,37 @@ private Account saveInTransaction(Account account) { .execute(status -> repository.save(account))); } + /** + * Test-only lifecycle row shaping in a rolled-back transaction; this is not proof of a production + * lifecycle transition. + */ + private void withTestOnlyPersistedLifecycle( + AccountLifecycleState lifecycleState, Consumer assertions) { + new TransactionTemplate(new DataSourceTransactionManager(dataSource)) + .executeWithoutResult( + status -> { + Account persisted = + account("original", "original@example.com", AccountLifecycleState.ACTIVE); + persisted.setPasswordHash("original-password-hash"); + Account saved = repository.save(persisted); + if (lifecycleState != AccountLifecycleState.ACTIVE) { + // This row image exists only for generic-save assertions and is always rolled back. + int updatedRows = + dsl.execute( + "UPDATE accounts SET lifecycle_state = ? WHERE id = ?", + lifecycleState.storageValue(), + saved.getId()); + if (updatedRows != 1) { + throw new IllegalStateException( + "Test-only lifecycle row shaping did not update one Account"); + } + saved.setLifecycleState(lifecycleState); + } + assertions.accept(saved); + status.setRollbackOnly(); + }); + } + @Test void connectScopeRepositoryRetainsCanonicalRealmUuidAndDetectsTampering() { JdbcTemplate jdbc = new JdbcTemplate(dataSource); @@ -928,116 +960,120 @@ private static VerifiedJoinScope joinScope( @EnumSource(AccountLifecycleState.class) void genericUpdateRejectsLifecycleChangeWithoutMutatingAccountOrAuthorityEvidence( AccountLifecycleState lifecycleState) { - Account persisted = account("original", "original@example.com", lifecycleState); - persisted.setPasswordHash("original-password-hash"); - Account saved = saveInTransaction(persisted); - UUID accountUuid = saved.getAccountUuid(); - - AccountLifecycleState requestedLifecycleState = - lifecycleState == AccountLifecycleState.ACTIVE - ? AccountLifecycleState.SECURITY_LOCKED - : AccountLifecycleState.ACTIVE; - Account staleUpdate = account("updated", "updated@example.com", requestedLifecycleState); - staleUpdate.setPasswordHash("updated-password-hash"); - staleUpdate.setId(saved.getId()); - - String accountBefore = - jsonRow( - "SELECT jsonb_build_object('username', username, 'email', email, " - + "'password_hash', password_hash, 'lifecycle_state', lifecycle_state)::text " - + "FROM accounts WHERE id = ?", - saved.getId()); - String generationBefore = - jsonRow( - "SELECT to_jsonb(generation_row)::text FROM account_authority_generations " - + "AS generation_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", - accountUuid); - String fenceBefore = - jsonRow( - "SELECT to_jsonb(fence_row)::text FROM account_authority_issuance_fences " - + "AS fence_row WHERE account_uuid = ?", - accountUuid); - String checkpointBefore = - jsonRow( - "SELECT to_jsonb(source_row)::text FROM account_authority_source_records " - + "AS source_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", - accountUuid); - String outboxStreamBefore = - jsonRow( - "SELECT to_jsonb(stream_row)::text FROM account_authority_outbox_streams " - + "AS stream_row WHERE outbox_stream_key = ?", - "account:auth-authority:v1:account/" + accountUuid); - String outboxEventsBefore = - jsonRow( - "SELECT COALESCE(jsonb_agg(to_jsonb(event_row) ORDER BY outbox_sequence), " - + "'[]'::jsonb)::text FROM account_authority_outbox_events AS event_row " - + "WHERE outbox_stream_key = ?", - "account:auth-authority:v1:account/" + accountUuid); - - assertThatThrownBy(() -> saveInTransaction(staleUpdate)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Account lifecycle changes are unavailable through generic Account saves"); + withTestOnlyPersistedLifecycle( + lifecycleState, + saved -> { + UUID accountUuid = saved.getAccountUuid(); + + AccountLifecycleState requestedLifecycleState = + lifecycleState == AccountLifecycleState.ACTIVE + ? AccountLifecycleState.SECURITY_LOCKED + : AccountLifecycleState.ACTIVE; + Account staleUpdate = account("updated", "updated@example.com", requestedLifecycleState); + staleUpdate.setPasswordHash("updated-password-hash"); + staleUpdate.setId(saved.getId()); + + String accountBefore = + jsonRow( + "SELECT jsonb_build_object('username', username, 'email', email, " + + "'password_hash', password_hash, 'lifecycle_state', lifecycle_state)::text " + + "FROM accounts WHERE id = ?", + saved.getId()); + String generationBefore = + jsonRow( + "SELECT to_jsonb(generation_row)::text FROM account_authority_generations " + + "AS generation_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid); + String fenceBefore = + jsonRow( + "SELECT to_jsonb(fence_row)::text FROM account_authority_issuance_fences " + + "AS fence_row WHERE account_uuid = ?", + accountUuid); + String checkpointBefore = + jsonRow( + "SELECT to_jsonb(source_row)::text FROM account_authority_source_records " + + "AS source_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid); + String outboxStreamBefore = + jsonRow( + "SELECT to_jsonb(stream_row)::text FROM account_authority_outbox_streams " + + "AS stream_row WHERE outbox_stream_key = ?", + "account:auth-authority:v1:account/" + accountUuid); + String outboxEventsBefore = + jsonRow( + "SELECT COALESCE(jsonb_agg(to_jsonb(event_row) ORDER BY outbox_sequence), " + + "'[]'::jsonb)::text FROM account_authority_outbox_events AS event_row " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:account/" + accountUuid); + + assertThatThrownBy(() -> saveInTransaction(staleUpdate)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Account lifecycle changes are unavailable through generic Account saves"); - assertThat( - jsonRow( - "SELECT jsonb_build_object('username', username, 'email', email, " - + "'password_hash', password_hash, 'lifecycle_state', lifecycle_state)::text " - + "FROM accounts WHERE id = ?", - saved.getId())) - .isEqualTo(accountBefore); - assertThat( - jsonRow( - "SELECT to_jsonb(generation_row)::text FROM account_authority_generations " - + "AS generation_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", - accountUuid)) - .isEqualTo(generationBefore); - assertThat( - jsonRow( - "SELECT to_jsonb(fence_row)::text FROM account_authority_issuance_fences " - + "AS fence_row WHERE account_uuid = ?", - accountUuid)) - .isEqualTo(fenceBefore); - assertThat( - jsonRow( - "SELECT to_jsonb(source_row)::text FROM account_authority_source_records " - + "AS source_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", - accountUuid)) - .isEqualTo(checkpointBefore); - assertThat( - jsonRow( - "SELECT to_jsonb(stream_row)::text FROM account_authority_outbox_streams " - + "AS stream_row WHERE outbox_stream_key = ?", - "account:auth-authority:v1:account/" + accountUuid)) - .isEqualTo(outboxStreamBefore); - assertThat( - jsonRow( - "SELECT COALESCE(jsonb_agg(to_jsonb(event_row) ORDER BY outbox_sequence), " - + "'[]'::jsonb)::text FROM account_authority_outbox_events AS event_row " - + "WHERE outbox_stream_key = ?", - "account:auth-authority:v1:account/" + accountUuid)) - .isEqualTo(outboxEventsBefore); + assertThat( + jsonRow( + "SELECT jsonb_build_object('username', username, 'email', email, " + + "'password_hash', password_hash, 'lifecycle_state', lifecycle_state)::text " + + "FROM accounts WHERE id = ?", + saved.getId())) + .isEqualTo(accountBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(generation_row)::text FROM account_authority_generations " + + "AS generation_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid)) + .isEqualTo(generationBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(fence_row)::text FROM account_authority_issuance_fences " + + "AS fence_row WHERE account_uuid = ?", + accountUuid)) + .isEqualTo(fenceBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(source_row)::text FROM account_authority_source_records " + + "AS source_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid)) + .isEqualTo(checkpointBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(stream_row)::text FROM account_authority_outbox_streams " + + "AS stream_row WHERE outbox_stream_key = ?", + "account:auth-authority:v1:account/" + accountUuid)) + .isEqualTo(outboxStreamBefore); + assertThat( + jsonRow( + "SELECT COALESCE(jsonb_agg(to_jsonb(event_row) ORDER BY outbox_sequence), " + + "'[]'::jsonb)::text FROM account_authority_outbox_events AS event_row " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:account/" + accountUuid)) + .isEqualTo(outboxEventsBefore); + }); } @ParameterizedTest @EnumSource(AccountLifecycleState.class) void genericUpdateAllowsOrdinaryChangesWhenLifecycleMatches( AccountLifecycleState lifecycleState) { - Account persisted = account("original", "original@example.com", lifecycleState); - Account saved = saveInTransaction(persisted); - UUID accountUuid = saved.getAccountUuid(); - - Account ordinaryUpdate = account("updated", " Updated@Example.COM ", lifecycleState); - ordinaryUpdate.setPasswordHash("updated-password-hash"); - ordinaryUpdate.setId(saved.getId()); - Account updated = saveInTransaction(ordinaryUpdate); - - Account loaded = repository.findById(saved.getId()).orElseThrow(); - assertThat(loaded.getUsername()).isEqualTo("updated"); - assertThat(loaded.getEmail()).isEqualTo("updated@example.com"); - assertThat(loaded.getPasswordHash()).isEqualTo("updated-password-hash"); - assertThat(loaded.getLifecycleState()).isEqualTo(lifecycleState); - assertThat(updated.getAccountUuid()).isEqualTo(accountUuid); - assertThat(updated.getLifecycleState()).isEqualTo(lifecycleState); + withTestOnlyPersistedLifecycle( + lifecycleState, + saved -> { + UUID accountUuid = saved.getAccountUuid(); + + Account ordinaryUpdate = account("updated", " Updated@Example.COM ", lifecycleState); + ordinaryUpdate.setPasswordHash("updated-password-hash"); + ordinaryUpdate.setId(saved.getId()); + Account updated = saveInTransaction(ordinaryUpdate); + + Account loaded = repository.findById(saved.getId()).orElseThrow(); + assertThat(loaded.getUsername()).isEqualTo("updated"); + assertThat(loaded.getEmail()).isEqualTo("updated@example.com"); + assertThat(loaded.getPasswordHash()).isEqualTo("updated-password-hash"); + assertThat(loaded.getLifecycleState()).isEqualTo(lifecycleState); + assertThat(updated.getAccountUuid()).isEqualTo(accountUuid); + assertThat(updated.getLifecycleState()).isEqualTo(lifecycleState); + }); } @Test diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/PreRestrictionBirthAccountFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/PreRestrictionBirthAccountFixture.java new file mode 100644 index 0000000000..7cc0220fb2 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/PreRestrictionBirthAccountFixture.java @@ -0,0 +1,182 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.common.EmailCanonicalization; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Seeds the canonical pre-V88 repository-created Account image in historical migration fixtures. + * + *

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

The target schema must already include V40 and V74.1. Use only when a test intentionally + * starts from a historical schema before V88 and then verifies forward migration preservation. + */ + public static Account create( + DSLContext dsl, String username, String email, String passwordHash, String loginAuthModes) { + Objects.requireNonNull(dsl, "DSLContext is required"); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Historical Account setup requires a writable transaction"); + } + Record restrictionBirthSchemaReadback = + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM information_schema.tables " + + "WHERE table_schema = current_schema() AND table_name = ?)", + "account_platform_restriction_births"); + if (restrictionBirthSchemaReadback == null) { + throw new IllegalStateException("Could not read restriction-birth schema guard"); + } + Boolean restrictionBirthSchemaInstalled = + Objects.requireNonNull( + restrictionBirthSchemaReadback.get(0, Boolean.class), + "Restriction-birth schema guard readback is required"); + if (Boolean.TRUE.equals(restrictionBirthSchemaInstalled)) { + throw new IllegalStateException( + "Pre-V88 Account fixture cannot run after restriction-birth schema installation"); + } + Objects.requireNonNull(username, "username is required"); + Objects.requireNonNull(passwordHash, "password hash is required"); + + String canonicalEmail = EmailCanonicalization.normalize(email); + String normalizedLoginAuthModes = AccountLoginAuthModes.normalize(loginAuthModes); + Account account = new Account(); + account.setUsername(username); + account.setEmail(canonicalEmail); + account.setPasswordHash(passwordHash); + account.setLoginAuthModes(normalizedLoginAuthModes); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new PreV88SourceEvidence(dsl, generations, outbox); + sources.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + return new AccountRepository(dsl, sources).save(account); + } + + private static final class PreV88SourceEvidence extends AccountAuthoritySourceEvidenceRepository { + private final DSLContext dsl; + private final AccountAuthorityGenerationRepository generations; + + private PreV88SourceEvidence( + DSLContext dsl, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox) { + super(dsl, generations, outbox); + this.dsl = dsl; + this.generations = generations; + } + + @Override + @Transactional(propagation = Propagation.MANDATORY) + public void initializeFreshAccount(AccountRepository.FreshAccountInsert proof) { + Objects.requireNonNull(proof, "fresh Account repository insert proof is required"); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Historical Account setup requires a writable transaction"); + } + + Record account = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_provenance, " + + "account_uuid_source_numeric_id, account_repository_insert_transaction_id, " + + "lifecycle_state, txid_current() AS current_xid " + + "FROM accounts WHERE id = ? FOR UPDATE", + proof.accountId()); + if (account == null + || !Objects.equals(account.get("id", Long.class), proof.accountId()) + || !Objects.equals(account.get("account_uuid", UUID.class), proof.accountUuid()) + || !Objects.equals( + account.get("account_uuid_provenance", String.class), + proof.accountUuidProvenance().name()) + || !Objects.equals( + account.get("account_uuid_source_numeric_id", Long.class), proof.accountId()) + || !Objects.equals( + account.get("account_repository_insert_transaction_id", Long.class), + account.get("current_xid", Long.class)) + || !"active".equals(account.get("lifecycle_state", String.class))) { + throw new IllegalStateException( + "Historical source baseline requires the exact repository-created Account row"); + } + + long insertTransactionId = + positive( + account.get("account_repository_insert_transaction_id", Long.class), + "Account insert transaction ID"); + ScopeState state = + Objects.requireNonNull( + generations.initializeAccountForFreshRepositoryInsert(proof), + "Account generation baseline is required"); + long generation = positive(state.generation(), "Account generation"); + long sourceVersion = positive(state.sourceVersion(), "Account source version"); + IssuanceFence fence = + Objects.requireNonNull( + state.issuanceFence(), "Account issuance-fence baseline is required"); + positive(fence.value(), "Account issuance fence"); + positive(fence.sourceVersion(), "Account issuance-fence source version"); + String streamKey = ACCOUNT_STREAM_PREFIX + proof.accountUuid(); + requireOne( + dsl.execute( + "INSERT INTO account_authority_outbox_streams (outbox_stream_key, last_sequence) " + + "VALUES (?, 0)", + streamKey), + "Account authority outbox stream"); + requireOne( + dsl.execute( + "INSERT INTO account_authority_source_records " + + "(outbox_stream_key, scope_kind, issuer_id, account_uuid, " + + "baseline_generation, baseline_source_version, baseline_issuance_fence, " + + "initialization_provenance, account_source_numeric_id, account_uuid_provenance, " + + "account_repository_insert_transaction_id, current_generation, " + + "current_source_version, current_issuance_fence, " + + "current_issuance_fence_source_version, last_outbox_sequence) " + + "VALUES (?, 'ACCOUNT', NULL, ?, 1, 1, ?, 'ACCOUNT_REPOSITORY_INSERT', ?, ?, " + + "?, ?, ?, ?, ?, 0)", + streamKey, + proof.accountUuid(), + fence.value(), + proof.accountId(), + proof.accountUuidProvenance().name(), + insertTransactionId, + generation, + sourceVersion, + fence.value(), + fence.sourceVersion()), + "Account sequence-zero source record"); + readCurrentIssuerAccountSources(ACCOUNT_ISSUER, proof.accountUuid()); + } + } + + private static long positive(Long value, String label) { + if (value == null || value <= 0L) { + throw new IllegalStateException(label + " must be positive"); + } + return value; + } + + private static void requireOne(int affectedRows, String label) { + if (affectedRows != 1) { + throw new IllegalStateException(label + " insert did not affect exactly one row"); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionGameplayAdmissionDecisionClientMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionGameplayAdmissionDecisionClientMtlsTest.java new file mode 100644 index 0000000000..4d3a4cb295 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionGameplayAdmissionDecisionClientMtlsTest.java @@ -0,0 +1,623 @@ +package net.firedevops.firemud.accountservice.client; + +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 io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.UnaryOperator; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionProvisionalDecision; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionDecisionStatus; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical socket proof against a transport-only double, not Game Session owner/database proof. */ +class GameSessionGameplayAdmissionDecisionClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String OTHER_NAMESPACE_URI = + "spiffe://firemud/ns/other-test/sa/game-session-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String OTHER_ACCOUNT_URI = + "spiffe://firemud/ns/other-test/sa/account-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final UUID BINDING_DECISION_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private GameSessionGameplayAdmissionDecisionClient client; + private AtomicInteger headers; + private AtomicInteger ownerResults; + private UnaryOperator responseMutation = + UnaryOperator.identity(); + private Status serviceFailure; + + @BeforeAll + static void createTrustedCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + closeTransport(); + } + + @Test + void exactAuthenticatedReadReturnsOriginalEvidenceAndUnchangedRetry() throws Exception { + startServer(pki.gameSessionServer()); + client = newClient(server, pki.accountClient()); + client.init(); + + AccountGameplayAdmissionLeaseEvidence original = evidence(); + var first = client.read(BINDING_DECISION_ID, original); + var retry = client.read(BINDING_DECISION_ID, original); + + assertThat(first) + .isEqualTo(new AccountGameplayAdmissionProvisionalDecision(BINDING_DECISION_ID, original)); + assertThat(retry).isEqualTo(first); + assertThat(ownerResults).hasValue(2); + assertThat(headers).hasValue(2); + } + + @Test + void trustedWrongServerWorkloadOrNamespaceReleasesNoHeadersOrBody() throws Exception { + AccountGameplayAdmissionLeaseEvidence original = evidence(); + for (TestIdentity identity : List.of(pki.wrongWorkloadServer(), pki.otherNamespaceServer())) { + startServer(identity); + client = newClient(server, pki.accountClient()); + client.init(); + + assertThatThrownBy(() -> client.read(BINDING_DECISION_ID, original)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + exception -> + assertThat(Status.fromThrowable(exception).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(ownerResults).hasValue(0); + closeTransport(); + } + } + + @Test + void sameCaWrongAccountWorkloadOrNamespaceCannotReachOwnerResult() throws Exception { + AccountGameplayAdmissionLeaseEvidence original = evidence(); + for (TestIdentity identity : List.of(pki.wrongAccountClient(), pki.otherNamespaceAccount())) { + startServer(pki.gameSessionServer()); + client = newClient(server, identity); + client.init(); + + assertThatThrownBy(() -> client.read(BINDING_DECISION_ID, original)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + exception -> + assertThat(Status.fromThrowable(exception).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(1); + assertThat(ownerResults).hasValue(0); + closeTransport(); + } + } + + @Test + void alteredOrMalformedAuthenticatedResponseIsRejected() throws Exception { + List> mutations = + List.of( + response -> response.toBuilder().setSchemaVersion(2).build(), + response -> response.toBuilder().setBindingDecisionUuid("not-a-uuid").build(), + response -> + response.toBuilder().setLeaseEvidence(ByteString.copyFromUtf8("{}")).build(), + response -> response.toBuilder().setLeaseEvidenceSha256("0".repeat(64)).build(), + response -> + response.toBuilder() + .setStatus( + CanonicalGameplayAdmissionDecisionStatus + .CANONICAL_GAMEPLAY_ADMISSION_DECISION_STATUS_UNSPECIFIED) + .build(), + response -> + response.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build()); + + for (UnaryOperator mutation : mutations) { + startServer(pki.gameSessionServer()); + responseMutation = mutation; + client = newClient(server, pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.read(BINDING_DECISION_ID, evidence())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("response is invalid"); + assertThat(ownerResults).hasValue(1); + closeTransport(); + } + } + + @Test + void nonOkOwnerTransportStatusIsPropagated() throws Exception { + startServer(pki.gameSessionServer()); + serviceFailure = Status.UNAVAILABLE.withDescription("test owner unavailable"); + client = newClient(server, pki.accountClient()); + client.init(); + + assertThatThrownBy(() -> client.read(BINDING_DECISION_ID, evidence())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + exception -> + assertThat(Status.fromThrowable(exception).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(ownerResults).hasValue(1); + } + + private void startServer(TestIdentity identity) throws Exception { + closeTransport(); + headers = new AtomicInteger(); + ownerResults = new AtomicInteger(); + responseMutation = UnaryOperator.identity(); + serviceFailure = null; + var service = + new GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceImplBase() { + @Override + public void getCanonicalGameplayAdmissionDecision( + GetCanonicalGameplayAdmissionDecisionRequest request, + StreamObserver observer) { + ownerResults.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + AccountGameplayAdmissionLeaseEvidence original = evidence(); + byte[] exactOriginalBytes = original.canonicalJson().getBytes(StandardCharsets.UTF_8); + assertThat(request.getSchemaVersion()).isEqualTo(1); + assertThat(request.getBindingDecisionUuid()).isEqualTo(BINDING_DECISION_ID.toString()); + assertThat(request.getLeaseEvidence().toByteArray()).isEqualTo(exactOriginalBytes); + if (serviceFailure != null) { + observer.onError(serviceFailure.asRuntimeException()); + return; + } + var response = + GetCanonicalGameplayAdmissionDecisionResponse.newBuilder() + .setSchemaVersion(1) + .setBindingDecisionUuid(request.getBindingDecisionUuid()) + .setLeaseEvidence(request.getLeaseEvidence()) + .setLeaseEvidenceSha256(original.sha256()) + .setStatus( + CanonicalGameplayAdmissionDecisionStatus + .CANONICAL_GAMEPLAY_ADMISSION_DECISION_STATUS_PROVISIONAL) + .build(); + observer.onNext(responseMutation.apply(response)); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + ServerInterceptor exactAccountCallerGuard = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !ACCOUNT_URI.equals(peer.uri())) { + call.close( + Status.UNAUTHENTICATED.withDescription("Exact Account workload required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, + exactAccountCallerGuard, + countHeaders, + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GameSessionGameplayAdmissionDecisionClient newClient(Server target, TestIdentity caller) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("localhost:" + target.getPort()); + return new GameSessionGameplayAdmissionDecisionClient( + endpoints, + pki.clientProperties(tempDirectory, caller), + new GrpcChannelFactory(), + NAMESPACE); + } + + private void closeTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + private static AccountGameplayAdmissionLeaseEvidence evidence() { + String account = "11111111-1111-4111-8111-111111111111"; + String tenant = "22222222-2222-4222-8222-222222222222"; + String other = "33333333-3333-4333-8333-333333333333"; + String high = "9007199254740993"; + String prefix = "account:auth-authority:v1:"; + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", NAMESPACE); + value.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + value.put("requestId", other); + value.put("leaseId", tenant); + value.put("leaseFence", high); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) { + scope.put(key, other); + } + scope.put("accountId", account); + scope.put("tenantId", tenant); + scope.put("worldSlug", "fabricated-test-world"); + scope.put("realmSlug", "fabricated-test-realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) { + scope.put(key, high); + } + value.put("bindingScope", scope); + value.put( + "authorityTuple", + new LinkedHashMap<>( + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(tenant, high), + "membershipAuthorityGeneration", Map.of(tenant, high), + "privateRealmGrantVersions", List.of()))); + value.put("issuanceFence", high); + value.put( + "membershipBaseline", + new LinkedHashMap<>( + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + new LinkedHashMap<>(Map.of(tenant, high)), + "membershipAuthorityGeneration", + high))); + List> checkpoints = new ArrayList<>(); + for (String suffix : + List.of( + "account/" + account, + "issuer/firemud-account-service", + "membership/" + account + "/" + tenant, + "tenant/" + tenant)) { + checkpoints.add( + new LinkedHashMap<>( + Map.of( + "outboxStreamKey", + prefix + suffix, + "outboxSequence", + suffix.startsWith("account/") || suffix.startsWith("issuer/") ? "0" : high))); + } + value.put("outboxCheckpoints", checkpoints); + Map token = new LinkedHashMap<>(); + token.put("accountId", account); + for (String key : List.of("operationId", "issuanceRequestId", "tokenJti")) { + token.put(key, other); + } + token.put("tokenSHA256", "a".repeat(64)); + token.put("tokenProfile", "game-session-account-delegation"); + for (String key : List.of("tokenGeneration", "issuanceFence", "tokenIdentityFence")) { + token.put(key, high); + } + token.put("issuedAt", "999"); + token.put("notBefore", "999"); + token.put("expiresAt", "1300"); + value.put("tokenIdentityEvidence", token); + value.put("evaluatedAt", "1000000"); + value.put("expiresAt", "1015000"); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(value); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameSessionServer, + TestIdentity wrongWorkloadServer, + TestIdentity otherNamespaceServer, + TestIdentity accountClient, + TestIdentity wrongAccountClient, + TestIdentity otherNamespaceAccount) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("admission-decision-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD admission-decision test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("admission-decision-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "gs-server", GAME_SESSION_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_WORKLOAD_URI, true), + issueIdentity( + directory, caStore, caFile, "other-namespace-server", OTHER_NAMESPACE_URI, true), + issueIdentity(directory, caStore, caFile, "account-client", ACCOUNT_URI, false), + issueIdentity( + directory, caStore, caFile, "wrong-account-client", WRONG_WORKLOAD_URI, false), + issueIdentity( + directory, caStore, caFile, "other-namespace-account", OTHER_ACCOUNT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path cert = + writePem( + directory.resolve("caller.crt"), "CERTIFICATE", identity.certificate().getEncoded()); + Path key = + writePem( + directory.resolve("caller.key"), "PRIVATE KEY", identity.privateKey().getEncoded()); + Path ca = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(cert.toString()); + properties.setPrivateKey(key.toString()); + properties.setCaCert(ca.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + String eku = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionGameplayAdmissionDecisionClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionGameplayAdmissionDecisionClientTest.java new file mode 100644 index 0000000000..96abaa5875 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionGameplayAdmissionDecisionClientTest.java @@ -0,0 +1,402 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionProvisionalDecision; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +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.gamesession.v1.CanonicalGameplayAdmissionDecisionStatus; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionGameplayAdmissionDecisionClientTest { + private static final UUID BINDING_DECISION_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID OTHER_DECISION_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID NON_V4_DECISION_ID = + UUID.fromString("11111111-1111-1111-8111-111111111111"); + private static final String ACCOUNT = "11111111-1111-4111-8111-111111111111"; + private static final String TENANT = "22222222-2222-4222-8222-222222222222"; + private static final String OTHER = "33333333-3333-4333-8333-333333333333"; + private static final String HIGH = "9007199254740993"; + private static final String CHECKPOINT_PREFIX = "account:auth-authority:v1:"; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactProvisionalResponseReturnsOriginalCarrierAndUsesBoundedDeadline(@TempDir Path directory) + throws Exception { + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub stub = mockStub(); + AccountGameplayAdmissionLeaseEvidence original = evidence(); + when(stub.getCanonicalGameplayAdmissionDecision(any())) + .thenReturn(validResponse(BINDING_DECISION_ID, original)); + GameSessionGameplayAdmissionDecisionClient client = newClient(stub, "test", directory); + + AccountGameplayAdmissionProvisionalDecision result = client.read(BINDING_DECISION_ID, original); + + assertThat(result.bindingDecisionId()).isEqualTo(BINDING_DECISION_ID); + assertThat(result.evidence()).isSameAs(original); + assertThat(result.toString()) + .doesNotContain(original.canonicalJson(), original.sha256(), ACCOUNT, TENANT); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(GetCanonicalGameplayAdmissionDecisionRequest.class); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).getCanonicalGameplayAdmissionDecision(requestCaptor.capture()); + GetCanonicalGameplayAdmissionDecisionRequest request = requestCaptor.getValue(); + assertThat(request.getSchemaVersion()).isEqualTo(1); + assertThat(request.getBindingDecisionUuid()).isEqualTo(BINDING_DECISION_ID.toString()); + assertThat(request.getLeaseEvidence()) + .isEqualTo(ByteString.copyFrom(original.canonicalJson(), StandardCharsets.UTF_8)); + } + + @Test + void rejectsUnsupportedSchemaChangedDecisionOrMalformedResponseUuid(@TempDir Path directory) + throws Exception { + AccountGameplayAdmissionLeaseEvidence original = evidence(); + GetCanonicalGameplayAdmissionDecisionResponse valid = + validResponse(BINDING_DECISION_ID, original); + assertRejected(valid.toBuilder().setSchemaVersion(2).build(), original, directory); + assertRejected( + valid.toBuilder().setBindingDecisionUuid(OTHER_DECISION_ID.toString()).build(), + original, + directory); + assertRejected( + valid.toBuilder().setBindingDecisionUuid("not-a-uuid").build(), original, directory); + assertRejected( + valid.toBuilder().setBindingDecisionUuid("11111111-1111-1111-8111-111111111111").build(), + original, + directory); + } + + @Test + void rejectsChangedOriginalBytesDigestDefaultOrUnknownStatusAndUnknownFields( + @TempDir Path directory) throws Exception { + AccountGameplayAdmissionLeaseEvidence original = evidence(); + GetCanonicalGameplayAdmissionDecisionResponse valid = + validResponse(BINDING_DECISION_ID, original); + assertRejected( + valid.toBuilder() + .setLeaseEvidence(ByteString.copyFromUtf8(original.canonicalJson() + " ")) + .build(), + original, + directory); + assertRejected( + valid.toBuilder().setLeaseEvidenceSha256("b".repeat(64)).build(), original, directory); + assertRejected( + valid.toBuilder() + .setStatus( + CanonicalGameplayAdmissionDecisionStatus + .CANONICAL_GAMEPLAY_ADMISSION_DECISION_STATUS_UNSPECIFIED) + .build(), + original, + directory); + assertRejected(valid.toBuilder().setStatusValue(77).build(), original, directory); + assertRejected( + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(), + original, + directory); + } + + @Test + void rejectsMalformedSelectorsAndWrongNamespaceBeforeRpc(@TempDir Path directory) + throws Exception { + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub stub = mockStub(); + AccountGameplayAdmissionLeaseEvidence original = evidence(); + GameSessionGameplayAdmissionDecisionClient client = newClient(stub, "test", directory); + + assertThatThrownBy(() -> client.read(null, original)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.read(new UUID(0L, 0L), original)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.read(NON_V4_DECISION_ID, original)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.read(BINDING_DECISION_ID, null)) + .isInstanceOf(IllegalArgumentException.class); + + GameSessionGameplayAdmissionDecisionClient wrongNamespaceClient = + newClient(stub, "other", directory); + assertThatThrownBy(() -> wrongNamespaceClient.read(BINDING_DECISION_ID, original)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + verifyNoInteractions(stub); + } + + @Test + void rejectsAmbientAccountTransactionBeforeNetwork(@TempDir Path directory) throws Exception { + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub stub = mockStub(); + GameSessionGameplayAdmissionDecisionClient client = newClient(stub, "test", directory); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> client.read(BINDING_DECISION_ID, evidence())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account transaction"); + + verifyNoInteractions(stub); + } + + @Test + void propagatesCanonicalNonOkTransportFailureAndRejectsUseBeforeInitOrAfterClose( + @TempDir Path directory) throws Exception { + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub stub = mockStub(); + StatusRuntimeException unavailable = + new StatusRuntimeException(Status.UNAVAILABLE.withDescription("owner unavailable")); + when(stub.getCanonicalGameplayAdmissionDecision(any())).thenThrow(unavailable); + GameSessionGameplayAdmissionDecisionClient client = newClient(stub, "test", directory); + + assertThatThrownBy(() -> client.read(BINDING_DECISION_ID, evidence())).isSameAs(unavailable); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + + GameSessionGameplayAdmissionDecisionClient uninitializedClient = + newUninitializedClient("test", directory); + assertThatThrownBy(() -> uninitializedClient.read(BINDING_DECISION_ID, evidence())) + .isInstanceOf(IllegalStateException.class); + uninitializedClient.close(); + assertThatThrownBy(() -> uninitializedClient.read(BINDING_DECISION_ID, evidence())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(uninitializedClient::init) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + } + + @Test + void rejectsPlaintextMissingAndClasspathMtlsConfigurationBeforeChannelCreation( + @TempDir Path directory) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = tlsProperties(directory); + plaintext.setPlaintext(true); + + assertThatThrownBy( + () -> + new GameSessionGameplayAdmissionDecisionClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + assertThatThrownBy( + () -> + new GameSessionGameplayAdmissionDecisionClient( + new ServiceEndpointsProperties(), null, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("TLS configuration is required"); + + CommonGrpcClientProperties missingFiles = new CommonGrpcClientProperties(); + missingFiles.setCertChain(directory.resolve("missing.crt").toString()); + missingFiles.setPrivateKey(directory.resolve("missing.key").toString()); + missingFiles.setCaCert(directory.resolve("missing-ca.crt").toString()); + assertThatThrownBy( + () -> + new GameSessionGameplayAdmissionDecisionClient( + new ServiceEndpointsProperties(), missingFiles, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("readable file-backed"); + + CommonGrpcClientProperties classpathMaterial = tlsProperties(directory); + classpathMaterial.setPrivateKey("classpath:account-client.key"); + assertThatThrownBy( + () -> + new GameSessionGameplayAdmissionDecisionClient( + new ServiceEndpointsProperties(), classpathMaterial, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("readable file-backed"); + verifyNoInteractions(channelFactory); + } + + private static void assertRejected( + GetCanonicalGameplayAdmissionDecisionResponse response, + AccountGameplayAdmissionLeaseEvidence original, + Path directory) + throws Exception { + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub stub = mockStub(); + when(stub.getCanonicalGameplayAdmissionDecision(any())).thenReturn(response); + GameSessionGameplayAdmissionDecisionClient client = newClient(stub, "test", directory); + + assertThatThrownBy(() -> client.read(BINDING_DECISION_ID, original)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Game Session admission decision response is invalid"); + } + + private static GameSessionGameplayAdmissionDecisionClient newClient( + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub stub, + String namespace, + Path directory) + throws Exception { + // Mocked stub and initialized flag exercise response validation, not a TLS server handshake. + GameSessionGameplayAdmissionDecisionClient client = + new GameSessionGameplayAdmissionDecisionClient( + new ServiceEndpointsProperties(), + tlsProperties(directory), + mock(GrpcChannelFactory.class), + namespace); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + Field initializedField = + GameSessionGameplayAdmissionDecisionClient.class.getDeclaredField("initialized"); + initializedField.setAccessible(true); + initializedField.setBoolean(client, true); + return client; + } + + private static GameSessionGameplayAdmissionDecisionClient newUninitializedClient( + String namespace, Path directory) throws Exception { + return new GameSessionGameplayAdmissionDecisionClient( + new ServiceEndpointsProperties(), + tlsProperties(directory), + mock(GrpcChannelFactory.class), + namespace); + } + + private static GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub + mockStub() { + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub stub = + mock(GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static GetCanonicalGameplayAdmissionDecisionResponse validResponse( + UUID bindingDecisionId, AccountGameplayAdmissionLeaseEvidence original) { + return GetCanonicalGameplayAdmissionDecisionResponse.newBuilder() + .setSchemaVersion(1) + .setBindingDecisionUuid(bindingDecisionId.toString()) + .setLeaseEvidence(ByteString.copyFrom(original.canonicalJson(), StandardCharsets.UTF_8)) + .setLeaseEvidenceSha256(original.sha256()) + .setStatus( + CanonicalGameplayAdmissionDecisionStatus + .CANONICAL_GAMEPLAY_ADMISSION_DECISION_STATUS_PROVISIONAL) + .build(); + } + + private static AccountGameplayAdmissionLeaseEvidence evidence() { + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", "test"); + value.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + value.put("requestId", OTHER); + value.put("leaseId", TENANT); + value.put("leaseFence", HIGH); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String field : + List.of( + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) { + scope.put(field, OTHER); + } + scope.put("accountId", ACCOUNT); + scope.put("tenantId", TENANT); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String field : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) { + scope.put(field, HIGH); + } + value.put("bindingScope", scope); + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", "1"); + tuple.put("accountAuthorityGeneration", "1"); + tuple.put("tenantAuthorityGeneration", Map.of(TENANT, HIGH)); + tuple.put("membershipAuthorityGeneration", Map.of(TENANT, HIGH)); + tuple.put("privateRealmGrantVersions", List.of()); + value.put("authorityTuple", tuple); + value.put("issuanceFence", HIGH); + value.put( + "membershipBaseline", + new LinkedHashMap<>( + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + new LinkedHashMap<>(Map.of(TENANT, HIGH)), + "membershipAuthorityGeneration", + HIGH))); + List> checkpoints = new ArrayList<>(); + for (String suffix : + List.of( + "account/" + ACCOUNT, + "issuer/firemud-account-service", + "membership/" + ACCOUNT + "/" + TENANT, + "tenant/" + TENANT)) { + checkpoints.add( + new LinkedHashMap<>( + Map.of( + "outboxStreamKey", + CHECKPOINT_PREFIX + suffix, + "outboxSequence", + suffix.startsWith("account/") || suffix.startsWith("issuer/") ? "0" : HIGH))); + } + value.put("outboxCheckpoints", checkpoints); + Map token = new LinkedHashMap<>(); + token.put("accountId", ACCOUNT); + for (String field : List.of("operationId", "issuanceRequestId", "tokenJti")) { + token.put(field, OTHER); + } + token.put("tokenSHA256", "a".repeat(64)); + token.put("tokenProfile", "game-session-account-delegation"); + for (String field : List.of("tokenGeneration", "issuanceFence", "tokenIdentityFence")) { + token.put(field, HIGH); + } + token.put("issuedAt", "999"); + token.put("notBefore", "999"); + token.put("expiresAt", "1300"); + value.put("tokenIdentityEvidence", token); + value.put("evaluatedAt", "1000000"); + value.put("expiresAt", "1015000"); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(value); + } + + private static CommonGrpcClientProperties tlsProperties(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain( + Files.writeString(directory.resolve("account-client.crt"), "test-cert").toString()); + tls.setPrivateKey( + Files.writeString(directory.resolve("account-client.key"), "test-key").toString()); + tls.setCaCert( + Files.writeString(directory.resolve("game-session-ca.crt"), "test-ca").toString()); + return tls; + } +} 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()); + } +} From acfc654d4ee0ee719a0ce807fb8cbb84d625535e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 11:16:04 +1300 Subject: [PATCH 06/16] Fence pending lifecycle admission reads and retain authenticated abort retries --- .../player-access-and-session.md | 12 +- .../AccountGameplayAdmissionAbortOwner.java | 119 +++++++ ...countGameplayAdmissionLeaseRepository.java | 12 +- .../AccountLifecyclePendingDenialReader.java | 112 +++++++ ...ntGameplayPublicAdmissionSourceReader.java | 7 +- ...ountGameplayAdmissionLeaseGrpcService.java | 71 ++++ ...__account_lifecycle_serving_operations.sql | 191 +++++++++++ ...issionLeasePersistenceIntegrationTest.java | 155 +++++++++ ...ionIssuancePersistenceIntegrationTest.java | 305 +++++++++++++++++- ...ccountGameplayAdmissionAbortOwnerTest.java | 304 +++++++++++++++++ ...countLifecyclePendingDenialReaderTest.java | 151 +++++++++ ...meplayPublicAdmissionSourceReaderTest.java | 39 ++- ...GameplayAdmissionLeaseGrpcServiceTest.java | 278 ++++++++++++++++ 13 files changed, 1747 insertions(+), 9 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcService.java create mode 100644 services/account-service/src/main/resources/db/migration/V86__account_lifecycle_serving_operations.sql create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwnerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReaderTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcServiceTest.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index ca801d64e0..43b3097827 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,6 +10,8 @@ This is a non-normative implementation tracker for player access and session. Ca The isolated Account candidate adds an unregistered same-transaction source reader for fresh Game Design tenant provenance and the existing `NON_PAID_DEMO` entitlement class. It captures the actual issuer/Account/tenant/membership sources, persisted Account lifecycle, exact membership event and role snapshot, current entitlement and its separate billing receipt, and the exact SQL token-identity fence. The exact Account row identity and `ACTIVE` lifecycle, active player membership, entitlement admission flags, provenance, issuance fence and receipt/checkpoint consistency are checked through the existing owner repositories; missing, changed or unsupported evidence is denied. Unit fixtures use doubles of those repositories and do not establish PostgreSQL lock or race behavior. Four PostgreSQL source-capture definitions compose the existing first-JOIN, entitlement and issuance owners; their seeded evidence does not prove authenticated Game Design transport, gameplay admission or lease finalization. +The unregistered source reader also requires the exact Account/tenant denial predicate from the canonical V86 lifecycle-serving journal. Both `PENDING` and `WORLD_TERMINAL` remain unresolved denial evidence; a World receipt alone does not finalize Account sources. Missing journal data, query failures or a serialization failure deny the observation. The journal's pending-insert guard versions the exact Account row without changing logical Account state, authority counters or outbox evidence, so an older repeatable-read snapshot cannot wait for that writer and then silently miss its committed intent. This is not a lifecycle writer, a World verifier or a source finalizer. Its concurrent PostgreSQL cases require physical execution before claiming that ordering proof. + The shared admission-lease evidence value preserves the complete unchanged baseline, public-target tuple, ordered authority checkpoints, exact token metadata, caller workload, binding identity, absolute expiry and applicable resume/prior-generation fields. It is a bounded canonical shape/digest codec, not authenticated Account evidence or a lease issuer. Its tuple and baseline validation currently inherits the existing public-delegation validator's signed-long source range; unsupported values are denied rather than substituted. Billing cutoff evidence refers to the tenant authority stream; the demo entitlement's separate availability receipt is not invented as another authority checkpoint. The unregistered initial-token authenticator verifies the concrete same-namespace Game Session peer, the real asymmetric signature and initial unscoped profile, and exact current committed-issuance evidence through the existing SQL/Redis owner before opening a source transaction. It compares the original token hash, signer, Account identity, issuance times, generation, fence and global authority rather than trusting a supplied workload string or a post-admission player context. The composed source owner then opens its own writable SERIALIZABLE transaction and compares the current Account sources with that candidate, preserving the target membership baseline independently of the initial token's empty membership map. Expiry before, during and after source capture denies the observation. Fifteen signed-token tests and eight composition tests cover the bounded seam; owner and transaction doubles do not prove live mTLS, PostgreSQL/Redis currentness or admission through physical commit. The observation is non-authorizing and must not be reused as a later acquire or finalization decision. @@ -18,18 +20,24 @@ V87 adds unregistered Account-owned allocation and exact operation storage. Its The additive Account lease protobuf and Common Security wire codec wrap the existing canonical lease bytes and digest unchanged. Method-specific outcomes distinguish retained operations, domain denials and storage-only nonobservation; the wire does not register an RPC, authenticate a receipt or supply authorization. Unknown fields, malformed UTF-8, changed bytes/digest, unsupported counters and contradictory terminal presence are rejected. Game Session's separate exact lease-bound decision callback remains its owner boundary, not a pointer-read substitute. +The unregistered cancellation owner verifies the concrete same-namespace Game Session peer and the original canonical lease/caller binding before opening its own writable SERIALIZABLE Account transaction. It atomically records `PENDING` as `ABORTED` with one retained orphan-cleanup identity; an exact retry recovers the original bytes and decision presence without reminting. Changed operation evidence or decision correlation conflicts, absent operations remain unresolved, and `COMMITTED` cannot be turned into an abort or returned as admission evidence. The abort-only gRPC adapter distinguishes typed domain denial from validation, authentication and dependency errors. It remains unregistered; acquire, finalize, read and reconcile remain unimplemented. Unit collaborators and synthetic peer contexts are not physical SQL or mTLS proof, and cancellation does not retire a token or deliver Game Session cleanup. + The unregistered Account `GameSessionGameplayAdmissionDecisionClient` consumes that existing Game Session callback. It requires file-backed mTLS and the exact same-namespace Game Session server identity before releasing request headers or the original lease bytes, then verifies the response identity independently. Its bounded read rejects ambient Account transactions, changed decision IDs, schema/status/unknown fields, bytes and digest. The result remains a point-in-time `PROVISIONAL` observation, not held World or Account authority, a durable Account finalization result, or admission permission. Its socket tests use an explicitly labeled transport-only Game Session double and fabricated lease-shape fixtures; they cannot establish the real owner database or current target predicates. V88 and the actual fresh `AccountRepository.save` source initialization now create explicit birth-only category revisions, current projections, immutable results and distinct restriction outbox records in the same transaction as a genuinely new Account. The owner readback verifies the insert provenance, exact result identities and recomputed closed payload digests. Retained or unmapped Accounts are not enrolled. Historical birth generation/fence remains unchanged when unrelated current Account authority advances; current authority is read separately. This bounded source does not implement later moderation transitions or prove current protective-lock absence, and no admission path consumes it yet. PostgreSQL-specific completeness, immutability and digest guards remain active in the real migration; bounded fixed-vocabulary columns also support jOOQ generation. The canonical first-JOIN producer now permits advanced tenant authority only after exact current Account-owned tenant event readback matches the captured generation, source version and fresh Game Design provenance. The genuine sequence-zero fresh tenant baseline and committed JOIN replay remain unchanged. A new PostgreSQL case provisions the real demo entitlement before the JOIN intent, binds its actual policy evidence and verifies the advanced event and exact retry; missing or substituted owner evidence remains denied. Definitions and unit collaborators are not physical execution proof. -This prerequisite does not supply registered protected acquire/finalize/abort/reconcile RPCs, authenticated target authority, complete current safety-restriction transition enforcement, pending-invalidation enforcement, physical COMMIT-time expiry proof, committed-binding orphan reconciliation or delivered cleanup, private-grant or paid-entitlement support, or fresh-image LOGIN → PLAY → LOOK proof. Explicit fresh category birth evidence is not full current safety authority; an `ACTIVE` lifecycle, an empty restriction lookup or the per-token fence cannot substitute for the missing owner predicates. Construction of source capture, carrier or operation storage grants no admission, and the runtime path remains denied. The owning target contract is [Session Behavior](../../architecture/system-architecture-session-behavior.md), with Account's predicate and caller obligations in [Authentication](../../architecture/system-architecture-authentication.md). Local consolidated proof is recorded below; compilation and simulated schema generation do not establish physical PostgreSQL locks, migration execution or lease finalization. +This prerequisite does not supply registered protected acquire/finalize/abort/reconcile RPCs, authenticated target authority, complete current safety-restriction transition enforcement, the lifecycle-serving writer and source-finalization protocol, physical COMMIT-time expiry proof, committed-binding orphan reconciliation or delivered cleanup, private-grant or paid-entitlement support, or fresh-image LOGIN → PLAY → LOOK proof. Explicit fresh category birth evidence is not full current safety authority; an `ACTIVE` lifecycle, an empty restriction lookup or the per-token fence cannot substitute for the missing owner predicates. The bounded pending-journal denial read is not completion of that lifecycle protocol. Construction of source capture, carrier or operation storage grants no admission, and the runtime path remains denied. The owning target contract is [Session Behavior](../../architecture/system-architecture-session-behavior.md), with Account's predicate and caller obligations in [Authentication](../../architecture/system-architecture-authentication.md). Local consolidated proof is recorded below; compilation and simulated schema generation do not establish physical PostgreSQL locks, migration execution or lease finalization. -The consolidated authentication/source/storage/birth/wire/client correction gate passes Account and Common Security checks, integration-source compilation, formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown. Account executes 1,119 unit cases without failures or errors; three unit cases skip. All seven new decision-client unit cases and five actual socket mTLS cases execute and pass, including wrong-server denial before request release and wrong-caller denial before the transport double returns a result. Two non-database integration cases execute, while 144 integration cases skip without authorized local PostgreSQL infrastructure. Common Security has 155 passing cases; the separate Common Platform Core full check executes 176 cases without failures or skips. Account jOOQ and protobuf generation pass; narrowly excluded PostgreSQL constraint functions still require physical database proof. Skipped definitions and simulated schema generation are not runtime or migration execution evidence. +The prior authentication/source/storage/birth/wire/client correction gate passed Account and Common Security checks, integration-source compilation, formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown. Account executed 1,119 unit cases without failures or errors; three unit cases skipped. All seven new decision-client unit cases and five actual socket mTLS cases executed and passed, including wrong-server denial before request release and wrong-caller denial before the transport double returns a result. Two non-database integration cases executed, while 144 integration cases skipped without authorized local PostgreSQL infrastructure. Common Security had 155 passing cases; the separate Common Platform Core full check executed 176 cases without failures or skips. Account jOOQ and protobuf generation passed; narrowly excluded PostgreSQL constraint functions still require physical database proof. Skipped definitions and simulated schema generation are not runtime or migration execution evidence. + +The subsequent pending-journal and cancellation batch has 1,142 discovered Account unit cases: 1,139 executed, three skipped, and no failures or errors after correcting the new fabricated checkpoint fixture and Mockito restubbing. All five pending-reader, eight cancellation-owner and six abort-handler cases passed. Integration definitions compile: two non-database cases executed and 149 database cases skipped locally. Three new pending-journal cases include both PENDING/WORLD_TERMINAL denial, cross-tenant isolation and stale-snapshot denial under both REPEATABLE_READ and SERIALIZABLE; two actual cancellation-owner PostgreSQL cases define lost-response recovery and concurrent retry. Their physical execution remains pending, and no PostgreSQL behavior is inferred from compilation or skipped cases. Failed intermediate gates and exact publication proof remain in the controller. Predecessor exact-head CI run `37685986902` for `475949f3ba86b1c8c024dfee12d143ef1f7e1c6a` executed 1,107 Account unit cases without failures or errors, with three unit skips. Its JUnit reports contain 154 integration cases: 150 executed, four skipped, and 23 failed. All seven restriction-birth cases, five first-JOIN event cases including real demo provisioning before JOIN, and four public-admission source-capture cases executed and passed. Seven of the eight lease-storage cases passed, including unknown-decision abort and exact recovery. The remaining lease case and sixteen other historical-migration cases used the current Account creator before the V88 tables existed; six generic-update parameter cases attempted fresh non-`ACTIVE` creation instead of seeding an existing lifecycle fixture. The corrective batch preserves those migration targets and assertions through a test-only pre-V88 repository initializer that retains genuine insert provenance and fails if the birth schema is already installed. Generic-update cases first create a real fresh `ACTIVE` Account, then shape the existing lifecycle only inside a rolled-back test transaction; this is not production lifecycle-transition proof. Physical CI rerun of the corrected fixtures remains pending. The predecessor runner merge is `5f32c475bedcd84bffb1352f0dc6e07d91a6b83c` on exact base `7985e8a6f6354587f5c01649ede3d0cecde9fde2`; every other module and substantive validation job passed. Metadata-only run `37686048169` skipped substantive checks and failed gate preservation, so it supplies no execution proof. Aggregate CI is not green and this checkpoint is not merge-ready. Earlier failed runs and their corrections remain recorded in the controller and PR history. +Exact published admission checkpoint `e52fdee55236f659995a0602db1781f0ae41ee23` has physical Account JUnit evidence from CI run `37690080516`: 1,276 discovered cases, 1,269 executed, seven skipped, and no failures or errors. The seven client unit and five socket mTLS cases, seven restriction-birth cases, five first-JOIN event cases and eight lease-storage cases executed and passed. Historical migration and generic-update fixture suites executed without failures, but their individual loop subcases were not enumerated from runner logs during the bounded observer window. The full workflow subsequently completed successfully, including Dev Tool Contract Checks and Validation Summary. Green CI does not establish protected owner completion or merge readiness. Metadata-only sibling `37690096664` supplies no execution credit. This published-head proof excludes the subsequent pending-journal reader, row-version guard and cancellation-owner batch. + ### Credential-Bound Account LOGIN Owner The LOGIN prerequisite supplies the explicit Account owner for credential verification and immutable keyed request preparation, followed by the existing signer, pending registry, current authority projection, SQL commit, active readback and encrypted response-recovery owners. Exact retries bind the original Account identity, normalized email, authenticated workload, still-open pre-auth source context and transient credential presentation through a retained Account HMAC key; no raw credential or reusable unkeyed hash becomes operation evidence. V81 preserves historical unbound operations unchanged and non-authorizing while requiring immutable credential binding for new operations. Invalid credential denials commit their OTP-attempt evidence without creating an issuance; other authentication failures roll back. Canonical authentication and token authority remain in [Authentication](../../architecture/system-architecture-authentication.md) and [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwner.java new file mode 100644 index 0000000000..1ff62dd884 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwner.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.accountservice.repository; + +import io.grpc.Status; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered cancellation owner. Authenticates the original Game Session workload and retains + * pending orphan cleanup atomically; grants no admission, current authority or token retirement. A + * supplied decision is correlation only, never a verified Gameplay decision. + */ +public final class AccountGameplayAdmissionAbortOwner { + private final AccountGameplayAdmissionLeaseRepository repository; + private final TransactionTemplate transaction; + private final String namespace; + + public AccountGameplayAdmissionAbortOwner( + AccountGameplayAdmissionLeaseRepository repository, + PlatformTransactionManager transactionManager, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + } + + public AccountGameplayAdmissionLeaseOperation abort(AbortGameplayAdmissionLeaseRequest request) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + if (!GrpcPeerIdentity.isValidNamespace(namespace) + || !peer.uri().equals("spiffe://firemud/ns/" + namespace + "/sa/game-session-service")) + throw Status.PERMISSION_DENIED + .withDescription("Game Session workload required") + .asRuntimeException(); + if (request == null || !request.hasLease() || !request.getUnknownFields().asMap().isEmpty()) + throw new IllegalArgumentException("Malformed Account admission abort request"); + var evidence = AccountGameplayAdmissionLeaseWireCodec.parseReference(request.getLease()); + UUID decision = + request.hasBindingDecisionId() ? decision(request.getBindingDecisionId()) : null; + if (!namespace.equals(evidence.carrier().get("targetNamespace")) + || !peer.uri().equals(evidence.carrier().get("callerWorkload"))) + throw Status.PERMISSION_DENIED + .withDescription("Admission lease caller mismatch") + .asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION + .withDescription("Owned Account transaction required") + .asRuntimeException(); + return Objects.requireNonNull( + transaction.execute( + ignored -> { + AccountGameplayAdmissionLeaseOperation prior; + try { + prior = + repository + .readExact(evidence) + .orElseThrow(() -> new AbortDeniedException("ADMISSION_LEASE_UNRESOLVED")); + } catch (AccountGameplayAdmissionLeaseRepository.IdentityConflictException failure) { + throw conflict(); + } + if (prior.state() == State.COMMITTED) + throw new AbortDeniedException("ADMISSION_LEASE_NOT_ABORTABLE"); + if (prior.state() == State.ABORTED) { + if (!Objects.equals(prior.bindingDecisionId(), decision)) throw conflict(); + return prior; + } + try { + return repository.recordAborted(evidence, decision, UUID.randomUUID()); + } catch (AccountGameplayAdmissionLeaseRepository.IdentityConflictException failure) { + throw conflict(); + } + })); + } + + private static UUID decision(String text) { + try { + UUID value = UUID.fromString(text); + if (!value.toString().equals(text) || value.version() != 4 || value.variant() != 2) + throw new IllegalArgumentException(); + return value; + } catch (IllegalArgumentException ignored) { + throw new IllegalArgumentException("Malformed Account admission abort request"); + } + } + + private static AbortDeniedException conflict() { + return new AbortDeniedException("IDEMPOTENCY_CONFLICT"); + } + + /** Produced domain denial; no evidence or storage failure details are exposed. */ + public static final class AbortDeniedException extends IllegalStateException { + private static final long serialVersionUID = 1L; + private final String code; + + private AbortDeniedException(String code) { + super("Account admission abort denied"); + this.code = code; + } + + public String code() { + return code; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java index f9d314bdba..72d774ff1c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java @@ -304,8 +304,16 @@ private static void requireUuidV4(UUID value) { throw new IllegalArgumentException("Canonical non-nil UUIDv4 identity required"); } - private static IllegalStateException conflict() { - return new IllegalStateException("Exact admission operation identity conflict"); + private static IdentityConflictException conflict() { + return new IdentityConflictException(); + } + + static final class IdentityConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + IdentityConflictException() { + super("Exact admission operation identity conflict"); + } } record Allocation(UUID accountId, UUID requestId, UUID leaseId, long leaseFence) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java new file mode 100644 index 0000000000..f29fd36a2a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Reads the canonical Account lifecycle operation table as a fail-closed admission denial + * predicate. It proves no producer identity, World result, source finalization, current serving + * state, or admission permission. + */ +public final class AccountLifecyclePendingDenialReader { + private static final String ACCOUNT_LOCK_SQL = + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE"; + private static final String PENDING_SQL = + "SELECT EXISTS (SELECT 1 FROM account_lifecycle_serving_operations " + + "WHERE account_uuid = ? AND tenant_uuid = ? " + + "AND status IN ('PENDING', 'WORLD_TERMINAL'))"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + + public AccountLifecyclePendingDenialReader(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Requires no unresolved lifecycle operation for the exact Account/tenant pair. + * + *

The existing writable owner transaction must be REPEATABLE_READ or SERIALIZABLE. The + * canonical journal's BEFORE INSERT row-version fence forces an older snapshot waiting on the + * persisted Account lock to fail with a serialization error instead of reading a stale clear + * predicate. Both a pending intent and a correlated World terminal receipt remain denial + * evidence. + */ + public void requireNoPending(UUID accountUuid, UUID tenantUuid) { + requireWritableOwnerTransaction(); + requireUuid(accountUuid, "Account UUID"); + requireUuid(tenantUuid, "tenant UUID"); + + try { + Record account = dsl.fetchOne(ACCOUNT_LOCK_SQL, accountUuid); + if (account == null || !accountUuid.equals(account.get(0, UUID.class))) { + throw new PendingStateUnavailableException( + "Account lifecycle pending state could not be read"); + } + Record pendingRecord = dsl.fetchOne(PENDING_SQL, accountUuid, tenantUuid); + Boolean pending = pendingRecord == null ? null : pendingRecord.get(0, Boolean.class); + if (pending == null) { + throw new PendingStateUnavailableException( + "Account lifecycle pending state could not be read"); + } + if (pending) { + throw new PendingOperationException( + "Account lifecycle invalidation is unresolved for this Account and tenant"); + } + } catch (PendingOperationException | PendingStateUnavailableException denied) { + throw denied; + } catch (DataAccessException unavailable) { + throw new PendingStateUnavailableException( + "Account lifecycle pending state could not be read", unavailable); + } + } + + private static void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account lifecycle pending read requires an owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Account lifecycle pending read requires a writable transaction"); + } + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (isolation == null + || (isolation != TransactionDefinition.ISOLATION_REPEATABLE_READ + && isolation != TransactionDefinition.ISOLATION_SERIALIZABLE)) { + throw new IllegalStateException( + "Account lifecycle pending read requires REPEATABLE_READ or SERIALIZABLE isolation"); + } + } + + private static void requireUuid(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + public static final class PendingOperationException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public PendingOperationException(String message) { + super(message); + } + } + + public static final class PendingStateUnavailableException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public PendingStateUnavailableException(String message) { + super(message); + } + + public PendingStateUnavailableException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java index 7f910b7272..68e9ffe342 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountLifecyclePendingDenialReader; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountRepository; import org.springframework.transaction.TransactionDefinition; @@ -35,6 +36,7 @@ public final class AccountGameplayPublicAdmissionSourceReader { private final AccountRepository accounts; private final AccountDemoTenantEntitlementRepository entitlements; private final AccountGameplayTokenIdentityFenceRepository tokenFences; + private final AccountLifecyclePendingDenialReader lifecyclePendingDenials; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -43,11 +45,13 @@ public AccountGameplayPublicAdmissionSourceReader( AccountMembershipRoleSourceReader membershipSources, AccountRepository accounts, AccountDemoTenantEntitlementRepository entitlements, - AccountGameplayTokenIdentityFenceRepository tokenFences) { + AccountGameplayTokenIdentityFenceRepository tokenFences, + AccountLifecyclePendingDenialReader lifecyclePendingDenials) { this.membershipSources = Objects.requireNonNull(membershipSources); this.accounts = Objects.requireNonNull(accounts); this.entitlements = Objects.requireNonNull(entitlements); this.tokenFences = Objects.requireNonNull(tokenFences); + this.lifecyclePendingDenials = Objects.requireNonNull(lifecyclePendingDenials); } /** Captures exact Account owner sources under the caller's existing serialized transaction. */ @@ -65,6 +69,7 @@ public AccountGameplayPublicAdmissionSourceSnapshot readCurrent( AccountMembershipRoleSourceSnapshot membership = membershipSources.readCurrent(accountId, tenantId); requireMembership(membership, accountId, tenantId, identity); + lifecyclePendingDenials.requireNoPending(accountId, tenantId); Account account = accounts .findByAccountUuid(accountId) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcService.java new file mode 100644 index 0000000000..063e68c4a0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcService.java @@ -0,0 +1,71 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseServiceGrpc; +import net.firedevops.firemud.account.v1.GameplayAdmissionLeaseState; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionAbortOwner; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionAbortOwner.AbortDeniedException; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.shared.v1.ErrorDetail; + +/** Unregistered abort-only transport. Every other inherited method remains unimplemented. */ +public final class AccountGameplayAdmissionLeaseGrpcService + extends AccountGameplayAdmissionLeaseServiceGrpc.AccountGameplayAdmissionLeaseServiceImplBase { + private final AccountGameplayAdmissionAbortOwner owner; + + public AccountGameplayAdmissionLeaseGrpcService(AccountGameplayAdmissionAbortOwner owner) { + this.owner = Objects.requireNonNull(owner); + } + + @Override + public void abortGameplayAdmissionLease( + AbortGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + AbortGameplayAdmissionLeaseResponse response; + try { + var aborted = owner.abort(request); + if (aborted.state() != State.ABORTED) + throw new IllegalStateException("Abort result required"); + response = + AbortGameplayAdmissionLeaseResponse.newBuilder() + .setOperation( + AccountGameplayAdmissionLeaseWireCodec.encodeOperation( + aborted.evidence(), + GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED, + aborted.bindingDecisionId(), + aborted.orphanCleanupId())) + .build(); + } catch (AbortDeniedException failure) { + response = + AbortGameplayAdmissionLeaseResponse.newBuilder() + .setDenied( + ErrorDetail.newBuilder() + .setCode(failure.code()) + .setMessage("Account admission abort denied")) + .build(); + } catch (StatusRuntimeException failure) { + observer.onError(failure); + return; + } catch (IllegalArgumentException failure) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Malformed Account admission abort request") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Account admission abort unavailable") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V86__account_lifecycle_serving_operations.sql b/services/account-service/src/main/resources/db/migration/V86__account_lifecycle_serving_operations.sql new file mode 100644 index 0000000000..9b05b42da4 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V86__account_lifecycle_serving_operations.sql @@ -0,0 +1,191 @@ +-- Immutable Account pending-intent and World terminal-receipt correlation only. +-- No logical Account state/source/generation/fence/outbox mutation, serving authorization producer, +-- expiry, or retained-row backfill. BEFORE INSERT versions the unchanged Account row to fence +-- older REPEATABLE_READ and SERIALIZABLE snapshots. +CREATE TABLE account_lifecycle_serving_operations ( + request_id UUID PRIMARY KEY + CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + actor_account_uuid UUID NOT NULL + CHECK (actor_account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) + REFERENCES accounts (account_uuid) ON DELETE RESTRICT, + account_uuid UUID NOT NULL, + account_id BIGINT NOT NULL CHECK (account_id > 0), + account_provenance VARCHAR(40) NOT NULL + CHECK (account_provenance IN ( + 'ACCOUNT_V29_MIGRATION', 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT')), + tenant_uuid UUID NOT NULL + CHECK (tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + purpose VARCHAR(48) NOT NULL CHECK (purpose = 'WORLD_ACTIVATION_INVALIDATION'), + caller_proof_binding BYTEA NOT NULL + CHECK (octet_length(caller_proof_binding) BETWEEN 1 AND 16384), + world_activation_request_id UUID NOT NULL + CHECK (world_activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + world_activation_request_digest VARCHAR(71) NOT NULL + CHECK (world_activation_request_digest ~ '^sha256:[0-9a-f]{64}$'), + world_activation_request_bytes BYTEA NOT NULL + CHECK (octet_length(world_activation_request_bytes) BETWEEN 1 AND 1048576), + world_activation_preparing_evidence BYTEA NOT NULL + CHECK (octet_length(world_activation_preparing_evidence) BETWEEN 1 AND 1048576), + request_payload BYTEA NOT NULL + CHECK (octet_length(request_payload) BETWEEN 1 AND 2200000), + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + account_stream_key VARCHAR(2048) NOT NULL, + account_generation BIGINT NOT NULL CHECK (account_generation > 0), + account_source_version BIGINT NOT NULL CHECK (account_source_version > 0), + account_issuance_fence BIGINT NOT NULL CHECK (account_issuance_fence > 0), + account_fence_source_version BIGINT NOT NULL CHECK (account_fence_source_version > 0), + checkpoint_sequence BIGINT NOT NULL CHECK (checkpoint_sequence >= 0), + checkpoint_event_sequence BIGINT CHECK (checkpoint_event_sequence > 0), + checkpoint_event_request_id VARCHAR(512), + checkpoint_event_id VARCHAR(512), + checkpoint_event_digest VARCHAR(512), + checkpoint_payload BYTEA NOT NULL CHECK (octet_length(checkpoint_payload) <= 1048576), + capture_payload BYTEA NOT NULL + CHECK (octet_length(capture_payload) BETWEEN 1 AND 1100000), + capture_digest VARCHAR(71) NOT NULL CHECK (capture_digest ~ '^sha256:[0-9a-f]{64}$'), + status VARCHAR(16) NOT NULL CHECK (status IN ('PENDING', 'WORLD_TERMINAL')), + world_result_outcome VARCHAR(16), + world_result_payload BYTEA, + world_result_digest VARCHAR(71), + world_terminal_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_lifecycle_serving_account_identity_fk + FOREIGN KEY (account_uuid, account_id, account_provenance) + REFERENCES accounts (account_uuid, account_uuid_source_numeric_id, account_uuid_provenance) + ON DELETE RESTRICT, + CONSTRAINT account_lifecycle_serving_stream_fk + FOREIGN KEY (account_stream_key) + REFERENCES account_authority_source_records (outbox_stream_key) ON DELETE RESTRICT, + CONSTRAINT account_lifecycle_serving_checkpoint_event_fk + FOREIGN KEY (account_stream_key, checkpoint_event_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT, + CONSTRAINT account_lifecycle_serving_checkpoint_shape CHECK ( + account_stream_key = 'account:auth-authority:v1:account/' || account_uuid::TEXT + AND account_generation = account_source_version + AND account_issuance_fence = account_generation + AND account_fence_source_version = account_source_version + AND account_generation = checkpoint_sequence + 1 + AND account_source_version = checkpoint_sequence + 1 + AND account_issuance_fence = checkpoint_sequence + 1 + AND account_fence_source_version = checkpoint_sequence + 1 + AND ( + (checkpoint_sequence = 0 + AND checkpoint_event_sequence IS NULL + AND checkpoint_event_request_id IS NULL + AND checkpoint_event_id IS NULL + AND checkpoint_event_digest IS NULL + AND octet_length(checkpoint_payload) = 0) + OR + (checkpoint_sequence > 0 + AND checkpoint_event_sequence = checkpoint_sequence + AND checkpoint_event_request_id IS NOT NULL + AND length(btrim(checkpoint_event_request_id)) > 0 + AND checkpoint_event_id IS NOT NULL + AND length(btrim(checkpoint_event_id)) > 0 + AND checkpoint_event_digest IS NOT NULL + AND checkpoint_event_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(checkpoint_payload) BETWEEN 1 AND 1048576) + )), + CONSTRAINT account_lifecycle_serving_result_shape CHECK ( + (status = 'PENDING' + AND world_result_outcome IS NULL + AND world_result_payload IS NULL + AND world_result_digest IS NULL + AND world_terminal_at IS NULL) + OR + (status = 'WORLD_TERMINAL' + AND world_result_outcome IN ('COMMITTED', 'ABORTED') + AND world_result_payload IS NOT NULL + AND octet_length(world_result_payload) BETWEEN 1 AND 2200000 + AND world_result_digest IS NOT NULL + AND world_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_terminal_at IS NOT NULL) + ) +); + +CREATE UNIQUE INDEX account_lifecycle_serving_one_pending_scope_uq + ON account_lifecycle_serving_operations (account_uuid, tenant_uuid) + WHERE status IN ('PENDING', 'WORLD_TERMINAL'); + +-- [jooq ignore start] +CREATE FUNCTION account_lifecycle_serving_account_row_version_fence() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + touched_rows INTEGER; +BEGIN + UPDATE accounts + SET id = id + WHERE account_uuid = NEW.account_uuid + AND id = NEW.account_id + AND account_uuid_provenance = NEW.account_provenance + AND account_uuid_source_numeric_id = NEW.account_id; + GET DIAGNOSTICS touched_rows = ROW_COUNT; + IF touched_rows <> 1 THEN + RAISE EXCEPTION 'Account lifecycle operation requires the exact persisted Account row' + USING ERRCODE = '23514', + CONSTRAINT = 'account_lifecycle_serving_account_row_version_fence'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_lifecycle_serving_account_row_version_fence + BEFORE INSERT ON account_lifecycle_serving_operations + FOR EACH ROW EXECUTE FUNCTION account_lifecycle_serving_account_row_version_fence(); + +CREATE FUNCTION account_lifecycle_serving_operation_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF OLD.status <> 'PENDING' OR NEW.status <> 'WORLD_TERMINAL' + OR (to_jsonb(NEW) - ARRAY['status', 'world_result_outcome', 'world_result_payload', + 'world_result_digest', 'world_terminal_at']) + IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['status', 'world_result_outcome', 'world_result_payload', + 'world_result_digest', 'world_terminal_at']) THEN + RAISE EXCEPTION 'Account lifecycle request and capture are immutable; only one terminal World receipt may be added' + USING ERRCODE = '23514', CONSTRAINT = 'account_lifecycle_serving_operation_immutable'; + END IF; + NEW.world_terminal_at := CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_lifecycle_serving_operation_update + BEFORE UPDATE ON account_lifecycle_serving_operations + FOR EACH ROW EXECUTE FUNCTION account_lifecycle_serving_operation_update_guard(); + +CREATE FUNCTION account_lifecycle_serving_operation_delete_denied() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account lifecycle pending operations are retained' + USING ERRCODE = '23514', CONSTRAINT = 'account_lifecycle_serving_operation_no_delete'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_lifecycle_serving_operation_delete + BEFORE DELETE ON account_lifecycle_serving_operations + FOR EACH ROW EXECUTE FUNCTION account_lifecycle_serving_operation_delete_denied(); + +CREATE FUNCTION account_lifecycle_serving_operation_truncate_denied() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account lifecycle pending-operation history cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_lifecycle_serving_operation_no_truncate'; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_lifecycle_serving_operation_truncate + BEFORE TRUNCATE ON account_lifecycle_serving_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_lifecycle_serving_operation_truncate_denied(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index d21e4f5875..dcf719d48f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -8,15 +8,20 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -50,6 +55,156 @@ static void stop() { POSTGRES.stop(); } + @Test + void actualAbortOwnerRecoversLostResponseAndRetainsOriginalDecisionAndCleanup() throws Exception { + var context = context(null); + var original = pending(context, account(context)); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var owner = + new AccountGameplayAdmissionAbortOwner( + repository, new DataSourceTransactionManager(context.dataSource()), "test"); + UUID decision = UUID.randomUUID(); + var request = + AbortGameplayAdmissionLeaseRequest.newBuilder() + .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(original)) + .setBindingDecisionId(decision.toString()) + .build(); + // The trusted context is synthetic: this exercises real SQL ownership, never actual mTLS. + syntheticAbortPeer().call(() -> owner.abort(request)); // Discard the first response. + var stored = tx(context, () -> repository.readExact(original).orElseThrow()); + var replay = syntheticAbortPeer().call(() -> owner.abort(request)); + assertThat(replay).isEqualTo(stored); + assertThat(replay.state()).isEqualTo(State.ABORTED); + assertThat(replay.bindingDecisionId()).isEqualTo(decision); + assertThat(replay.orphanCleanupId()).isNotNull(); + assertThat(replay.evidence().canonicalJson()).isEqualTo(original.canonicalJson()); + assertThat(replay.evidence().sha256()).isEqualTo(original.sha256()); + assertThat(AccountGameplayAdmissionLeaseWireCodec.encodeReference(replay.evidence())) + .isEqualTo(request.getLease()); + for (var changed : + List.of( + request.toBuilder().clearBindingDecisionId().build(), + request.toBuilder().setBindingDecisionId(UUID.randomUUID().toString()).build())) { + assertThatThrownBy(() -> syntheticAbortPeer().call(() -> owner.abort(changed))) + .isInstanceOf(AccountGameplayAdmissionAbortOwner.AbortDeniedException.class) + .satisfies( + failure -> + assertThat( + ((AccountGameplayAdmissionAbortOwner.AbortDeniedException) failure) + .code()) + .isEqualTo("IDEMPOTENCY_CONFLICT")); + assertThat(tx(context, () -> repository.readExact(original))).contains(stored); + } + } + + @Test + void concurrentActualAbortOwnersRetainOneCleanupAndDenySubstitutionOrCommittedLease() + throws Exception { + var context = context(null); + UUID account = account(context); + var original = pending(context, account); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var owner = + new AccountGameplayAdmissionAbortOwner( + repository, new DataSourceTransactionManager(context.dataSource()), "test"); + var request = + AbortGameplayAdmissionLeaseRequest.newBuilder() + .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(original)) + .build(); + var start = new CountDownLatch(1); + Callable abort = + () -> { + if (!start.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("start timeout"); + try { + // DriverManagerDataSource supplies each thread's owned transaction its own SQL + // connection. + return syntheticAbortPeer().call(() -> owner.abort(request)); + } catch (RuntimeException failure) { + Throwable cause = failure; + while (cause != null) { + if (cause instanceof java.sql.SQLException sql && "40001".equals(sql.getSQLState())) + return null; + cause = cause.getCause(); + } + throw failure; + } + }; + AccountGameplayAdmissionLeaseOperation left; + AccountGameplayAdmissionLeaseOperation right; + try (var executor = Executors.newFixedThreadPool(2)) { + var first = executor.submit(abort); + var second = executor.submit(abort); + start.countDown(); + left = first.get(30, TimeUnit.SECONDS); + right = second.get(30, TimeUnit.SECONDS); + } + assertThat(left != null || right != null).isTrue(); + var replay = syntheticAbortPeer().call(() -> owner.abort(request)); + if (left != null) assertThat(left).isEqualTo(replay); + if (right != null) assertThat(right).isEqualTo(replay); + assertThat(replay.state()).isEqualTo(State.ABORTED); + assertThat(replay.bindingDecisionId()).isNull(); + assertThat(replay.orphanCleanupId()).isNotNull(); + assertThat(tx(context, () -> repository.readExact(original))).contains(replay); + assertThat(context.dsl().fetchCount(DSL.table("account_gameplay_admission_lease_operations"))) + .isEqualTo(1); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT count(DISTINCT orphan_cleanup_id) AS cleanups FROM account_gameplay_admission_lease_operations")) + .get("cleanups", Long.class)) + .isEqualTo(1L); + var changedCarrier = new LinkedHashMap<>(original.carrier()); + changedCarrier.put("leaseId", UUID.randomUUID().toString()); + var changed = + request.toBuilder() + .setLease( + AccountGameplayAdmissionLeaseWireCodec.encodeReference( + AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier))) + .build(); + assertThatThrownBy(() -> syntheticAbortPeer().call(() -> owner.abort(changed))) + .isInstanceOf(AccountGameplayAdmissionAbortOwner.AbortDeniedException.class); + var mismatchedRequest = + request.toBuilder() + .setLease(request.getLease().toBuilder().setRequestId(UUID.randomUUID().toString())) + .build(); + assertThatThrownBy(() -> syntheticAbortPeer().call(() -> owner.abort(mismatchedRequest))) + .isInstanceOf(IllegalArgumentException.class); + var changedDecision = + request.toBuilder().setBindingDecisionId(UUID.randomUUID().toString()).build(); + assertThatThrownBy(() -> syntheticAbortPeer().call(() -> owner.abort(changedDecision))) + .isInstanceOf(AccountGameplayAdmissionAbortOwner.AbortDeniedException.class); + assertThat(tx(context, () -> repository.readExact(original))).contains(replay); + + var committedEvidence = pending(context, account); + var committed = + tx(context, () -> repository.recordCommitted(committedEvidence, UUID.randomUUID())); + var committedRequest = + request.toBuilder() + .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(committedEvidence)) + .build(); + assertThatThrownBy(() -> syntheticAbortPeer().call(() -> owner.abort(committedRequest))) + .isInstanceOf(AccountGameplayAdmissionAbortOwner.AbortDeniedException.class) + .satisfies( + failure -> + assertThat( + ((AccountGameplayAdmissionAbortOwner.AbortDeniedException) failure).code()) + .isEqualTo("ADMISSION_LEASE_NOT_ABORTABLE")); + assertThat(tx(context, () -> repository.readExact(committedEvidence))).contains(committed); + assertThat(committed.orphanCleanupId()).isNull(); + } + + /** Synthetic trusted caller only; the existing carriers remain fabricated storage fixtures. */ + private static io.grpc.Context syntheticAbortPeer() { + return io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") + .orElseThrow()); + } + @Test void lostResponseRecoveryUsesOriginalRequestWithoutReconstructingServerLeaseIdentity() { var context = context(null); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java index 3d09ba6ec8..1ecf163634 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -30,6 +30,7 @@ import java.nio.file.Path; import java.security.MessageDigest; import java.sql.SQLException; +import java.sql.Timestamp; import java.time.Clock; import java.time.Instant; import java.time.LocalDateTime; @@ -90,6 +91,7 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository.TokenRevokedException; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLifecyclePendingDenialReader; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; @@ -1147,6 +1149,172 @@ void publicAdmissionSourceCaptureRejectsDurablePendingTokenRevocation() throws E .isInstanceOf(TokenRevokedException.class); } + @Test + void pendingAndWorldTerminalLifecycleRowsDenyWithoutChangingOwnerState() throws Exception { + for (String status : List.of("PENDING", "WORLD_TERMINAL")) { + AdmissionSourceFixture fixture = newAdmissionSourceFixture(); + String accountBefore = + accountSemanticSnapshot(fixture.harness().dsl(), fixture.harness().accountId()); + String sourceBefore = + accountAuthoritySourceSnapshot(fixture.harness().dsl(), fixture.harness().accountId()); + long authorityEventsBefore = + accountAuthorityEventCount(fixture.harness().dsl(), fixture.harness().accountId()); + UUID requestId = insertLifecycleDenialFixture(fixture, fixture.tenantId(), status); + + assertThatThrownBy( + () -> + inRepeatableReadTransaction( + fixture.harness().context(), + () -> + fixture + .admissionReader() + .readCurrent( + fixture.harness().accountId(), + fixture.tenantId(), + fixture.identity()))) + .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class) + .hasMessage("Account lifecycle invalidation is unresolved for this Account and tenant"); + + assertThat(accountSemanticSnapshot(fixture.harness().dsl(), fixture.harness().accountId())) + .isEqualTo(accountBefore); + assertThat( + accountAuthoritySourceSnapshot( + fixture.harness().dsl(), fixture.harness().accountId())) + .isEqualTo(sourceBefore); + assertThat( + Objects.requireNonNull( + fixture + .harness() + .dsl() + .fetchOne( + "SELECT status FROM account_lifecycle_serving_operations " + + "WHERE request_id = ?", + requestId)) + .get(0, String.class)) + .isEqualTo(status); + assertThat(accountAuthorityEventCount(fixture.harness().dsl(), fixture.harness().accountId())) + .isEqualTo(authorityEventsBefore); + assertThat( + Objects.requireNonNull( + fixture + .harness() + .dsl() + .fetchOne( + "SELECT state FROM account_gameplay_token_identity_fences " + + "WHERE operation_id = ?", + fixture.identity().operationId())) + .get(0, String.class)) + .isEqualTo("ACTIVE"); + } + } + + @Test + void lifecycleJournalInsertInvalidatesOlderRepeatableReadAndSerializableSnapshots() + throws Exception { + for (int isolation : + List.of( + TransactionDefinition.ISOLATION_REPEATABLE_READ, + TransactionDefinition.ISOLATION_SERIALIZABLE)) { + AdmissionSourceFixture fixture = newAdmissionSourceFixture(); + DSLContext dsl = fixture.harness().dsl(); + UUID accountId = fixture.harness().accountId(); + String accountBefore = accountSemanticSnapshot(dsl, accountId); + String sourceBefore = accountAuthoritySourceSnapshot(dsl, accountId); + long authorityEventsBefore = accountAuthorityEventCount(dsl, accountId); + CountDownLatch writerLockedAccount = new CountDownLatch(1); + CountDownLatch readerSnapshotEstablished = new CountDownLatch(1); + CountDownLatch readerIsChecking = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + TransactionTemplate writerTransaction = + new TransactionTemplate(fixture.harness().context().manager()); + writerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var writer = + executor.submit( + () -> + writerTransaction.execute( + transaction -> { + Record lockedAccount = + dsl.fetchOne( + "SELECT account_uuid FROM accounts " + + "WHERE account_uuid = ? FOR UPDATE", + accountId); + if (lockedAccount == null) { + throw new IllegalStateException( + "Lifecycle writer could not lock the exact Account"); + } + writerLockedAccount.countDown(); + awaitLatch( + readerSnapshotEstablished, "reader to establish its stale snapshot"); + awaitLatch(readerIsChecking, "reader to attempt its Account lock"); + insertLifecycleDenialFixture(fixture, fixture.tenantId(), "PENDING"); + return null; + })); + + var reader = + executor.submit( + () -> { + awaitLatch(writerLockedAccount, "lifecycle writer to lock the Account"); + TransactionTemplate readerTransaction = + new TransactionTemplate(fixture.harness().context().manager()); + readerTransaction.setIsolationLevel(isolation); + try { + readerTransaction.execute( + transaction -> { + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM account_lifecycle_serving_operations " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountId, + fixture.tenantId())); + readerSnapshotEstablished.countDown(); + readerIsChecking.countDown(); + new AccountLifecyclePendingDenialReader(dsl) + .requireNoPending(accountId, fixture.tenantId()); + return null; + }); + return null; + } catch (RuntimeException failure) { + return failure; + } + }); + + RuntimeException readerFailure = reader.get(15, TimeUnit.SECONDS); + writer.get(15, TimeUnit.SECONDS); + assertThat(readerFailure) + .as("an old %s snapshot cannot observe a clear lifecycle predicate", isolation) + .isInstanceOf( + AccountLifecyclePendingDenialReader.PendingStateUnavailableException.class); + assertThat(sqlState(readerFailure)).isEqualTo("40001"); + assertThat(accountSemanticSnapshot(dsl, accountId)).isEqualTo(accountBefore); + assertThat(accountAuthoritySourceSnapshot(dsl, accountId)).isEqualTo(sourceBefore); + assertThat(accountAuthorityEventCount(dsl, accountId)).isEqualTo(authorityEventsBefore); + } finally { + readerSnapshotEstablished.countDown(); + readerIsChecking.countDown(); + executor.shutdownNow(); + } + } + } + + @Test + void lifecycleOperationForAnotherTenantDoesNotDenyExactAdmissionScope() throws Exception { + AdmissionSourceFixture fixture = newAdmissionSourceFixture(); + UUID otherTenant = UUID.randomUUID(); + insertLifecycleDenialFixture(fixture, otherTenant, "PENDING"); + + var captured = + inRepeatableReadTransaction( + fixture.harness().context(), + () -> + fixture + .admissionReader() + .readCurrent( + fixture.harness().accountId(), fixture.tenantId(), fixture.identity())); + + assertThat(captured.membershipSource().membership().tenantId()).isEqualTo(fixture.tenantId()); + } + @Test void membershipRoleSnapshotMustStillMatchItsCommittedCurrentEvent() throws Exception { AdmissionSourceFixture fixture = newAdmissionSourceFixture(); @@ -1467,7 +1635,11 @@ private AdmissionSourceFixture newAdmissionSourceFixture() throws Exception { sources, generations, memberships, pairs, roles, outbox, tenantAuthorityEvents); AccountGameplayPublicAdmissionSourceReader admissionReader = new AccountGameplayPublicAdmissionSourceReader( - membershipReader, accounts, entitlements, tokenFences); + membershipReader, + accounts, + entitlements, + tokenFences, + new AccountLifecyclePendingDenialReader(dsl)); return new AdmissionSourceFixture( harness, tenantId, @@ -1483,6 +1655,137 @@ private AdmissionSourceFixture newAdmissionSourceFixture() throws Exception { identity); } + /** + * Creates opaque shape-valid storage evidence only. This fixture does not represent an + * authenticated caller, valid World request, or actual invalidation publisher. + */ + private UUID insertLifecycleDenialFixture( + AdmissionSourceFixture fixture, UUID tenantId, String status) { + UUID requestId = UUID.randomUUID(); + inTransaction( + fixture.harness().context(), + () -> { + DSLContext dsl = fixture.harness().dsl(); + Account account = + new AccountRepository(dsl) + .findByAccountUuid(fixture.harness().accountId()) + .orElseThrow(); + String streamKey = "account:auth-authority:v1:account/" + fixture.harness().accountId(); + Record source = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_generation, current_source_version, " + + "current_issuance_fence, current_issuance_fence_source_version, " + + "last_outbox_sequence " + + "FROM account_authority_source_records WHERE outbox_stream_key = ?", + streamKey)); + Long checkpointSequenceValue = source.get("last_outbox_sequence", Long.class); + if (checkpointSequenceValue == null || checkpointSequenceValue < 0L) { + throw new IllegalStateException( + "Current Account authority source checkpoint is unavailable"); + } + long checkpointSequence = checkpointSequenceValue; + Record checkpoint = + checkpointSequence == 0L + ? null + : Objects.requireNonNull( + dsl.fetchOne( + "SELECT request_id, event_id, event_digest, payload " + + "FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = ?", + streamKey, + checkpointSequence)); + String terminalOutcome = "WORLD_TERMINAL".equals(status) ? "ABORTED" : null; + byte[] terminalPayload = + "WORLD_TERMINAL".equals(status) + ? "opaque-storage-shape".getBytes(StandardCharsets.US_ASCII) + : null; + String digest = "sha256:" + "a".repeat(64); + dsl.execute( + "INSERT INTO account_lifecycle_serving_operations (" + + "request_id, actor_account_uuid, account_uuid, account_id, account_provenance, " + + "tenant_uuid, purpose, caller_proof_binding, world_activation_request_id, " + + "world_activation_request_digest, world_activation_request_bytes, " + + "world_activation_preparing_evidence, request_payload, request_digest, " + + "account_stream_key, account_generation, account_source_version, " + + "account_issuance_fence, account_fence_source_version, checkpoint_sequence, " + + "checkpoint_event_sequence, checkpoint_event_request_id, checkpoint_event_id, " + + "checkpoint_event_digest, checkpoint_payload, capture_payload, capture_digest, " + + "status, world_result_outcome, world_result_payload, world_result_digest, " + + "world_terminal_at) VALUES (?, ?, ?, ?, ?, ?, 'WORLD_ACTIVATION_INVALIDATION', " + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + requestId, + fixture.harness().accountId(), + fixture.harness().accountId(), + account.getId(), + account.getAccountUuidProvenance().name(), + tenantId, + new byte[] {1}, + UUID.randomUUID(), + digest, + new byte[] {1}, + new byte[] {1}, + new byte[] {1}, + digest, + streamKey, + source.get("current_generation", Long.class), + source.get("current_source_version", Long.class), + source.get("current_issuance_fence", Long.class), + source.get("current_issuance_fence_source_version", Long.class), + checkpointSequence, + checkpoint == null ? null : checkpointSequence, + checkpoint == null ? null : checkpoint.get("request_id", String.class), + checkpoint == null ? null : checkpoint.get("event_id", String.class), + checkpoint == null ? null : checkpoint.get("event_digest", String.class), + checkpoint == null ? new byte[0] : checkpoint.get("payload", byte[].class), + new byte[] {1}, + digest, + status, + terminalOutcome, + terminalPayload, + "WORLD_TERMINAL".equals(status) ? digest : null, + "WORLD_TERMINAL".equals(status) ? Timestamp.from(Instant.now()) : null); + return null; + }); + return requestId; + } + + private static long accountAuthorityEventCount(DSLContext dsl, UUID accountId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:account/" + accountId)) + .get(0, Long.class); + } + + private static String accountSemanticSnapshot(DSLContext dsl, UUID accountId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(account_row)::text FROM accounts account_row " + + "WHERE account_uuid = ?", + accountId)) + .get(0, String.class); + } + + private static String accountAuthoritySourceSnapshot(DSLContext dsl, UUID accountId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(source_row)::text FROM account_authority_source_records source_row " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:account/" + accountId)) + .get(0, String.class); + } + + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException && sqlException.getSQLState() != null) { + return sqlException.getSQLState(); + } + } + return null; + } + private static FreshTenantCreationEvidence freshAdmissionTenantEvidence(UUID tenantId) { UUID requestId = UUID.randomUUID(); UUID operationId = UUID.randomUUID(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwnerTest.java new file mode 100644 index 0000000000..acc29d1582 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwnerTest.java @@ -0,0 +1,304 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Owner/storage/transaction doubles only; fabricated carriers prove no current source authority. + */ +public class AccountGameplayAdmissionAbortOwnerTest { + private final AccountGameplayAdmissionLeaseRepository repository = + mock(AccountGameplayAdmissionLeaseRepository.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final TransactionStatus status = mock(TransactionStatus.class); + private final AccountGameplayAdmissionAbortOwner owner = + new AccountGameplayAdmissionAbortOwner(repository, manager, "test"); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void missingWrongAndCrossNamespacePeersNeverReachStorage() { + assertThatThrownBy(() -> owner.abort(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + f -> + assertThat(Status.fromThrowable(f).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + for (String uri : + List.of( + "spiffe://firemud/ns/test/sa/account-service", + "spiffe://firemud/ns/other/sa/game-session-service")) { + assertThatThrownBy(() -> peer(uri).call(() -> owner.abort(request()))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + f -> + assertThat(Status.fromThrowable(f).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsAmbientTransactionBeforeOwnedTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> peer().call(() -> owner.abort(request()))) + .isInstanceOf(StatusRuntimeException.class); + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsAmbientSynchronizationBeforeOwnedTransaction() { + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> peer().call(() -> owner.abort(request()))) + .isInstanceOf(StatusRuntimeException.class); + verifyNoInteractions(repository, manager); + } + + @Test + void pendingAbortAndLostResponseRetryRetainOneCleanupAndOriginalExpiredEvidence() + throws Exception { + var original = fixture(); + var stored = + new AtomicReference<>( + new AccountGameplayAdmissionLeaseOperation(original, State.PENDING, null, null)); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.readExact(any())).thenAnswer(invocation -> Optional.of(stored.get())); + when(repository.recordAborted(eq(original), eq(null), any())) + .thenAnswer( + invocation -> { + var value = + new AccountGameplayAdmissionLeaseOperation( + original, State.ABORTED, null, invocation.getArgument(2)); + stored.set(value); + return value; + }); + var first = peer().call(() -> owner.abort(request())); + var retry = peer().call(() -> owner.abort(request())); + assertThat(retry).isSameAs(first); + assertThat(first.evidence()).isEqualTo(original); + assertThat(first.bindingDecisionId()).isNull(); + assertThat(first.orphanCleanupId().version()).isEqualTo(4); + verify(repository).recordAborted(eq(original), eq(null), eq(first.orphanCleanupId())); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(manager, org.mockito.Mockito.times(2)).getTransaction(definition.capture()); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().isReadOnly()).isFalse(); + verify(manager, org.mockito.Mockito.times(2)).commit(status); + } + + @Test + void suppliedDecisionIsOnlyCorrelationAndChangedPresenceOrValueConflicts() throws Exception { + UUID decision = UUID.randomUUID(); + var aborted = + new AccountGameplayAdmissionLeaseOperation( + fixture(), State.ABORTED, decision, UUID.randomUUID()); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.readExact(any())).thenReturn(Optional.of(aborted)); + var exact = request().toBuilder().setBindingDecisionId(decision.toString()).build(); + assertThat(peer().call(() -> owner.abort(exact))).isSameAs(aborted); + for (var changed : + List.of( + request(), + request().toBuilder().setBindingDecisionId(UUID.randomUUID().toString()).build())) { + assertThatThrownBy(() -> peer().call(() -> owner.abort(changed))) + .isInstanceOf(IllegalStateException.class); + } + verify(repository, never()).recordAborted(any(), any(), any()); + verify(manager, org.mockito.Mockito.times(2)).rollback(status); + } + + @Test + void committedAbsentAndChangedStoredEvidenceDenyAndRollBack() { + when(manager.getTransaction(any())).thenReturn(status); + when(repository.readExact(any())) + .thenReturn( + Optional.of( + new AccountGameplayAdmissionLeaseOperation( + fixture(), State.COMMITTED, UUID.randomUUID(), null))) + .thenReturn(Optional.empty()) + .thenThrow(new AccountGameplayAdmissionLeaseRepository.IdentityConflictException()); + for (int attempt = 0; attempt < 3; attempt++) { + assertThatThrownBy(() -> peer().call(() -> owner.abort(request()))) + .isInstanceOf(IllegalStateException.class); + } + verify(repository, never()).recordAborted(any(), any(), any()); + verify(manager, org.mockito.Mockito.times(3)).rollback(status); + } + + @Test + void failedWriteRollsBackWithoutReturningAnAbort() { + when(manager.getTransaction(any())).thenReturn(status); + when(repository.readExact(any())) + .thenReturn( + Optional.of( + new AccountGameplayAdmissionLeaseOperation(fixture(), State.PENDING, null, null))); + when(repository.recordAborted(any(), any(), any())) + .thenThrow(new IllegalStateException("write failed")); + assertThatThrownBy(() -> peer().call(() -> owner.abort(request()))) + .isInstanceOf(IllegalStateException.class); + verify(manager).rollback(status); + verify(manager, never()).commit(status); + } + + @Test + void mismatchedCarrierNamespaceAndMalformedDecisionFailBeforeSql() { + var carrier = new LinkedHashMap<>(fixture().carrier()); + carrier.put("targetNamespace", "other"); + carrier.put("callerWorkload", "spiffe://firemud/ns/other/sa/game-session-service"); + var wrongCaller = + request().toBuilder() + .setLease( + AccountGameplayAdmissionLeaseWireCodec.encodeReference( + AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier))) + .build(); + assertThatThrownBy(() -> peer().call(() -> owner.abort(wrongCaller))) + .isInstanceOf(StatusRuntimeException.class); + assertThatThrownBy( + () -> + peer() + .call( + () -> owner.abort(request().toBuilder().setBindingDecisionId("").build()))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(repository, manager); + } + + public static AbortGameplayAdmissionLeaseRequest request() { + return AbortGameplayAdmissionLeaseRequest.newBuilder() + .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(fixture())) + .build(); + } + + private static Context peer() { + return peer("spiffe://firemud/ns/test/sa/game-session-service"); + } + + private static Context peer(String uri) { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + } + + /** Deliberately fabricated expired storage carrier, not issuer or current authority evidence. */ + public static AccountGameplayAdmissionLeaseEvidence fixture() { + String account = "11111111-1111-4111-8111-111111111111"; + String tenant = "22222222-2222-4222-8222-222222222222"; + String other = "33333333-3333-4333-8333-333333333333"; + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", "test"); + value.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + value.put("requestId", other); + value.put("leaseId", tenant); + value.put("leaseFence", "1"); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, other); + scope.put("accountId", account); + scope.put("tenantId", tenant); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "1"); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(tenant, "1"), + "membershipAuthorityGeneration", + Map.of(tenant, "1"), + "privateRealmGrantVersions", + List.of())); + value.put("issuanceFence", "1"); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(tenant, "1"), + "membershipAuthorityGeneration", + "1")); + value.put( + "outboxCheckpoints", + List.of( + "account/" + account, + "issuer/firemud-account-service", + "membership/" + account + "/" + tenant, + "tenant/" + tenant) + .stream() + .map( + suffix -> + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:" + suffix, + "outboxSequence", + suffix.startsWith("account/") || suffix.startsWith("issuer/") ? "0" : "1")) + .toList()); + Map token = new LinkedHashMap<>(); + token.put("accountId", account); + for (String key : List.of("operationId", "issuanceRequestId", "tokenJti")) + token.put(key, other); + token.put("tokenSHA256", "a".repeat(64)); + token.put("tokenProfile", "game-session-account-delegation"); + for (String key : List.of("tokenGeneration", "issuanceFence", "tokenIdentityFence")) + token.put(key, "1"); + token.put("issuedAt", "999"); + token.put("notBefore", "999"); + token.put("expiresAt", "1300"); + value.put("tokenIdentityEvidence", token); + value.put("evaluatedAt", "1000000"); + value.put("expiresAt", "1015000"); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(value); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReaderTest.java new file mode 100644 index 0000000000..f7a135eec1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReaderTest.java @@ -0,0 +1,151 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountLifecyclePendingDenialReader; +import net.firedevops.firemud.accountservice.repository.AccountLifecyclePendingDenialReader.PendingOperationException; +import net.firedevops.firemud.accountservice.repository.AccountLifecyclePendingDenialReader.PendingStateUnavailableException; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountLifecyclePendingDenialReaderTest { + private static final UUID ACCOUNT = UUID.randomUUID(); + private static final UUID TENANT = UUID.randomUUID(); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void pendingOperationDeniesAfterLockingExactAccount() { + DSLContext dsl = mock(DSLContext.class); + Record account = accountRow(); + Record pending = mock(Record.class); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, pending); + when(pending.get(0, Boolean.class)).thenReturn(true); + transaction(TransactionDefinition.ISOLATION_REPEATABLE_READ); + + assertThatThrownBy( + () -> new AccountLifecyclePendingDenialReader(dsl).requireNoPending(ACCOUNT, TENANT)) + .isInstanceOf(PendingOperationException.class) + .hasMessage("Account lifecycle invalidation is unresolved for this Account and tenant"); + + var ordered = inOrder(dsl); + ordered + .verify(dsl) + .fetchOne("SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", ACCOUNT); + ordered + .verify(dsl) + .fetchOne( + "SELECT EXISTS (SELECT 1 FROM account_lifecycle_serving_operations " + + "WHERE account_uuid = ? AND tenant_uuid = ? " + + "AND status IN ('PENDING', 'WORLD_TERMINAL'))", + ACCOUNT, + TENANT); + } + + @Test + void noPendingOperationDoesNotTripTheDenialPredicate() { + DSLContext dsl = mock(DSLContext.class); + Record account = accountRow(); + Record pending = mock(Record.class); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, pending); + when(pending.get(0, Boolean.class)).thenReturn(false); + transaction(TransactionDefinition.ISOLATION_SERIALIZABLE); + + new AccountLifecyclePendingDenialReader(dsl).requireNoPending(ACCOUNT, TENANT); + + verify(dsl) + .fetchOne( + "SELECT EXISTS (SELECT 1 FROM account_lifecycle_serving_operations " + + "WHERE account_uuid = ? AND tenant_uuid = ? " + + "AND status IN ('PENDING', 'WORLD_TERMINAL'))", + ACCOUNT, + TENANT); + } + + @Test + void missingAccountAndUnreadablePredicateFailClosed() { + DSLContext missingAccountDsl = mock(DSLContext.class); + when(missingAccountDsl.fetchOne(anyString(), any(Object[].class))).thenReturn(null); + transaction(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy( + () -> + new AccountLifecyclePendingDenialReader(missingAccountDsl) + .requireNoPending(ACCOUNT, TENANT)) + .isInstanceOf(PendingStateUnavailableException.class); + verify(missingAccountDsl) + .fetchOne("SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", ACCOUNT); + + DSLContext unreadableDsl = mock(DSLContext.class); + Record account = accountRow(); + when(unreadableDsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, null); + assertThatThrownBy( + () -> + new AccountLifecyclePendingDenialReader(unreadableDsl) + .requireNoPending(ACCOUNT, TENANT)) + .isInstanceOf(PendingStateUnavailableException.class); + } + + @Test + void ownerQueryFailureFailsClosed() { + DSLContext dsl = mock(DSLContext.class); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenThrow(new DataAccessException("unavailable")); + transaction(TransactionDefinition.ISOLATION_REPEATABLE_READ); + + assertThatThrownBy( + () -> new AccountLifecyclePendingDenialReader(dsl).requireNoPending(ACCOUNT, TENANT)) + .isInstanceOf(PendingStateUnavailableException.class) + .hasCauseInstanceOf(DataAccessException.class); + } + + @Test + void ownerTransactionAndExactUuidInputsAreRequiredBeforeReads() { + DSLContext dsl = mock(DSLContext.class); + var reader = new AccountLifecyclePendingDenialReader(dsl); + + assertThatThrownBy(() -> reader.requireNoPending(ACCOUNT, TENANT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("owner transaction"); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThatThrownBy(() -> reader.requireNoPending(ACCOUNT, TENANT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("REPEATABLE_READ or SERIALIZABLE"); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy(() -> reader.requireNoPending(new UUID(0L, 0L), TENANT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + verifyNoInteractions(dsl); + } + + private static Record accountRow() { + Record account = mock(Record.class); + when(account.get(0, UUID.class)).thenReturn(ACCOUNT); + return account; + } + + private static void transaction(int isolation) { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(isolation); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java index 8333d0f944..5f936f83bd 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; @@ -35,6 +36,7 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountLifecyclePendingDenialReader; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; @@ -81,14 +83,43 @@ void composesExactExistingOwnerReadsInAccountFirstOrder() { assertThat(result.entitlementSource()).isEqualTo(fixture.entitlement); assertThat(result.tokenIdentityFence()).isEqualTo(fixture.activeFence); var ordered = - inOrder(fixture.memberships, fixture.accounts, fixture.entitlements, fixture.tokenFences); + inOrder( + fixture.memberships, + fixture.lifecyclePendingDenials, + fixture.accounts, + fixture.entitlements, + fixture.tokenFences); ordered.verify(fixture.memberships).readCurrent(ACCOUNT, TENANT); + ordered.verify(fixture.lifecyclePendingDenials).requireNoPending(ACCOUNT, TENANT); ordered.verify(fixture.accounts).findByAccountUuid(ACCOUNT); ordered.verify(fixture.entitlements).readCurrent(TENANT); ordered.verify(fixture.entitlements).revalidate(fixture.entitlement); ordered.verify(fixture.tokenFences).requireActiveForUpdate(fixture.identity); verifyNoMoreInteractions( - fixture.memberships, fixture.accounts, fixture.entitlements, fixture.tokenFences); + fixture.memberships, + fixture.lifecyclePendingDenials, + fixture.accounts, + fixture.entitlements, + fixture.tokenFences); + } + + @Test + void pendingLifecycleDenialStopsBeforeEntitlementAndTokenReads() { + Fixture fixture = new Fixture(); + doThrow( + new AccountLifecyclePendingDenialReader.PendingOperationException( + "Account lifecycle invalidation is unresolved for this Account and tenant")) + .when(fixture.lifecyclePendingDenials) + .requireNoPending(ACCOUNT, TENANT); + + assertThatThrownBy(fixture::read) + .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class) + .hasMessage("Account lifecycle invalidation is unresolved for this Account and tenant"); + + var ordered = inOrder(fixture.memberships, fixture.lifecyclePendingDenials); + ordered.verify(fixture.memberships).readCurrent(ACCOUNT, TENANT); + ordered.verify(fixture.lifecyclePendingDenials).requireNoPending(ACCOUNT, TENANT); + verifyNoInteractions(fixture.accounts, fixture.entitlements, fixture.tokenFences); } @Test @@ -333,10 +364,12 @@ private static final class Fixture { mock(AccountDemoTenantEntitlementRepository.class); final AccountGameplayTokenIdentityFenceRepository tokenFences = mock(AccountGameplayTokenIdentityFenceRepository.class); + final AccountLifecyclePendingDenialReader lifecyclePendingDenials = + mock(AccountLifecyclePendingDenialReader.class); final Account account = account(); final AccountGameplayPublicAdmissionSourceReader reader = new AccountGameplayPublicAdmissionSourceReader( - memberships, accounts, entitlements, tokenFences); + memberships, accounts, entitlements, tokenFences, lifecyclePendingDenials); TokenIdentity identity = new TokenIdentity( ACCOUNT, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcServiceTest.java new file mode 100644 index 0000000000..3fcef5a7c5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcServiceTest.java @@ -0,0 +1,278 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.AcquirePublicGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.AcquirePublicGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.GameplayAdmissionLeaseState; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.ReconcileGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ReconcileGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionAbortOwner; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionAbortOwnerTest; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionLeaseRepository; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionStatus; + +/** Transport/owner doubles only; no registration, actual TLS or source-authority proof. */ +class AccountGameplayAdmissionLeaseGrpcServiceTest { + @Test + void encodesExactAbortedCarrierAndUnknownDecisionOnly() { + var owner = mock(AccountGameplayAdmissionAbortOwner.class); + UUID cleanup = UUID.randomUUID(); + when(owner.abort(any())) + .thenReturn( + new AccountGameplayAdmissionLeaseOperation( + AccountGameplayAdmissionAbortOwnerTest.fixture(), State.ABORTED, null, cleanup)); + var observer = new Capture(); + new AccountGameplayAdmissionLeaseGrpcService(owner) + .abortGameplayAdmissionLease(AccountGameplayAdmissionAbortOwnerTest.request(), observer); + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + var operation = observer.value.getOperation(); + assertThat(operation.getState()) + .isEqualTo(GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED); + assertThat(operation.getPendingOrphanCleanup()).isTrue(); + assertThat(operation.hasBindingDecisionId()).isFalse(); + assertThat(operation.getOrphanCleanupId()).isEqualTo(cleanup.toString()); + assertThat(AccountGameplayAdmissionLeaseWireCodec.validateOperation(operation)) + .isEqualTo(AccountGameplayAdmissionAbortOwnerTest.fixture()); + } + + @Test + void committedCannotEscapeAbortTransport() { + var owner = mock(AccountGameplayAdmissionAbortOwner.class); + when(owner.abort(any())) + .thenReturn( + new AccountGameplayAdmissionLeaseOperation( + AccountGameplayAdmissionAbortOwnerTest.fixture(), + State.COMMITTED, + UUID.randomUUID(), + null)); + var observer = new Capture(); + new AccountGameplayAdmissionLeaseGrpcService(owner) + .abortGameplayAdmissionLease(AccountGameplayAdmissionAbortOwnerTest.request(), observer); + assertFailure(observer, Status.Code.UNAVAILABLE); + } + + @Test + void actualOwnerDomainDenialsAreTypedButStorageFailuresAreUnavailable() { + var stored = + new java.util.concurrent.atomic.AtomicReference< + Optional>(Optional.empty()); + var repository = + mock( + AccountGameplayAdmissionLeaseRepository.class, + invocation -> { + if (invocation.getMethod().getName().equals("readExact")) return stored.get(); + return org.mockito.Answers.RETURNS_DEFAULTS.answer(invocation); + }); + var manager = mock(PlatformTransactionManager.class); + when(manager.getTransaction(any())).thenReturn(mock(TransactionStatus.class)); + var service = + new AccountGameplayAdmissionLeaseGrpcService( + new AccountGameplayAdmissionAbortOwner(repository, manager, "test")); + UUID decision = UUID.randomUUID(); + var aborted = + new AccountGameplayAdmissionLeaseOperation( + AccountGameplayAdmissionAbortOwnerTest.fixture(), + State.ABORTED, + decision, + UUID.randomUUID()); + for (String code : + List.of( + "ADMISSION_LEASE_UNRESOLVED", + "ADMISSION_LEASE_NOT_ABORTABLE", + "IDEMPOTENCY_CONFLICT")) { + if (code.equals("ADMISSION_LEASE_NOT_ABORTABLE")) + stored.set( + Optional.of( + new AccountGameplayAdmissionLeaseOperation( + AccountGameplayAdmissionAbortOwnerTest.fixture(), + State.COMMITTED, + decision, + null))); + if (code.equals("IDEMPOTENCY_CONFLICT")) stored.set(Optional.of(aborted)); + var observer = new Capture(); + peer() + .run( + () -> + service.abortGameplayAdmissionLease( + AccountGameplayAdmissionAbortOwnerTest.request(), observer)); + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.hasOperation()).isFalse(); + assertThat(observer.value.getDenied().getCode()).isEqualTo(code); + assertThat(observer.value.getDenied().getMessage()) + .isEqualTo("Account admission abort denied"); + } + var failingRepository = + mock( + AccountGameplayAdmissionLeaseRepository.class, + invocation -> { + throw new IllegalStateException("secret storage read failure"); + }); + var unavailable = new Capture(); + var failingService = + new AccountGameplayAdmissionLeaseGrpcService( + new AccountGameplayAdmissionAbortOwner(failingRepository, manager, "test")); + peer() + .run( + () -> + failingService.abortGameplayAdmissionLease( + AccountGameplayAdmissionAbortOwnerTest.request(), unavailable)); + assertFailure(unavailable, Status.Code.UNAVAILABLE); + assertThat(Status.fromThrowable(unavailable.failure).getDescription()).doesNotContain("secret"); + } + + @Test + void rejectsMalformedOuterReferenceAndClosedJsonBeforeSql() { + var repository = mock(AccountGameplayAdmissionLeaseRepository.class); + var manager = mock(PlatformTransactionManager.class); + var service = + new AccountGameplayAdmissionLeaseGrpcService( + new AccountGameplayAdmissionAbortOwner(repository, manager, "test")); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var original = AccountGameplayAdmissionAbortOwnerTest.request(); + var reference = original.getLease(); + for (var request : + List.of( + AbortGameplayAdmissionLeaseRequest.getDefaultInstance(), + original.toBuilder().setUnknownFields(unknown).build(), + original.toBuilder().setLease(reference.toBuilder().setUnknownFields(unknown)).build(), + original.toBuilder() + .setLease(reference.toBuilder().setRequestId(UUID.randomUUID().toString())) + .build(), + original.toBuilder() + .setLease(reference.toBuilder().setEvidenceSha256("0".repeat(64))) + .build(), + original.toBuilder() + .setLease( + reference.toBuilder().setEvidenceCanonicalJson(ByteString.copyFromUtf8("{}"))) + .build(), + original.toBuilder() + .setLease( + reference.toBuilder() + .setEvidenceCanonicalJson( + ByteString.copyFromUtf8( + reference + .getEvidenceCanonicalJson() + .toStringUtf8() + .replace( + "\"schemaVersion\":\"1\"", "\"schemaVersion\":\"2\"")))) + .build())) { + var observer = new Capture(); + peer().run(() -> service.abortGameplayAdmissionLease(request, observer)); + assertFailure(observer, Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(repository, manager); + } + + @Test + void returnsBoundedRedactedErrorsWithoutSuccessfulOutcome() { + var owner = mock(AccountGameplayAdmissionAbortOwner.class); + var service = new AccountGameplayAdmissionLeaseGrpcService(owner); + for (var failure : + List.of( + new IllegalArgumentException("secret evidence"), + new IllegalStateException("secret evidence"), + new RuntimeException("secret evidence"))) { + doThrow(failure).when(owner).abort(any()); + var observer = new Capture(); + service.abortGameplayAdmissionLease( + AccountGameplayAdmissionAbortOwnerTest.request(), observer); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + assertThat(Status.fromThrowable(observer.failure).getDescription()) + .doesNotContain("secret evidence"); + assertThat(observer.failure.getCause()).isNull(); + } + } + + @Test + void everyOtherMethodRemainsUnimplemented() { + var owner = mock(AccountGameplayAdmissionAbortOwner.class); + var service = new AccountGameplayAdmissionLeaseGrpcService(owner); + var acquire = new Capture(); + var finalize = new Capture(); + var read = new Capture(); + var reconcile = new Capture(); + service.acquirePublicGameplayAdmissionLease( + AcquirePublicGameplayAdmissionLeaseRequest.getDefaultInstance(), acquire); + service.finalizeGameplayAdmissionLease( + FinalizeGameplayAdmissionLeaseRequest.getDefaultInstance(), finalize); + service.readGameplayAdmissionLease( + ReadGameplayAdmissionLeaseRequest.getDefaultInstance(), read); + service.reconcileGameplayAdmissionLease( + ReconcileGameplayAdmissionLeaseRequest.getDefaultInstance(), reconcile); + for (var observer : List.of(acquire, finalize, read, reconcile)) + assertFailure(observer, Status.Code.UNIMPLEMENTED); + verifyNoInteractions(owner); + } + + private static Context peer() { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") + .orElseThrow()); + } + + private static void assertFailure(Capture observer, Status.Code code) { + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + assertThat(Status.fromThrowable(observer.failure).getCode()).isEqualTo(code); + } + + private static final class Capture implements StreamObserver { + private T value; + private Throwable failure; + private boolean completed; + + @Override + public void onNext(T value) { + this.value = value; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Test observer retains the exact supplied failure for redaction assertions.") + public void onError(Throwable failure) { + this.failure = failure; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} From 2ddb226e2e55a3647437f1482420ce11dd267bdc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 11:31:59 +1300 Subject: [PATCH 07/16] Deny new canonical JOIN mutations while lifecycle intents remain pending --- .../player-access-and-session.md | 4 + .../AccountLifecyclePendingDenialReader.java | 47 ++++-- ...CanonicalFirstJoinTerminalCoordinator.java | 7 +- ...ionIssuancePersistenceIntegrationTest.java | 3 +- ...anonicalFirstJoinEventIntegrationTest.java | 159 +++++++++++++++++- ...countLifecyclePendingDenialReaderTest.java | 120 ++++++++++++- ...nicalFirstJoinTerminalCoordinatorTest.java | 67 +++++++- 7 files changed, 387 insertions(+), 20 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 43b3097827..c6ea65f30c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,6 +12,8 @@ The isolated Account candidate adds an unregistered same-transaction source read The unregistered source reader also requires the exact Account/tenant denial predicate from the canonical V86 lifecycle-serving journal. Both `PENDING` and `WORLD_TERMINAL` remain unresolved denial evidence; a World receipt alone does not finalize Account sources. Missing journal data, query failures or a serialization failure deny the observation. The journal's pending-insert guard versions the exact Account row without changing logical Account state, authority counters or outbox evidence, so an older repeatable-read snapshot cannot wait for that writer and then silently miss its committed intent. This is not a lifecycle writer, a World verifier or a source finalizer. Its concurrent PostgreSQL cases require physical execution before claiming that ordering proof. +The canonical first-JOIN coordinator consumes that same denial reader after the Account-first lock and exact operation/caller comparison, before a new `PENDING` operation writes membership, roles, authority events or audit evidence. An exact already-`COMMITTED` JOIN replay preserves the historical receipt and does not re-evaluate this new-commit predicate; that replay is not fresh admission. The registered persistence reader accepts writable READ_COMMITTED, REPEATABLE_READ or SERIALIZABLE transactions, checking PostgreSQL's actual isolation when Spring uses the datasource default. This negative predicate does not weaken the public-admission source reader's separate same-snapshot isolation requirement. The first-JOIN PostgreSQL definition checks both unresolved statuses and unchanged JOIN owner state using opaque fixture lifecycle payloads, not authenticated World publication evidence. + The shared admission-lease evidence value preserves the complete unchanged baseline, public-target tuple, ordered authority checkpoints, exact token metadata, caller workload, binding identity, absolute expiry and applicable resume/prior-generation fields. It is a bounded canonical shape/digest codec, not authenticated Account evidence or a lease issuer. Its tuple and baseline validation currently inherits the existing public-delegation validator's signed-long source range; unsupported values are denied rather than substituted. Billing cutoff evidence refers to the tenant authority stream; the demo entitlement's separate availability receipt is not invented as another authority checkpoint. The unregistered initial-token authenticator verifies the concrete same-namespace Game Session peer, the real asymmetric signature and initial unscoped profile, and exact current committed-issuance evidence through the existing SQL/Redis owner before opening a source transaction. It compares the original token hash, signer, Account identity, issuance times, generation, fence and global authority rather than trusting a supplied workload string or a post-admission player context. The composed source owner then opens its own writable SERIALIZABLE transaction and compares the current Account sources with that candidate, preserving the target membership baseline independently of the initial token's empty membership map. Expiry before, during and after source capture denies the observation. Fifteen signed-token tests and eight composition tests cover the bounded seam; owner and transaction doubles do not prove live mTLS, PostgreSQL/Redis currentness or admission through physical commit. The observation is non-authorizing and must not be reused as a later acquire or finalization decision. @@ -34,6 +36,8 @@ The prior authentication/source/storage/birth/wire/client correction gate passed The subsequent pending-journal and cancellation batch has 1,142 discovered Account unit cases: 1,139 executed, three skipped, and no failures or errors after correcting the new fabricated checkpoint fixture and Mockito restubbing. All five pending-reader, eight cancellation-owner and six abort-handler cases passed. Integration definitions compile: two non-database cases executed and 149 database cases skipped locally. Three new pending-journal cases include both PENDING/WORLD_TERMINAL denial, cross-tenant isolation and stale-snapshot denial under both REPEATABLE_READ and SERIALIZABLE; two actual cancellation-owner PostgreSQL cases define lost-response recovery and concurrent retry. Their physical execution remains pending, and no PostgreSQL behavior is inferred from compilation or skipped cases. Failed intermediate gates and exact publication proof remain in the controller. +The first-JOIN pending-enforcement correction passes the complete Account check, formatting, static analysis and integration-source compilation: 1,145 unit cases executed, three skipped, and zero failures/errors. Two non-database integration cases executed and 150 database cases skipped, including the new no-mutation first-JOIN definition. The new default-isolation query compiled after correcting its jOOQ overload; no guard or assertion was weakened. This local proof does not establish PostgreSQL transaction ordering or enabled admission. Physical CI for the preceding pending/cancellation head remains separate from this newer source state. + Predecessor exact-head CI run `37685986902` for `475949f3ba86b1c8c024dfee12d143ef1f7e1c6a` executed 1,107 Account unit cases without failures or errors, with three unit skips. Its JUnit reports contain 154 integration cases: 150 executed, four skipped, and 23 failed. All seven restriction-birth cases, five first-JOIN event cases including real demo provisioning before JOIN, and four public-admission source-capture cases executed and passed. Seven of the eight lease-storage cases passed, including unknown-decision abort and exact recovery. The remaining lease case and sixteen other historical-migration cases used the current Account creator before the V88 tables existed; six generic-update parameter cases attempted fresh non-`ACTIVE` creation instead of seeding an existing lifecycle fixture. The corrective batch preserves those migration targets and assertions through a test-only pre-V88 repository initializer that retains genuine insert provenance and fails if the birth schema is already installed. Generic-update cases first create a real fresh `ACTIVE` Account, then shape the existing lifecycle only inside a rolled-back test transaction; this is not production lifecycle-transition proof. Physical CI rerun of the corrected fixtures remains pending. The predecessor runner merge is `5f32c475bedcd84bffb1352f0dc6e07d91a6b83c` on exact base `7985e8a6f6354587f5c01649ede3d0cecde9fde2`; every other module and substantive validation job passed. Metadata-only run `37686048169` skipped substantive checks and failed gate preservation, so it supplies no execution proof. Aggregate CI is not green and this checkpoint is not merge-ready. Earlier failed runs and their corrections remain recorded in the controller and PR history. Exact published admission checkpoint `e52fdee55236f659995a0602db1781f0ae41ee23` has physical Account JUnit evidence from CI run `37690080516`: 1,276 discovered cases, 1,269 executed, seven skipped, and no failures or errors. The seven client unit and five socket mTLS cases, seven restriction-birth cases, five first-JOIN event cases and eight lease-storage cases executed and passed. Historical migration and generic-update fixture suites executed without failures, but their individual loop subcases were not enumerated from runner logs during the bounded observer window. The full workflow subsequently completed successfully, including Dev Tool Contract Checks and Validation Summary. Green CI does not establish protected owner completion or merge readiness. Metadata-only sibling `37690096664` supplies no execution credit. This published-head proof excludes the subsequent pending-journal reader, row-version guard and cancellation-owner batch. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java index f29fd36a2a..3eda357d8b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java @@ -1,10 +1,12 @@ package net.firedevops.firemud.accountservice.repository; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Objects; import java.util.UUID; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.exception.DataAccessException; +import org.springframework.stereotype.Repository; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -13,7 +15,8 @@ * predicate. It proves no producer identity, World result, source finalization, current serving * state, or admission permission. */ -public final class AccountLifecyclePendingDenialReader { +@Repository +public class AccountLifecyclePendingDenialReader { private static final String ACCOUNT_LOCK_SQL = "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE"; private static final String PENDING_SQL = @@ -24,6 +27,10 @@ public final class AccountLifecyclePendingDenialReader { private final DSLContext dsl; + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep the required DSL precondition fail-fast; this non-final Spring repository is proxied and no partially initialized instance escapes.") public AccountLifecyclePendingDenialReader(DSLContext dsl) { this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); } @@ -31,14 +38,15 @@ public AccountLifecyclePendingDenialReader(DSLContext dsl) { /** * Requires no unresolved lifecycle operation for the exact Account/tenant pair. * - *

The existing writable owner transaction must be REPEATABLE_READ or SERIALIZABLE. The - * canonical journal's BEFORE INSERT row-version fence forces an older snapshot waiting on the - * persisted Account lock to fail with a serialization error instead of reading a stale clear - * predicate. Both a pending intent and a correlated World terminal receipt remain denial - * evidence. + *

The existing writable owner transaction must be READ_COMMITTED, REPEATABLE_READ, or + * SERIALIZABLE. At READ_COMMITTED, the exact Account row lock makes this query observe a + * lifecycle insert committed before the lock is acquired; the journal's BEFORE INSERT row-version + * fence prevents an insert from crossing a later lock holder. When Spring uses the datasource's + * default isolation, the actual PostgreSQL transaction isolation is checked. Both a pending + * intent and a correlated World terminal receipt remain denial evidence. */ public void requireNoPending(UUID accountUuid, UUID tenantUuid) { - requireWritableOwnerTransaction(); + requireWritableOwnerTransaction(dsl); requireUuid(accountUuid, "Account UUID"); requireUuid(tenantUuid, "tenant UUID"); @@ -66,7 +74,7 @@ public void requireNoPending(UUID accountUuid, UUID tenantUuid) { } } - private static void requireWritableOwnerTransaction() { + private static void requireWritableOwnerTransaction(DSLContext dsl) { if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( "Account lifecycle pending read requires an owner transaction"); @@ -76,11 +84,30 @@ private static void requireWritableOwnerTransaction() { "Account lifecycle pending read requires a writable transaction"); } Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (isolation == null) { + final String databaseIsolation; + try { + Record isolationRecord = dsl.fetchOne("SHOW transaction_isolation"); + databaseIsolation = isolationRecord == null ? null : isolationRecord.get(0, String.class); + } catch (DataAccessException unavailable) { + throw new IllegalStateException( + "Account lifecycle pending read could not determine transaction isolation", + unavailable); + } + if ("read committed".equals(databaseIsolation)) { + isolation = TransactionDefinition.ISOLATION_READ_COMMITTED; + } else if ("repeatable read".equals(databaseIsolation)) { + isolation = TransactionDefinition.ISOLATION_REPEATABLE_READ; + } else if ("serializable".equals(databaseIsolation)) { + isolation = TransactionDefinition.ISOLATION_SERIALIZABLE; + } + } if (isolation == null - || (isolation != TransactionDefinition.ISOLATION_REPEATABLE_READ + || (isolation != TransactionDefinition.ISOLATION_READ_COMMITTED + && isolation != TransactionDefinition.ISOLATION_REPEATABLE_READ && isolation != TransactionDefinition.ISOLATION_SERIALIZABLE)) { throw new IllegalStateException( - "Account lifecycle pending read requires REPEATABLE_READ or SERIALIZABLE isolation"); + "Account lifecycle pending read requires READ_COMMITTED, REPEATABLE_READ, or SERIALIZABLE isolation"); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java index c8c9bb63df..3867299636 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java @@ -25,6 +25,7 @@ import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationConflictException; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; +import net.firedevops.firemud.accountservice.repository.AccountLifecyclePendingDenialReader; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; @@ -63,6 +64,7 @@ public class AccountCanonicalFirstJoinTerminalCoordinator { private final AccountMembershipPairAuthorityRepository pairAuthorityRepository; private final AccountAuditOutboxRepository auditOutboxRepository; private final AccountMembershipAuthorityEventProducer eventProducer; + private final AccountLifecyclePendingDenialReader lifecyclePendingDenialReader; @SuppressFBWarnings( value = {"CT_CONSTRUCTOR_THROW", "EI_EXPOSE_REP2"}, @@ -77,7 +79,8 @@ public AccountCanonicalFirstJoinTerminalCoordinator( AccountAuthorityOutboxRepository authorityOutboxRepository, AccountMembershipPairAuthorityRepository pairAuthorityRepository, AccountAuditOutboxRepository auditOutboxRepository, - AccountMembershipAuthorityEventProducer eventProducer) { + AccountMembershipAuthorityEventProducer eventProducer, + AccountLifecyclePendingDenialReader lifecyclePendingDenialReader) { this.accountRepository = Objects.requireNonNull(accountRepository); this.joinOperationRepository = Objects.requireNonNull(joinOperationRepository); this.membershipRepository = Objects.requireNonNull(membershipRepository); @@ -86,6 +89,7 @@ public AccountCanonicalFirstJoinTerminalCoordinator( this.pairAuthorityRepository = Objects.requireNonNull(pairAuthorityRepository); this.auditOutboxRepository = Objects.requireNonNull(auditOutboxRepository); this.eventProducer = Objects.requireNonNull(eventProducer); + this.lifecyclePendingDenialReader = Objects.requireNonNull(lifecyclePendingDenialReader); } /** @@ -120,6 +124,7 @@ public CanonicalJoinTerminalProof commitCanonicalFirstJoin( final Checkpoint checkpoint; if ("PENDING".equals(operation.status())) { + lifecyclePendingDenialReader.requireNoPending(scope.accountId(), scope.tenantId()); VerifiedTenantProvenance provenance = operation.scopeEvidence().tenantProvenance(); if (!Boolean.TRUE.equals(operation.allowPublicJoin()) || !"AVAILABLE".equals(operation.entitlementAuthorityAvailability()) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java index 1ecf163634..385f8db1a6 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -1615,7 +1615,8 @@ private AdmissionSourceFixture newAdmissionSourceFixture() throws Exception { outbox, pairs, new AccountAuditOutboxRepository(dsl), - membershipEvents); + membershipEvents, + new AccountLifecyclePendingDenialReader(dsl)); inTransaction( harness.context(), () -> { 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 9c78809f68..e142622755 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 @@ -5,6 +5,9 @@ import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -21,6 +24,7 @@ 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.AccountLifecyclePendingDenialReader; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; @@ -284,6 +288,59 @@ void terminalJournalFailureRollsBackMembershipEventPairAndAuditTogether() { assertThat(operation.terminalProof()).isNull(); } + @Test + void unresolvedLifecycleJournalRowsDenyNewFirstJoinWithoutChangingJoinOwnerState() { + assertLifecycleJournalDeniesFirstJoin("PENDING"); + assertLifecycleJournalDeniesFirstJoin("WORLD_TERMINAL"); + } + + private void assertLifecycleJournalDeniesFirstJoin(String status) { + Fixture fixture = newFixture(); + fixture.seedLifecycleOperation(status); + + assertThatThrownBy(fixture::commitFirstJoin) + .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class) + .hasMessage("Account lifecycle invalidation is unresolved for this Account and tenant"); + assertThat( + fixture.dsl.fetchValue( + "SELECT status FROM account_lifecycle_serving_operations " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + String.class, + fixture.account.getAccountUuid(), + fixture.tenantUuid)) + .isEqualTo(status); + + assertThat(fixture.count("account_tenant_membership", "tenant_uuid", fixture.tenantUuid)) + .isZero(); + assertThat(fixture.countAll("account_tenant_membership_role_snapshots")).isZero(); + assertThat(fixture.countAll("account_membership_pair_authority")).isZero(); + assertThat( + fixture.count( + "account_authority_outbox_streams", + "outbox_stream_key", + fixture.membershipStream())) + .isZero(); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isZero(); + UUID auditEventId = + UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + fixture.requestId).getBytes(StandardCharsets.UTF_8)); + assertThat(fixture.count("account_audit_outbox", "audit_event_id", auditEventId)).isZero(); + assertThat(fixture.count("account_join_operations", "request_id", fixture.requestId)) + .isEqualTo(1L); + var operation = + fixture.inTransaction( + () -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(fixture.requestId) + .orElseThrow()); + assertThat(operation.status()).isEqualTo("PENDING"); + assertThat(operation.terminalProof()).isNull(); + } + private Fixture newFixture() { return new Fixture(newTestContext()); } @@ -376,7 +433,15 @@ private Fixture(TestContext context, boolean provisionDemo) { tenantEvents); this.terminalCoordinator = new AccountCanonicalFirstJoinTerminalCoordinator( - accounts, operations, memberships, roles, outbox, pairs, auditOutbox, producer); + accounts, + operations, + memberships, + roles, + outbox, + pairs, + auditOutbox, + producer, + new AccountLifecyclePendingDenialReader(dsl)); this.account = createAccount(); this.tenantEvidence = freshTenantEvidence(tenantUuid); this.provenance = @@ -422,6 +487,98 @@ private void seedOwnerRowsAndOperation(boolean provisionDemo) { }); } + private void seedLifecycleOperation(String status) { + // Lifecycle fixture payloads are opaque shape-only; they do not prove an authenticated World + // receipt. + if (!"PENDING".equals(status) && !"WORLD_TERMINAL".equals(status)) { + throw new IllegalArgumentException("unsupported lifecycle fixture status"); + } + String accountStream = "account:auth-authority:v1:account/" + account.getAccountUuid(); + var source = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_generation, current_source_version, " + + "current_issuance_fence, current_issuance_fence_source_version, " + + "last_outbox_sequence FROM account_authority_source_records " + + "WHERE outbox_stream_key = ?", + accountStream)); + long generation = source.get("current_generation", Long.class); + long sourceVersion = source.get("current_source_version", Long.class); + long issuanceFence = source.get("current_issuance_fence", Long.class); + long fenceSourceVersion = source.get("current_issuance_fence_source_version", Long.class); + long checkpointSequence = source.get("last_outbox_sequence", Long.class); + if (checkpointSequence != 0L) { + throw new IllegalStateException("fixture Account baseline unexpectedly has an event"); + } + UUID lifecycleRequestId = UUID.randomUUID(); + byte[] callerBinding = opaqueBytes("caller-proof"); + byte[] activationRequest = opaqueBytes("world-request"); + byte[] preparingEvidence = opaqueBytes("world-preparing-evidence"); + byte[] requestPayload = opaqueBytes("account-request"); + byte[] capturePayload = opaqueBytes("account-capture"); + byte[] resultPayload = "opaque-world-terminal-result".getBytes(StandardCharsets.UTF_8); + dsl.execute( + "INSERT INTO account_lifecycle_serving_operations (" + + "request_id, actor_account_uuid, account_uuid, account_id, account_provenance, " + + "tenant_uuid, purpose, caller_proof_binding, world_activation_request_id, " + + "world_activation_request_digest, world_activation_request_bytes, " + + "world_activation_preparing_evidence, request_payload, request_digest, " + + "account_stream_key, account_generation, account_source_version, " + + "account_issuance_fence, account_fence_source_version, checkpoint_sequence, " + + "checkpoint_payload, capture_payload, capture_digest, status, " + + "world_result_outcome, world_result_payload, world_result_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, 'WORLD_ACTIVATION_INVALIDATION', ?, ?, ?, ?, ?, ?, ?, " + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + lifecycleRequestId, + account.getAccountUuid(), + account.getAccountUuid(), + account.getId(), + account.getAccountUuidProvenance(), + tenantUuid, + callerBinding, + UUID.randomUUID(), + sha256(activationRequest), + activationRequest, + preparingEvidence, + requestPayload, + sha256(requestPayload), + accountStream, + generation, + sourceVersion, + issuanceFence, + fenceSourceVersion, + checkpointSequence, + new byte[0], + capturePayload, + sha256(capturePayload), + "PENDING", + null, + null, + null); + if ("WORLD_TERMINAL".equals(status)) { + dsl.execute( + "UPDATE account_lifecycle_serving_operations SET world_result_outcome = 'ABORTED', " + + "world_result_payload = ?, world_result_digest = ?, status = 'WORLD_TERMINAL' " + + "WHERE request_id = ?", + resultPayload, + sha256(resultPayload), + lifecycleRequestId); + } + } + + private static byte[] opaqueBytes(String label) { + return ("opaque-fixture:" + label + ":" + UUID.randomUUID()).getBytes(StandardCharsets.UTF_8); + } + + private static String sha256(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + private AccountAuthorityOutboxRepository.Checkpoint writeAndPublish() { return inTransaction( () -> { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReaderTest.java index f7a135eec1..ece09e1ff7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReaderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReaderTest.java @@ -5,8 +5,8 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.UUID; @@ -78,6 +78,103 @@ void noPendingOperationDoesNotTripTheDenialPredicate() { TENANT); } + @Test + void readCommittedWritableOwnerTransactionIsAllowedForNegativePredicate() { + DSLContext dsl = mock(DSLContext.class); + Record account = accountRow(); + Record pending = mock(Record.class); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, pending); + when(pending.get(0, Boolean.class)).thenReturn(false); + transaction(TransactionDefinition.ISOLATION_READ_COMMITTED); + + new AccountLifecyclePendingDenialReader(dsl).requireNoPending(ACCOUNT, TENANT); + + verify(dsl) + .fetchOne( + "SELECT EXISTS (SELECT 1 FROM account_lifecycle_serving_operations " + + "WHERE account_uuid = ? AND tenant_uuid = ? " + + "AND status IN ('PENDING', 'WORLD_TERMINAL'))", + ACCOUNT, + TENANT); + } + + @Test + void datasourceDefaultReadCommittedIsolationIsAccepted() { + DSLContext dsl = mock(DSLContext.class); + Record account = accountRow(); + Record pending = mock(Record.class); + Record isolation = mock(Record.class); + when(dsl.fetchOne("SHOW transaction_isolation")).thenReturn(isolation); + when(isolation.get(0, String.class)).thenReturn("read committed"); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, pending); + when(pending.get(0, Boolean.class)).thenReturn(false); + defaultIsolationTransaction(); + + new AccountLifecyclePendingDenialReader(dsl).requireNoPending(ACCOUNT, TENANT); + + var ordered = inOrder(dsl); + ordered.verify(dsl).fetchOne("SHOW transaction_isolation"); + ordered + .verify(dsl) + .fetchOne("SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", ACCOUNT); + ordered + .verify(dsl) + .fetchOne( + "SELECT EXISTS (SELECT 1 FROM account_lifecycle_serving_operations " + + "WHERE account_uuid = ? AND tenant_uuid = ? " + + "AND status IN ('PENDING', 'WORLD_TERMINAL'))", + ACCOUNT, + TENANT); + } + + @Test + void unknownDatasourceDefaultIsolationDeniesBeforeOwnerReads() { + DSLContext dsl = mock(DSLContext.class); + defaultIsolationTransaction(); + + assertThatThrownBy( + () -> new AccountLifecyclePendingDenialReader(dsl).requireNoPending(ACCOUNT, TENANT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires READ_COMMITTED"); + + verify(dsl).fetchOne("SHOW transaction_isolation"); + verify(dsl, never()).fetchOne(anyString(), any(Object[].class)); + } + + @Test + void nullDatasourceDefaultIsolationValueDeniesBeforeOwnerReads() { + DSLContext dsl = mock(DSLContext.class); + Record isolation = mock(Record.class); + when(dsl.fetchOne("SHOW transaction_isolation")).thenReturn(isolation); + when(isolation.get(0, String.class)).thenReturn(null); + defaultIsolationTransaction(); + + assertThatThrownBy( + () -> new AccountLifecyclePendingDenialReader(dsl).requireNoPending(ACCOUNT, TENANT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires READ_COMMITTED"); + + verify(dsl).fetchOne("SHOW transaction_isolation"); + verify(dsl, never()).fetchOne(anyString(), any(Object[].class)); + } + + @Test + void datasourceDefaultIsolationQueryFailureDeniesBeforeOwnerReads() { + DSLContext dsl = mock(DSLContext.class); + DataAccessException unavailable = new DataAccessException("isolation unavailable"); + when(dsl.fetchOne("SHOW transaction_isolation")).thenThrow(unavailable); + defaultIsolationTransaction(); + + assertThatThrownBy( + () -> new AccountLifecyclePendingDenialReader(dsl).requireNoPending(ACCOUNT, TENANT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("could not determine transaction isolation") + .hasCause(unavailable); + + verify(dsl).fetchOne("SHOW transaction_isolation"); + verify(dsl, never()).fetchOne(anyString(), any(Object[].class)); + } + @Test void missingAccountAndUnreadablePredicateFailClosed() { DSLContext missingAccountDsl = mock(DSLContext.class); @@ -124,17 +221,28 @@ void ownerTransactionAndExactUuidInputsAreRequiredBeforeReads() { .hasMessageContaining("owner transaction"); TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + assertThatThrownBy(() -> reader.requireNoPending(ACCOUNT, TENANT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("isolation"); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_READ_UNCOMMITTED); + assertThatThrownBy(() -> reader.requireNoPending(ACCOUNT, TENANT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("isolation"); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( TransactionDefinition.ISOLATION_READ_COMMITTED); assertThatThrownBy(() -> reader.requireNoPending(ACCOUNT, TENANT)) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("REPEATABLE_READ or SERIALIZABLE"); + .hasMessageContaining("writable transaction"); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( TransactionDefinition.ISOLATION_REPEATABLE_READ); assertThatThrownBy(() -> reader.requireNoPending(new UUID(0L, 0L), TENANT)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("non-nil UUID"); - verifyNoInteractions(dsl); + verify(dsl).fetchOne("SHOW transaction_isolation"); + verify(dsl, never()).fetchOne(anyString(), any(Object[].class)); } private static Record accountRow() { @@ -148,4 +256,10 @@ private static void transaction(int isolation) { TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(isolation); } + + private static void defaultIsolationTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java index 636c33e740..71077e778b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java @@ -6,6 +6,7 @@ import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -35,6 +36,7 @@ import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinTerminalProof; +import net.firedevops.firemud.accountservice.repository.AccountLifecyclePendingDenialReader; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; @@ -85,7 +87,18 @@ void pendingFirstJoinStagesSourcesAppendsAuditAndCommitsExactTerminalProof() { fixture.coordinator.commitCanonicalFirstJoin(fixture.scope, REQUEST_ID, CALLER_BINDING); assertThat(result).isEqualTo(fixture.expectedProof); - InOrder ordered = inOrder(fixture.memberships, fixture.roles, fixture.eventProducer); + InOrder ordered = + inOrder( + fixture.accounts, + fixture.operations, + fixture.pendingReader, + fixture.memberships, + fixture.roles, + fixture.eventProducer); + ordered.verify(fixture.accounts).findByAccountUuid(ACCOUNT_ID); + ordered.verify(fixture.operations).lockAccount(17L); + ordered.verify(fixture.operations).findCanonicalEvidenceForUpdateByRequestId(REQUEST_ID); + ordered.verify(fixture.pendingReader).requireNoPending(ACCOUNT_ID, TENANT_ID); ordered.verify(fixture.memberships).createFreshMembershipForJoin(ACCOUNT_ID, TENANT_ID); ordered .verify(fixture.roles) @@ -123,12 +136,46 @@ void committedExactRetryReadsReceiptWithoutCreatingMembershipOrAppendingAudit() verify(fixture.roles, never()).replaceCanonical(any(), any(), any(), any(), anyLong(), any()); verify(fixture.audit, never()) .appendCanonicalTenant(any(), anyString(), anyString(), anyString()); + verify(fixture.pendingReader, never()).requireNoPending(any(), any()); verify(fixture.audit) .findCanonicalTenantEnvelopeForUpdate(fixture.expectedProof.auditEventId()); verify(fixture.operations) .commitCanonicalFirstJoin(REQUEST_ID, fixture.scope, CALLER_BINDING, fixture.expectedProof); } + @Test + void pendingLifecycleOperationDeniesBeforeAnyJoinMutationOrPublication() { + Fixture fixture = new Fixture(); + fixture.arrangePending(); + doThrow( + new AccountLifecyclePendingDenialReader.PendingOperationException( + "Account lifecycle invalidation is unresolved for this Account and tenant")) + .when(fixture.pendingReader) + .requireNoPending(ACCOUNT_ID, TENANT_ID); + fixture.startWritableTransaction(); + + assertThatThrownBy( + () -> + fixture.coordinator.commitCanonicalFirstJoin( + fixture.scope, REQUEST_ID, CALLER_BINDING)) + .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class) + .hasMessage("Account lifecycle invalidation is unresolved for this Account and tenant"); + + InOrder ordered = inOrder(fixture.operations, fixture.pendingReader); + ordered.verify(fixture.operations).lockAccount(17L); + ordered.verify(fixture.operations).findCanonicalEvidenceForUpdateByRequestId(REQUEST_ID); + ordered.verify(fixture.pendingReader).requireNoPending(ACCOUNT_ID, TENANT_ID); + verifyNoInteractions( + fixture.memberships, + fixture.roles, + fixture.outbox, + fixture.pairs, + fixture.audit, + fixture.eventProducer); + verify(fixture.operations, never()) + .commitCanonicalFirstJoin(anyString(), any(), anyString(), any()); + } + @Test void changedCallerUnderGlobalRequestIdConflictsBeforeReturningAnyReceipt() { Fixture fixture = new Fixture(); @@ -282,7 +329,8 @@ void readOnlyTransactionIsRejectedBeforeOwnerRepositoriesAreTouched() { fixture.outbox, fixture.pairs, fixture.audit, - fixture.eventProducer); + fixture.eventProducer, + fixture.pendingReader); } @Test @@ -303,7 +351,8 @@ void inactiveTransactionIsRejectedBeforeOwnerRepositoriesAreTouched() { fixture.outbox, fixture.pairs, fixture.audit, - fixture.eventProducer); + fixture.eventProducer, + fixture.pendingReader); } @Test @@ -358,9 +407,19 @@ private static final class Fixture { private final AccountAuditOutboxRepository audit = mock(AccountAuditOutboxRepository.class); private final AccountMembershipAuthorityEventProducer eventProducer = mock(AccountMembershipAuthorityEventProducer.class); + private final AccountLifecyclePendingDenialReader pendingReader = + mock(AccountLifecyclePendingDenialReader.class); private final AccountCanonicalFirstJoinTerminalCoordinator coordinator = new AccountCanonicalFirstJoinTerminalCoordinator( - accounts, operations, memberships, roles, outbox, pairs, audit, eventProducer); + accounts, + operations, + memberships, + roles, + outbox, + pairs, + audit, + eventProducer, + pendingReader); private final CanonicalJoinScopeV2 scope = scope(ACCOUNT_ID); private final VerifiedTenantProvenance provenance = new VerifiedTenantProvenance( From 7c8e40ad2073b2815e80fa0913ff23f9f34205e9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 11:51:20 +1300 Subject: [PATCH 08/16] Correct first-JOIN PostgreSQL provenance fixture binding --- design/project-management/ai-observations.md | 5 +++++ .../implementation-tracking/player-access-and-session.md | 2 ++ .../AccountCanonicalFirstJoinEventIntegrationTest.java | 2 +- 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index f83e325ea4..6163b7f1ad 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -66,3 +66,8 @@ Entry format: - Observation: jOOQ's H2-backed DDL interpreter maps PostgreSQL `TEXT` to CLOB, which cannot be indexed there. Closed category/kind/state vocabulary and fixed-format stream keys can use appropriately bounded `VARCHAR` while retaining the actual PostgreSQL checks, foreign keys and triggers; simulator success is not physical migration proof. - Expected pattern: build Mockito-returned fixtures before starting an outer `when(...).thenReturn(...)` call, because nested stubbing leaves that outer call unfinished. Give generic transaction readbacks an explicit typed local before overloaded AssertJ assertions, and check nullable fetched rows or fields explicitly rather than suppressing null-boundary warnings. - Reconsideration trigger: apply these bounded patterns to the next migration or transaction-fixture change without broad constraint exclusions, weaker assertions or a new validator family. + +- `2026-10-08`: Distinguish negative-test diagnostics from superseded CI failures + - Observation: an exact-head CI observer initially attributed a cancelled dev-tool job to a retry-validation error printed by a negative-test fixture. Parent inspection found both displayed unittest groups ended `OK`, and GitHub marked the job cancelled after a newer run superseded it. The completed Account job and uploaded PostgreSQL JUnit evidence remained valid, while aggregate validation was incomplete. + - Expected pattern: inspect failing assertions, group summaries and exact job/step conclusions before treating an error-shaped log line as a defect. Preserve completed module proof separately from cancellation, skipped later steps and whole-workflow readiness. + - Reconsideration trigger: apply this classification to the next failed or cancelled exact-head run; a later green run does not retroactively execute the cancelled steps. 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 c6ea65f30c..46b78fc345 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -38,6 +38,8 @@ The subsequent pending-journal and cancellation batch has 1,142 discovered Accou The first-JOIN pending-enforcement correction passes the complete Account check, formatting, static analysis and integration-source compilation: 1,145 unit cases executed, three skipped, and zero failures/errors. Two non-database integration cases executed and 150 database cases skipped, including the new no-mutation first-JOIN definition. The new default-isolation query compiled after correcting its jOOQ overload; no guard or assertion was weakened. This local proof does not establish PostgreSQL transaction ordering or enabled admission. Physical CI for the preceding pending/cancellation head remains separate from this newer source state. +Physical Account CI for pending/cancellation checkpoint `acfc654d4ee0ee719a0ce807fb8cbb84d625535e` executed 1,294 cases with seven skips and no failures/errors. All five added PostgreSQL cases passed, including stale-snapshot denial, both unresolved lifecycle statuses, cross-tenant isolation, lost-response cancellation and concurrent cancellation retry. Its later aggregate failure reflects cancellation of the superseded Dev Tool job, not a failed negative-test assertion. At subsequent first-JOIN checkpoint `2ddb226e2e55a3647437f1482420ce11dd267bdc`, Account CI executed 1,301 cases with seven skips and one failure: the new first-JOIN definition failed while binding its Java provenance enum into a VARCHAR fixture column, before reaching either status's no-mutation assertions. The fixture now binds the existing enum name; those assertions still need a corrected physical rerun. Neither result establishes positive protected admission, authenticated World settlement, or target currentness through Account commit. + Predecessor exact-head CI run `37685986902` for `475949f3ba86b1c8c024dfee12d143ef1f7e1c6a` executed 1,107 Account unit cases without failures or errors, with three unit skips. Its JUnit reports contain 154 integration cases: 150 executed, four skipped, and 23 failed. All seven restriction-birth cases, five first-JOIN event cases including real demo provisioning before JOIN, and four public-admission source-capture cases executed and passed. Seven of the eight lease-storage cases passed, including unknown-decision abort and exact recovery. The remaining lease case and sixteen other historical-migration cases used the current Account creator before the V88 tables existed; six generic-update parameter cases attempted fresh non-`ACTIVE` creation instead of seeding an existing lifecycle fixture. The corrective batch preserves those migration targets and assertions through a test-only pre-V88 repository initializer that retains genuine insert provenance and fails if the birth schema is already installed. Generic-update cases first create a real fresh `ACTIVE` Account, then shape the existing lifecycle only inside a rolled-back test transaction; this is not production lifecycle-transition proof. Physical CI rerun of the corrected fixtures remains pending. The predecessor runner merge is `5f32c475bedcd84bffb1352f0dc6e07d91a6b83c` on exact base `7985e8a6f6354587f5c01649ede3d0cecde9fde2`; every other module and substantive validation job passed. Metadata-only run `37686048169` skipped substantive checks and failed gate preservation, so it supplies no execution proof. Aggregate CI is not green and this checkpoint is not merge-ready. Earlier failed runs and their corrections remain recorded in the controller and PR history. Exact published admission checkpoint `e52fdee55236f659995a0602db1781f0ae41ee23` has physical Account JUnit evidence from CI run `37690080516`: 1,276 discovered cases, 1,269 executed, seven skipped, and no failures or errors. The seven client unit and five socket mTLS cases, seven restriction-birth cases, five first-JOIN event cases and eight lease-storage cases executed and passed. Historical migration and generic-update fixture suites executed without failures, but their individual loop subcases were not enumerated from runner logs during the bounded observer window. The full workflow subsequently completed successfully, including Dev Tool Contract Checks and Validation Summary. Green CI does not establish protected owner completion or merge readiness. Metadata-only sibling `37690096664` supplies no execution credit. This published-head proof excludes the subsequent pending-journal reader, row-version guard and cancellation-owner batch. 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 e142622755..0ecd6dee5a 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 @@ -533,7 +533,7 @@ private void seedLifecycleOperation(String status) { account.getAccountUuid(), account.getAccountUuid(), account.getId(), - account.getAccountUuidProvenance(), + account.getAccountUuidProvenance().name(), tenantUuid, callerBinding, UUID.randomUUID(), From 63d4ae962b2f43b54fff2744306e4dd19bbd0e6d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:05:59 +1300 Subject: [PATCH 09/16] Read first-JOIN lifecycle fixture status through a typed record --- .../player-access-and-session.md | 2 ++ ...countCanonicalFirstJoinEventIntegrationTest.java | 13 +++++++------ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 46b78fc345..7daba4e783 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -40,6 +40,8 @@ The first-JOIN pending-enforcement correction passes the complete Account check, Physical Account CI for pending/cancellation checkpoint `acfc654d4ee0ee719a0ce807fb8cbb84d625535e` executed 1,294 cases with seven skips and no failures/errors. All five added PostgreSQL cases passed, including stale-snapshot denial, both unresolved lifecycle statuses, cross-tenant isolation, lost-response cancellation and concurrent cancellation retry. Its later aggregate failure reflects cancellation of the superseded Dev Tool job, not a failed negative-test assertion. At subsequent first-JOIN checkpoint `2ddb226e2e55a3647437f1482420ce11dd267bdc`, Account CI executed 1,301 cases with seven skips and one failure: the new first-JOIN definition failed while binding its Java provenance enum into a VARCHAR fixture column, before reaching either status's no-mutation assertions. The fixture now binds the existing enum name; those assertions still need a corrected physical rerun. Neither result establishes positive protected admission, authenticated World settlement, or target currentness through Account commit. +At corrected fixture checkpoint `7c8e40ad2073b2815e80fa0913ff23f9f34205e9`, substantive CI `37698850869` again executed 1,301 Account cases with seven skips and one failure. The first `PENDING` denial assertion passed, then its status readback used the wrong `fetchValue` overload and bound `String.class` as a SQL parameter. The remaining no-mutation assertions and the `WORLD_TERMINAL` iteration were not reached. That readback now uses a non-null fetched Record and an explicit typed column getter; all original assertions and production predicates remain unchanged. Complete executed proof for this definition still requires a corrected physical rerun; compilation and Docker-free skips cannot establish it. + Predecessor exact-head CI run `37685986902` for `475949f3ba86b1c8c024dfee12d143ef1f7e1c6a` executed 1,107 Account unit cases without failures or errors, with three unit skips. Its JUnit reports contain 154 integration cases: 150 executed, four skipped, and 23 failed. All seven restriction-birth cases, five first-JOIN event cases including real demo provisioning before JOIN, and four public-admission source-capture cases executed and passed. Seven of the eight lease-storage cases passed, including unknown-decision abort and exact recovery. The remaining lease case and sixteen other historical-migration cases used the current Account creator before the V88 tables existed; six generic-update parameter cases attempted fresh non-`ACTIVE` creation instead of seeding an existing lifecycle fixture. The corrective batch preserves those migration targets and assertions through a test-only pre-V88 repository initializer that retains genuine insert provenance and fails if the birth schema is already installed. Generic-update cases first create a real fresh `ACTIVE` Account, then shape the existing lifecycle only inside a rolled-back test transaction; this is not production lifecycle-transition proof. Physical CI rerun of the corrected fixtures remains pending. The predecessor runner merge is `5f32c475bedcd84bffb1352f0dc6e07d91a6b83c` on exact base `7985e8a6f6354587f5c01649ede3d0cecde9fde2`; every other module and substantive validation job passed. Metadata-only run `37686048169` skipped substantive checks and failed gate preservation, so it supplies no execution proof. Aggregate CI is not green and this checkpoint is not merge-ready. Earlier failed runs and their corrections remain recorded in the controller and PR history. Exact published admission checkpoint `e52fdee55236f659995a0602db1781f0ae41ee23` has physical Account JUnit evidence from CI run `37690080516`: 1,276 discovered cases, 1,269 executed, seven skipped, and no failures or errors. The seven client unit and five socket mTLS cases, seven restriction-birth cases, five first-JOIN event cases and eight lease-storage cases executed and passed. Historical migration and generic-update fixture suites executed without failures, but their individual loop subcases were not enumerated from runner logs during the bounded observer window. The full workflow subsequently completed successfully, including Dev Tool Contract Checks and Validation Summary. Green CI does not establish protected owner completion or merge readiness. Metadata-only sibling `37690096664` supplies no execution credit. This published-head proof excludes the subsequent pending-journal reader, row-version guard and cancellation-owner batch. 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 0ecd6dee5a..d4e556e4b1 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 @@ -302,12 +302,13 @@ private void assertLifecycleJournalDeniesFirstJoin(String status) { .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class) .hasMessage("Account lifecycle invalidation is unresolved for this Account and tenant"); assertThat( - fixture.dsl.fetchValue( - "SELECT status FROM account_lifecycle_serving_operations " - + "WHERE account_uuid = ? AND tenant_uuid = ?", - String.class, - fixture.account.getAccountUuid(), - fixture.tenantUuid)) + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT status FROM account_lifecycle_serving_operations " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + fixture.account.getAccountUuid(), + fixture.tenantUuid)) + .get(0, String.class)) .isEqualTo(status); assertThat(fixture.count("account_tenant_membership", "tenant_uuid", fixture.tenantUuid)) From 215124f753c6c0a746931ae92398f1a0d82bd91d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:43:04 +1300 Subject: [PATCH 10/16] Add exact Account mTLS World player hold acquisition and recovery client --- .../account-service/runtime-and-data.md | 2 + .../world-management-service/api-contracts.md | 12 + .../player-access-and-session.md | 2 + .../v1/draft_terminal_service.proto | 38 + ...orld_canonical_player_admission_hold.proto | 45 + .../WorldGameplayAdmissionHoldClient.java | 243 ++++ ...dmissionHoldClientMtlsIntegrationTest.java | 1218 +++++++++++++++++ .../WorldGameplayAdmissionHoldClientTest.java | 930 +++++++++++++ .../DraftAuthorizationFenceBinding.java | 501 +++++++ .../WorldDraftTerminalReadEvidence.java | 99 ++ .../WorldDraftTerminalReadGrpcCodec.java | 736 ++++++++++ ...AuthoredWorldLaunchDescriptorEvidence.java | 568 ++++++++ ...thoredWorldReleaseAttestationEvidence.java | 732 ++++++++++ .../CompleteLaunchBindingEvidence.java | 14 + .../tenant/AuthoredWorldSourceDigest.java | 147 ++ .../firemud/common/world/RoomTemplateRef.java | 22 + ...rldCanonicalInstanceLifecycleEvidence.java | 475 +++++++ .../WorldDraftStartLocationEvidence.java | 286 ++++ .../WorldPublishedStartLocationEvidence.java | 556 ++++++++ ...dCanonicalPlayerAdmissionHoldEvidence.java | 312 +++++ ...onicalPlayerAdmissionHoldEvidenceTest.java | 804 +++++++++++ 21 files changed, 7742 insertions(+) create mode 100644 protos/world-management/v1/draft_terminal_service.proto create mode 100644 protos/world-management/v1/world_canonical_player_admission_hold.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/WorldGameplayAdmissionHoldClient.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/client/WorldGameplayAdmissionHoldClientMtlsIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/WorldGameplayAdmissionHoldClientTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/RoomTemplateRef.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidence.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index db2e66a0d0..c0c7b547c0 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +The admission prerequisite prepares an unregistered Account client for the distinct [World player-admission serving hold](../world-management-service/api-contracts.md#player-admission-serving-hold). It uses file-backed workload mTLS, verifies the exact same-namespace World server before releasing request evidence, and compares the original lease, target, expected World lifecycle epoch/row version, response correlation, and complete closed hold evidence. Calls run outside Account transactions and synchronization; absent or inconsistent readback remains unresolved. The client does not finalize Account authority, release a World hold, register a runtime RPC or admit gameplay. Executed proof and the remaining current-source/physical-COMMIT gates belong to the [Account admission tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-admission-lease-prerequisite). + The credential-bound LOGIN source-only owner prepares or exactly replays one immutable Account operation, then invokes signer, Coordination Redis and response-recovery owners outside its credential-verification transaction. V81 adds the retained digest-key identifier and schema-qualified credential binding without converting historical unbound operations into authority. All components remain explicitly unwired; public gameplay authentication, trusted source-context production, key provisioning and physical PostgreSQL/Redis/fresh-image proof remain incomplete. See the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#credential-bound-account-login-owner) for this cut's proof status; canonical issuance and response-recovery predicates remain in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). The source-only Account authority-event and receipt/readback cut adds typed event codecs and vectors, draft-commit binding, owner-local operation receipts, and current-source event readback/projections above the separate tenant-authority and signer/readiness foundations. Its schema set is V74, V74.1, and V75–V78; the rejecting V61 migration and V74.1 legacy scalar-role guard are withheld, while V74.1's immutable, truncate, and fresh-birth source guards remain and reserved V79/V80 are untouched. The enabled `AccountRepository.save` path records a scalar role update as generic Account source history without changing the immutable empty global-role source; closed currentness/readback rejects that generic history. This is not canonical global-role authority, producer convergence, or activation of public LOGIN, issuance, credential release, or PLAY. The canonical role writer remains pending. Composed compilation, unit, packaged-JAR and formatting proof passes; the focused PostgreSQL regression is unexecuted, and physical PostgreSQL/Redis proof has not run. Detailed counts and limits belong to the [Account source event and receipt foundation status](../../../project-management/implementation-tracking/player-access-and-session.md#account-authority-event-and-receipt-source-foundation). diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 340b01d865..3c399a0de9 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -297,6 +297,18 @@ Current implementation notes: - `stopSession` now consumes `GetWorldInstanceLifecycle` + `TerminateWorldInstance` rather than the old ping-only shutdown path; Entity Management cleanup runs through `CleanupRuntimeInstance`, and World hard-deletes its own runtime rows (`world_event`, room exits, rooms, zones, regions) before reporting `TERMINATED`. - Replacement-instance/cutover callers beyond explicit stop/termination are still follow-on work. +## Player Admission Serving Hold + +The Account lease and provisional/final binding sequence remains owned by [Session Behavior](../../system-architecture-session-behavior.md#session-types-and-lifetimes). World supplies a distinct player-admission serving hold over its actual current `ACTIVE` target; neither an initial-pointer hold nor an immutable historical activation result supplies this protection. Acquisition and readback authenticate the exact same-namespace Account workload without end-user context before parsing or owner access. Acquisition binds the original Account lease ID, request/attempt identity, unchanged full lease bytes and digest, complete canonical target scope, and expected World `ACTIVE` lifecycle epoch and row version. World resolves its private row through its persisted canonical association rather than caller-supplied numeric keys. + +World verifies and locks that actual lifecycle row in its own transaction before recording one immutable hold identity and fence. Identical retries return the original hold and acquisition evidence without extending the Account attempt's deadline; changed input conflicts. Concurrent and older-snapshot lifecycle mutations cannot pass through the acquisition fence, and every conflicting owner mutation remains blocked while the hold is unresolved. This must include database-level race and readback proof, not only an application preflight check. + +The protected `AcquireCanonicalPlayerAdmissionHold` and `ReadCanonicalPlayerAdmissionHold` methods carry the original canonical Account lease bytes and SHA-256 digest plus the expected World lifecycle epoch and row version as canonical decimal strings. A separate request UUID correlates each transport response; it does not replace the retained lease/attempt identity or create a new hold. The closed `world-canonical-player-admission-hold-evidence/v1` readback contains string `schemaVersion = "1"`, opaque `holdId` and `holdFence`, the exact request object (`accountLeaseJson`, `accountLeaseSha256`, `expectedLifecycleEpoch`, `expectedRowVersion`), and canonical `worldLifecycleEvidenceBase64` retaining the complete original World lifecycle evidence. Its SHA-256 digest covers the canonical outer bytes and is carried separately. Receivers reject unknown or duplicate fields, malformed or noncanonical encoding, changed original bytes, substituted scope or digest, and mismatched request correlation. Missing readback is unresolved and never proves absence or permission to release. Codec validation does not authenticate an owner or establish current Account authorization. + +The cross-owner order is Account acquire, Game Session provisional binding, Account finalize, then Game Session admissible installation. The Game Session decision is bound only once it exists. Account must independently revalidate its current sources and exact lease before its commit; World lifecycle protection does not prove Game Session pointer/catalog currentness, and those owners must fence their own conflicting mutations through Account commit. A storage `COMMITTED` value, earlier source capture, caller-supplied decision or this hold by itself never grants admission. + +World releases only after exact authenticated Account terminal evidence and the matching Game Session installation or cleanup evidence jointly prove the approved outcome. Missing, contradictory, unavailable or ambiguous evidence retains the hold. Expiry is diagnostic, not proof of abort or permission to release; initial-pointer outcomes cannot be reused. The currently prepared owner has no enabled release or admission transport. Implementation and executed proof limits belong in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). + ## LOOK Consumer Notes Telnet and WebSocket clients both route through the `/ws/game/**` gameplay path, so `LOOK` commands hit the same `LookCommandHandler` regardless of transport. 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 7daba4e783..549cce6597 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -26,6 +26,8 @@ The unregistered cancellation owner verifies the concrete same-namespace Game Se The unregistered Account `GameSessionGameplayAdmissionDecisionClient` consumes that existing Game Session callback. It requires file-backed mTLS and the exact same-namespace Game Session server identity before releasing request headers or the original lease bytes, then verifies the response identity independently. Its bounded read rejects ambient Account transactions, changed decision IDs, schema/status/unknown fields, bytes and digest. The result remains a point-in-time `PROVISIONAL` observation, not held World or Account authority, a durable Account finalization result, or admission permission. Its socket tests use an explicitly labeled transport-only Game Session double and fabricated lease-shape fixtures; they cannot establish the real owner database or current target predicates. +The matching unregistered `WorldGameplayAdmissionHoldClient` consumes the distinct [World player-admission serving-hold owner](../../architecture/microservices/world-management-service/api-contracts.md#player-admission-serving-hold). It requires file-backed Account mTLS and the exact same-namespace World server before releasing headers or original lease bytes, rejects ambient transactions and synchronization, and validates fresh transport correlation, the complete original lease/digest/scope, expected World epoch/row version and bounded closed hold evidence. `readExact` additionally preserves the original hold identity, fence and complete canonical bytes; missing readback remains unresolved. The minimal shared dependency closure is byte-identical to published World #3084 `673aaaf6eff34c3263964db9581bb8924982d398`; no World runtime owner, ancestor tree, migration or registration is imported into this Account slice. Five new unit tests use real nested codecs with mocked transport, while five actual socket mTLS tests use an explicitly synthetic World source. The lost-response case deliberately processes the original acquire then loses its acknowledgement, and recovers identical bytes/identity/fence without a second acquire. Local full checks, formatting, static analysis, protobuf generation, integration-source compilation and Account boot packaging passed; the corrected transport fixture rerun passed in 1m16s. Matching reports contain 1,150 executed Account unit cases with three skips, seven executed integration cases (including all five new socket cases) and 150 PostgreSQL skips. Common Security's 160 and Common Platform Core's 176 unit outcomes were reused in the corrected rerun, not freshly executed twice. This proves the protected client against a source double, not actual World database composition, current restriction authority, physical-COMMIT expiry, release or positive admission. + V88 and the actual fresh `AccountRepository.save` source initialization now create explicit birth-only category revisions, current projections, immutable results and distinct restriction outbox records in the same transaction as a genuinely new Account. The owner readback verifies the insert provenance, exact result identities and recomputed closed payload digests. Retained or unmapped Accounts are not enrolled. Historical birth generation/fence remains unchanged when unrelated current Account authority advances; current authority is read separately. This bounded source does not implement later moderation transitions or prove current protective-lock absence, and no admission path consumes it yet. PostgreSQL-specific completeness, immutability and digest guards remain active in the real migration; bounded fixed-vocabulary columns also support jOOQ generation. The canonical first-JOIN producer now permits advanced tenant authority only after exact current Account-owned tenant event readback matches the captured generation, source version and fresh Game Design provenance. The genuine sequence-zero fresh tenant baseline and committed JOIN replay remain unchanged. A new PostgreSQL case provisions the real demo entitlement before the JOIN intent, binds its actual policy evidence and verifies the advanced event and exact retry; missing or substituted owner evidence remains denied. Definitions and unit collaborators are not physical execution proof. diff --git a/protos/world-management/v1/draft_terminal_service.proto b/protos/world-management/v1/draft_terminal_service.proto new file mode 100644 index 0000000000..b839e55728 --- /dev/null +++ b/protos/world-management/v1/draft_terminal_service.proto @@ -0,0 +1,38 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Opt-in authenticated readback of immutable World Draft terminal evidence. +service WorldDraftTerminalReadService { + rpc ReadWorldDraftTerminalOutcome(ReadWorldDraftTerminalOutcomeRequest) + returns (ReadWorldDraftTerminalOutcomeResponse); +} + +enum WorldDraftTerminalReadStatus { + WORLD_DRAFT_TERMINAL_READ_STATUS_UNSPECIFIED = 0; + WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN = 1; + WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED = 2; + WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED = 3; +} + +message ReadWorldDraftTerminalOutcomeRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete canonical Account fence bytes; this is read identity, not permission. + bytes original_account_binding = 4; +} + +message ReadWorldDraftTerminalOutcomeResponse { + // The complete request tuple is echoed byte-for-byte, including the original Account binding. + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + bytes original_account_binding = 4; + WorldDraftTerminalReadStatus status = 5; + // Canonical account-draft-owner-readback/v1 bytes. Empty only for UNKNOWN. + bytes owner_readback_bytes = 6; +} diff --git a/protos/world-management/v1/world_canonical_player_admission_hold.proto b/protos/world-management/v1/world_canonical_player_admission_hold.proto new file mode 100644 index 0000000000..94b82b5b7b --- /dev/null +++ b/protos/world-management/v1/world_canonical_player_admission_hold.proto @@ -0,0 +1,45 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Distinct Account-to-World player-admission hold; neither binding admission nor hold release. +service WorldCanonicalPlayerAdmissionHoldService { + rpc AcquireCanonicalPlayerAdmissionHold(AcquireCanonicalPlayerAdmissionHoldRequest) + returns (AcquireCanonicalPlayerAdmissionHoldResponse); + rpc ReadCanonicalPlayerAdmissionHold(ReadCanonicalPlayerAdmissionHoldRequest) + returns (ReadCanonicalPlayerAdmissionHoldResponse); +} + +message AcquireCanonicalPlayerAdmissionHoldRequest { + // Fresh read correlation, echoed only; never the durable Account lease/attempt identity. + string request_id = 1; + bytes original_lease_json = 2; + string original_lease_sha256 = 3; + string expected_lifecycle_epoch = 4; + string expected_row_version = 5; +} + +message AcquireCanonicalPlayerAdmissionHoldResponse { + string request_id = 1; + string original_lease_sha256 = 2; + bytes hold_evidence_json = 3; + string hold_evidence_sha256 = 4; +} + +message ReadCanonicalPlayerAdmissionHoldRequest { + string request_id = 1; + bytes original_lease_json = 2; + string original_lease_sha256 = 3; + string expected_lifecycle_epoch = 4; + string expected_row_version = 5; +} + +message ReadCanonicalPlayerAdmissionHoldResponse { + string request_id = 1; + string original_lease_sha256 = 2; + bytes hold_evidence_json = 3; + string hold_evidence_sha256 = 4; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/WorldGameplayAdmissionHoldClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/WorldGameplayAdmissionHoldClient.java new file mode 100644 index 0000000000..55aea088d3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/WorldGameplayAdmissionHoldClient.java @@ -0,0 +1,243 @@ +package net.firedevops.firemud.accountservice.client; + +import com.google.protobuf.ByteString; +import io.grpc.ClientInterceptors; +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalPlayerAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalPlayerAdmissionHoldServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Account mTLS acquire/read consumer for the distinct World player-serving hold. + * Returned evidence authenticates original hold readback only; it supplies no current Account + * authority, admission, release, source finalization, or physical Account COMMIT proof. + */ +public final class WorldGameplayAdmissionHoldClient + extends AbstractReloadingBlockingGrpcClient< + WorldCanonicalPlayerAdmissionHoldServiceGrpc + .WorldCanonicalPlayerAdmissionHoldServiceBlockingStub> { + private final String workloadNamespace; + private final GrpcServerPeerIdentityClientInterceptor serverPeerIdentityInterceptor; + private final GrpcServerPeerIdentityCallCredentials serverPeerIdentityCallCredentials; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldGameplayAdmissionHoldClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireAccountMtls(tlsProps), + channelFactory, + WorldGameplayAdmissionHoldClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) + throw new IllegalArgumentException("Account workload namespace must be one DNS label"); + this.workloadNamespace = workloadNamespace; + String peer = "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + serverPeerIdentityInterceptor = new GrpcServerPeerIdentityClientInterceptor(peer); + serverPeerIdentityCallCredentials = new GrpcServerPeerIdentityCallCredentials(peer); + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("World admission hold client is closed"); + if (initialized) return; + try { + initReloadingClient(); + initialized = true; + } catch (IOException | RuntimeException failure) { + closed = true; + throw failure; + } + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldCanonicalPlayerAdmissionHoldServiceGrpc + .WorldCanonicalPlayerAdmissionHoldServiceBlockingStub + buildStub(ManagedChannel channel) { + return WorldCanonicalPlayerAdmissionHoldServiceGrpc.newBlockingStub( + ClientInterceptors.intercept(channel, serverPeerIdentityInterceptor)) + .withCallCredentials(serverPeerIdentityCallCredentials) + .withCompression("gzip"); + } + + /** Acquires the original lease-bound hold; no retry creates or extends an admission lease. */ + public WorldCanonicalPlayerAdmissionHoldEvidence acquire(Request original) { + requireCall(original); + UUID correlation = freshCorrelation(original); + var response = + stub() + .withDeadlineAfter(5L, TimeUnit.SECONDS) + .acquireCanonicalPlayerAdmissionHold( + AcquireCanonicalPlayerAdmissionHoldRequest.newBuilder() + .setRequestId(correlation.toString()) + .setOriginalLeaseJson(leaseBytes(original)) + .setOriginalLeaseSha256(original.lease().sha256()) + .setExpectedLifecycleEpoch(Long.toString(original.expectedLifecycleEpoch())) + .setExpectedRowVersion(Long.toString(original.expectedRowVersion())) + .build()); + if (response == null || !response.getUnknownFields().asMap().isEmpty()) throw invalid(); + return checked( + original, + correlation, + response.getRequestId(), + response.getOriginalLeaseSha256(), + response.getHoldEvidenceJson(), + response.getHoldEvidenceSha256()); + } + + /** Recovers authenticated original evidence; a missing response remains unresolved. */ + public WorldCanonicalPlayerAdmissionHoldEvidence read(Request original) { + requireCall(original); + UUID correlation = freshCorrelation(original); + var response = + stub() + .withDeadlineAfter(5L, TimeUnit.SECONDS) + .readCanonicalPlayerAdmissionHold( + ReadCanonicalPlayerAdmissionHoldRequest.newBuilder() + .setRequestId(correlation.toString()) + .setOriginalLeaseJson(leaseBytes(original)) + .setOriginalLeaseSha256(original.lease().sha256()) + .setExpectedLifecycleEpoch(Long.toString(original.expectedLifecycleEpoch())) + .setExpectedRowVersion(Long.toString(original.expectedRowVersion())) + .build()); + if (response == null || !response.getUnknownFields().asMap().isEmpty()) throw invalid(); + return checked( + original, + correlation, + response.getRequestId(), + response.getOriginalLeaseSha256(), + response.getHoldEvidenceJson(), + response.getHoldEvidenceSha256()); + } + + /** An already retained hold cannot be replaced by another valid hold for the same request. */ + public WorldCanonicalPlayerAdmissionHoldEvidence readExact( + WorldCanonicalPlayerAdmissionHoldEvidence original) { + Objects.requireNonNull(original, "Original World hold is required"); + var observed = read(original.request()); + if (!original.holdId().equals(observed.holdId()) + || !original.holdFence().equals(observed.holdFence()) + || !Arrays.equals(original.canonicalBytes(), observed.canonicalBytes())) throw invalid(); + return observed; + } + + private void requireCall(Request original) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException( + "World hold calls cannot run inside Account transaction or synchronization"); + Objects.requireNonNull(original, "Original Account lease request is required"); + if (!workloadNamespace.equals(original.targetNamespace())) + throw new IllegalArgumentException( + "Original lease does not match configured workload namespace"); + if (closed || !initialized || stub() == null) + throw new IllegalStateException( + "World admission hold client is not initialized or is closed"); + } + + private static UUID freshCorrelation(Request original) { + UUID id; + do { + id = UUID.randomUUID(); + } while (id.equals(original.attemptId()) || id.equals(original.leaseId())); + return id; + } + + private static ByteString leaseBytes(Request original) { + return ByteString.copyFrom(original.lease().canonicalJson(), StandardCharsets.UTF_8); + } + + private static WorldCanonicalPlayerAdmissionHoldEvidence checked( + Request original, + UUID correlation, + String echo, + String leaseSha, + ByteString bytes, + String sha) { + try { + UUID parsed = UUID.fromString(echo); + if (!parsed.equals(correlation) + || !parsed.toString().equals(echo) + || parsed.version() != 4 + || parsed.variant() != 2 + || !original.lease().sha256().equals(leaseSha) + || bytes.isEmpty() + || bytes.size() > WorldCanonicalPlayerAdmissionHoldEvidence.MAX_EVIDENCE_BYTES) + throw invalid(); + var result = + WorldCanonicalPlayerAdmissionHoldEvidence.fromCanonical(bytes.toByteArray(), sha); + if (!original.sameBinding(result.request()) + || !original.lease().canonicalJson().equals(result.request().lease().canonicalJson())) + throw invalid(); + original.requireExactActiveWorld(result.worldEvidence()); + return result; + } catch (IllegalArgumentException failure) { + throw new IllegalStateException("World admission hold response is invalid", failure); + } + } + + private static IllegalStateException invalid() { + return new IllegalStateException("World admission hold response is invalid or unresolved"); + } + + private static CommonGrpcClientProperties requireAccountMtls( + CommonGrpcClientProperties tlsProps) { + if (tlsProps == null || tlsProps.isPlaintext()) + throw new IllegalArgumentException( + "World admission hold calls require Account workload mTLS"); + if (!isReadableFile(tlsProps.getCertChain()) + || !isReadableFile(tlsProps.getPrivateKey()) + || !isReadableFile(tlsProps.getCaCert())) + throw new IllegalArgumentException( + "World admission hold calls require readable file-backed Account certificate, key and CA"); + return tlsProps; + } + + private static boolean isReadableFile(String value) { + if (value == null || value.isBlank() || value.trim().startsWith("classpath:")) return false; + try { + Path path = Path.of(value.trim()); + return Files.isRegularFile(path) && Files.isReadable(path); + } catch (RuntimeException failure) { + return false; + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/client/WorldGameplayAdmissionHoldClientMtlsIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/client/WorldGameplayAdmissionHoldClientMtlsIntegrationTest.java new file mode 100644 index 0000000000..c621ca16a4 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/client/WorldGameplayAdmissionHoldClientMtlsIntegrationTest.java @@ -0,0 +1,1218 @@ +package integration.net.firedevops.firemud.accountservice.client; + +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 io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.UnaryOperator; +import net.firedevops.firemud.accountservice.client.WorldGameplayAdmissionHoldClient; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalPlayerAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalPlayerAdmissionHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalPlayerAdmissionHoldServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Physical mTLS sockets against a synthetic transport source double, not World owner/database + * proof. + */ +class WorldGameplayAdmissionHoldClientMtlsIntegrationTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String OTHER_NAMESPACE_URI = + "spiffe://firemud/ns/other-test/sa/world-management-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String OTHER_ACCOUNT_URI = + "spiffe://firemud/ns/other-test/sa/account-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final String ID = "11111111-1111-4111-8111-111111111111"; + private static final String ACCOUNT = "22222222-2222-4222-8222-222222222222"; + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private WorldGameplayAdmissionHoldClient client; + private AtomicInteger headers; + private AtomicInteger ownerResults; + private AtomicInteger acquireCalls; + private WorldCanonicalPlayerAdmissionHoldEvidence original; + private WorldCanonicalPlayerAdmissionHoldEvidence acquiredHold; + private boolean loseAcquireResponseOnce; + private Status serviceFailure; + private boolean absent; + private UnaryOperator responseMutation = + UnaryOperator.identity(); + private final List correlations = new ArrayList<>(); + + @BeforeAll + static void createTrustedCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + closeTransport(); + } + + @Test + void exactAcquireAndLostResponseReadRecoverOriginalUnchangedHold() throws Exception { + startServer(pki.worldServer()); + client = newClient(server, pki.accountClient()); + client.init(); + loseAcquireResponseOnce = true; + assertThatThrownBy(() -> client.acquire(original.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> assertThat(Status.fromThrowable(e).getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(acquiredHold.canonicalBytes()).containsExactly(original.canonicalBytes()); + var recovered = client.read(original.request()); + assertThat(recovered.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(recovered.holdId()).isEqualTo(original.holdId()); + assertThat(recovered.holdFence()).isEqualTo(original.holdFence()); + assertThat(client.readExact(recovered).canonicalBytes()) + .containsExactly(original.canonicalBytes()); + assertThat(correlations).hasSize(3).doesNotHaveDuplicates(); + assertThat(ownerResults).hasValue(3); + assertThat(acquireCalls).hasValue(1); + } + + @Test + void trustedWrongServerReleasesNoHeadersOrBody() throws Exception { + for (var identity : List.of(pki.wrongWorkloadServer(), pki.otherNamespaceServer())) { + startServer(identity); + client = newClient(server, pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.acquire(original.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(ownerResults).hasValue(0); + closeTransport(); + } + } + + @Test + void wrongCallerCannotReachSourceDouble() throws Exception { + for (var identity : List.of(pki.wrongAccountClient(), pki.otherNamespaceAccount())) { + startServer(pki.worldServer()); + client = newClient(server, identity); + client.init(); + assertThatThrownBy(() -> client.read(original.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(ownerResults).hasValue(0); + closeTransport(); + } + } + + @Test + void authenticatedChangedCorrelationDigestAndUnknownFieldsAreDenied() throws Exception { + List> changes = + List.of( + r -> r.toBuilder().setRequestId(UUID.randomUUID().toString()).build(), + r -> r.toBuilder().setOriginalLeaseSha256("a".repeat(64)).build(), + r -> r.toBuilder().setHoldEvidenceSha256("b".repeat(64)).build(), + r -> + r.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build()); + for (var change : changes) { + startServer(pki.worldServer()); + responseMutation = change; + client = newClient(server, pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.read(original.request())) + .isInstanceOf(IllegalStateException.class); + closeTransport(); + } + } + + @Test + void unavailableAndAbsentReadRemainUnresolved() throws Exception { + startServer(pki.worldServer()); + client = newClient(server, pki.accountClient()); + client.init(); + serviceFailure = Status.UNAVAILABLE.withDescription("synthetic source unavailable"); + assertThatThrownBy(() -> client.read(original.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> assertThat(Status.fromThrowable(e).getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + serviceFailure = null; + absent = true; + assertThatThrownBy(() -> client.read(original.request())) + .isInstanceOf(IllegalStateException.class); + } + + private void requireRequest( + String correlation, ByteString lease, String sha, String epoch, String row) { + ownerResults.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + assertThat(lease.toStringUtf8()).isEqualTo(original.request().lease().canonicalJson()); + assertThat(sha).isEqualTo(original.request().lease().sha256()); + assertThat(epoch).isEqualTo(Long.toString(original.request().expectedLifecycleEpoch())); + assertThat(row).isEqualTo(Long.toString(original.request().expectedRowVersion())); + assertThat(UUID.fromString(correlation).version()).isEqualTo(4); + assertThat(correlation) + .isNotEqualTo(original.request().attemptId().toString()) + .isNotEqualTo(original.request().leaseId().toString()); + correlations.add(correlation); + } + + private void startServer(TestIdentity identity) throws Exception { + closeTransport(); + original = hold(); + headers = new AtomicInteger(); + ownerResults = new AtomicInteger(); + acquireCalls = new AtomicInteger(); + acquiredHold = null; + loseAcquireResponseOnce = false; + serviceFailure = null; + absent = false; + responseMutation = UnaryOperator.identity(); + correlations.clear(); + var service = + new WorldCanonicalPlayerAdmissionHoldServiceGrpc + .WorldCanonicalPlayerAdmissionHoldServiceImplBase() { + @Override + public void acquireCanonicalPlayerAdmissionHold( + AcquireCanonicalPlayerAdmissionHoldRequest request, + StreamObserver observer) { + requireRequest( + request.getRequestId(), + request.getOriginalLeaseJson(), + request.getOriginalLeaseSha256(), + request.getExpectedLifecycleEpoch(), + request.getExpectedRowVersion()); + acquireCalls.incrementAndGet(); + // Synthetic source applied the original hold before its acknowledgement is lost. + acquiredHold = original; + if (loseAcquireResponseOnce) { + loseAcquireResponseOnce = false; + observer.onError( + Status.UNAVAILABLE + .withDescription("Synthetic acquire response lost") + .asRuntimeException()); + return; + } + observer.onNext( + AcquireCanonicalPlayerAdmissionHoldResponse.newBuilder() + .setRequestId(request.getRequestId()) + .setOriginalLeaseSha256(original.request().lease().sha256()) + .setHoldEvidenceJson(ByteString.copyFrom(original.canonicalBytes())) + .setHoldEvidenceSha256(original.sha256()) + .build()); + observer.onCompleted(); + } + + @Override + public void readCanonicalPlayerAdmissionHold( + ReadCanonicalPlayerAdmissionHoldRequest request, + StreamObserver observer) { + requireRequest( + request.getRequestId(), + request.getOriginalLeaseJson(), + request.getOriginalLeaseSha256(), + request.getExpectedLifecycleEpoch(), + request.getExpectedRowVersion()); + if (serviceFailure != null) { + observer.onError(serviceFailure.asRuntimeException()); + return; + } + var result = + ReadCanonicalPlayerAdmissionHoldResponse.newBuilder() + .setRequestId(request.getRequestId()) + .setOriginalLeaseSha256(original.request().lease().sha256()); + var retained = acquiredHold == null ? original : acquiredHold; + if (!absent) + result + .setHoldEvidenceJson(ByteString.copyFrom(retained.canonicalBytes())) + .setHoldEvidenceSha256(retained.sha256()); + observer.onNext(responseMutation.apply(result.build())); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + ServerInterceptor exactAccountCallerGuard = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !ACCOUNT_URI.equals(peer.uri())) { + call.close( + Status.UNAUTHENTICATED.withDescription("Exact Account workload required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, + exactAccountCallerGuard, + countHeaders, + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private WorldGameplayAdmissionHoldClient newClient(Server target, TestIdentity caller) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + target.getPort()); + return new WorldGameplayAdmissionHoldClient( + endpoints, + pki.clientProperties(tempDirectory, caller), + new GrpcChannelFactory(), + NAMESPACE); + } + + private void closeTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + private static WorldCanonicalPlayerAdmissionHoldEvidence hold() throws Exception { + var world = lifecycleEvidence(); + var carrier = carrier(); + var boundScope = new LinkedHashMap<>(scope(carrier)); + boundScope.put("worldSlug", world.request().worldSlug()); + boundScope.put( + "playableStateNamespaceId", world.request().playableStateNamespaceId().toString()); + carrier.put("bindingScope", boundScope); + var lease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + return new WorldCanonicalPlayerAdmissionHoldEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + lease, world.lifecycleEpoch(), world.rowVersion()), + world); + } + + // Only synthetic fixture construction is adapted from existing Common Core codec tests below. + + private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID TENANT_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REVISION_ID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID REGION_TEMPLATE_ID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID ZONE_TEMPLATE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID ROOM_TEMPLATE_ID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID REGION_REVISION_ID = uuid("12345678-1234-4234-8234-123456789001"); + private static final UUID ZONE_REVISION_ID = uuid("12345678-1234-4234-8234-123456789002"); + private static final UUID ROOM_REVISION_ID = uuid("12345678-1234-4234-8234-123456789003"); + private static final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + private static WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence() throws Exception { + WorldPublishedStartLocationEvidence selector = publishedSelector(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.request().targetNamespace(), + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + RoomTemplateRef startLocation = selectorReceipt.startLocation(); + Request request = + new Request( + Request.SCHEMA_VERSION, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + startLocation, + 1042L, + "ACTIVE", + 3L, + 0L, + uuid("33333333-3333-4333-8333-333333333333"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "e".repeat(64)); + } + + static WorldPublishedStartLocationEvidence publishedSelector() throws Exception { + WorldDraftTerminalReadEvidence.Request terminalRequest = freshGraphRequest(); + OwnerReadback committed = committedReadback(terminalRequest, true); + var account = terminalRequest.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + List tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + account.tenantId(), + account.versionId(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + account.commitId().toString(), + "b".repeat(64), + 3, + tuples); + var applied = JSON.readTree(committed.result()); + byte[] receipt = + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()); + return new WorldPublishedStartLocationEvidence( + request, receipt, committed.fullBinding(), committed.result()); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request, boolean freshGraph) throws Exception { + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var operation = new ByteArrayOutputStream(); + var frames = new java.io.DataOutputStream(operation); + java.util.function.Consumer frame = + bytes -> { + try { + frames.writeInt(bytes.length); + frames.write(bytes); + } catch (java.io.IOException impossible) { + throw new AssertionError(impossible); + } + }; + java.util.function.Consumer text = + value -> frame.accept(value.getBytes(StandardCharsets.UTF_8)); + text.accept("world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) text.accept(id.toString()); + frame.accept(draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + Long.toString(draft.target().gameDesignVersionRowId()), + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "a".repeat(64), + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "b".repeat(64), + "c".repeat(64))) text.accept(value); + text.accept(sha256(account.canonicalBytes())); + frame.accept(account.canonicalBytes()); + byte[] graph = freshGraph ? graphBytes(request, draft) : historicalGraphBytes(account); + String graphDigest = sha256(graph); + var result = new java.util.LinkedHashMap(); + result.put( + "schema", freshGraph ? "world-draft-graph-applied/v2" : "world-draft-graph-applied/v1"); + result.put("status", "APPLIED"); + result.put("operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + if (freshGraph) { + var receipt = receipt(request, draft, graphDigest); + byte[] receiptBytes = canonical(receipt); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.get("receiptDigest").textValue()); + } + result.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) + .toList()); + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + canonical(JSON.valueToTree(result))); + } + + private static WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { + DraftCommitBinding draft = freshGraphBinding(); + return new WorldDraftTerminalReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), accountBinding(draft)); + } + + private static DraftCommitBinding freshGraphBinding() throws Exception { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "startLocation", + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + "1", + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_TEMPLATE_ID, null)), + new RevisionPayload( + "2", + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_TEMPLATE_ID, null))), + List.of( + affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private static String worldRevisionPayload( + UUID revisionId, String family, UUID templateId, String declaration) throws Exception { + var payload = new java.util.LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", COMMIT_ID.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(payload); + } + + private static List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private static byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private static byte[] historicalGraphBytes(DraftAuthorizationFenceBinding binding) { + return ("{\"schemaVersion\":\"2\",\"canonicalTenantId\":\"" + + binding.tenantId() + + "\",\"canonicalVersionId\":\"" + + binding.versionId() + + "\",\"rows\":[{}]}") + .getBytes(StandardCharsets.UTF_8); + } + + private static byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new java.util.LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new java.util.ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + var mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new java.util.LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", OPERATION_ID.toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private static tools.jackson.databind.node.ObjectNode receipt( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, String graphDigest) + throws Exception { + var account = request.accountBinding(); + var selector = + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()); + String accountBindingDigest = sha256(request.originalAccountBinding()); + String receiptDigest = + startLocationReceiptDigest( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + accountBindingDigest, + draft.digest(), + TENANT_ID, + VERSION_ID, + ROOM_TEMPLATE_ID, + graphDigest); + var value = new java.util.LinkedHashMap(); + value.put("schema", "world-draft-start-location-receipt/v1"); + value.put("targetNamespace", request.targetNamespace()); + value.put("operationId", account.operationId().toString()); + value.put("requestId", account.requestId().toString()); + value.put("commitId", account.commitId().toString()); + value.put("authorizationFenceId", account.fenceId().toString()); + value.put("accountBindingDigest", accountBindingDigest); + value.put("bindingDigest", draft.digest()); + value.put("startLocation", selector); + value.put("graphDigest", graphDigest); + value.put("receiptDigest", receiptDigest); + return (tools.jackson.databind.node.ObjectNode) JSON.valueToTree(value); + } + + private static String startLocationReceiptDigest( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + String accountBindingDigest, + String bindingDigest, + UUID tenantId, + UUID versionId, + UUID roomTemplateId, + String graphDigest) + throws Exception { + var framed = new ByteArrayOutputStream(); + for (String value : + List.of( + "world-draft-start-location-receipt/v1", + targetNamespace, + operationId.toString(), + requestId.toString(), + commitId.toString(), + fenceId.toString(), + accountBindingDigest, + bindingDigest, + tenantId.toString(), + versionId.toString(), + roomTemplateId.toString(), + graphDigest)) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + framed.writeBytes(bytes); + } + return sha256(framed.toByteArray()); + } + + private static byte[] canonical(tools.jackson.databind.JsonNode value) throws Exception { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + static Map carrier() { + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", "test"); + value.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + value.put("requestId", ID); + value.put("leaseId", ACCOUNT); + value.put("leaseFence", "1"); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "tenantId", + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, ID); + scope.put("accountId", ACCOUNT); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "9007199254740993"); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + Map.of(ID, "1"), + "privateRealmGrantVersions", + List.of())); + value.put("issuanceFence", "1"); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + "1")); + value.put( + "outboxCheckpoints", + List.of( + checkpoint("account/" + ACCOUNT, "0"), + checkpoint("issuer/firemud-account-service", "0"), + checkpoint("membership/" + ACCOUNT + "/" + ID, "1"), checkpoint("tenant/" + ID, "1"))); + long now = System.currentTimeMillis(); + value.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", ACCOUNT), + Map.entry("operationId", ID), + Map.entry("issuanceRequestId", ID), + Map.entry("tokenJti", ID), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("issuedAt", Long.toString(now / 1000)), + Map.entry("notBefore", Long.toString(now / 1000)), + Map.entry("expiresAt", Long.toString(now / 1000 + 300)))); + value.put("evaluatedAt", Long.toString(now)); + value.put("expiresAt", Long.toString(now + 15000)); + return value; + } + + @SuppressWarnings("unchecked") + static Map scope(Map carrier) { + return (Map) carrier.get("bindingScope"); + } + + private static Map checkpoint(String suffix, String sequence) { + return Map.of( + "outboxStreamKey", "account:auth-authority:v1:" + suffix, "outboxSequence", sequence); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity worldServer, + TestIdentity wrongWorkloadServer, + TestIdentity otherNamespaceServer, + TestIdentity accountClient, + TestIdentity wrongAccountClient, + TestIdentity otherNamespaceAccount) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("admission-decision-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD admission-decision test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("admission-decision-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "gs-server", WORLD_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_WORKLOAD_URI, true), + issueIdentity( + directory, caStore, caFile, "other-namespace-server", OTHER_NAMESPACE_URI, true), + issueIdentity(directory, caStore, caFile, "account-client", ACCOUNT_URI, false), + issueIdentity( + directory, caStore, caFile, "wrong-account-client", WRONG_WORKLOAD_URI, false), + issueIdentity( + directory, caStore, caFile, "other-namespace-account", OTHER_ACCOUNT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path cert = + writePem( + directory.resolve("caller.crt"), "CERTIFICATE", identity.certificate().getEncoded()); + Path key = + writePem( + directory.resolve("caller.key"), "PRIVATE KEY", identity.privateKey().getEncoded()); + Path ca = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(cert.toString()); + properties.setPrivateKey(key.toString()); + properties.setCaCert(ca.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + String eku = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/WorldGameplayAdmissionHoldClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/WorldGameplayAdmissionHoldClientTest.java new file mode 100644 index 0000000000..b0f2b404dd --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/WorldGameplayAdmissionHoldClientTest.java @@ -0,0 +1,930 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import java.io.ByteArrayOutputStream; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalPlayerAdmissionHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalPlayerAdmissionHoldServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mocked transport with real nested codecs and synthetic lease/World sources; not owner proof. */ +class WorldGameplayAdmissionHoldClientTest { + private static final String ID = "11111111-1111-4111-8111-111111111111"; + private static final String ACCOUNT = "22222222-2222-4222-8222-222222222222"; + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void acquireAndLostResponseReadPreserveOriginalBytesAndFreshCorrelation(@TempDir Path dir) + throws Exception { + var original = hold(); + var stub = stub(); + List correlations = new java.util.ArrayList<>(); + when(stub.acquireCanonicalPlayerAdmissionHold(any())) + .thenAnswer( + invocation -> { + net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalPlayerAdmissionHoldRequest + request = invocation.getArgument(0); + correlations.add(request.getRequestId()); + assertThat(request.getOriginalLeaseJson().toStringUtf8()) + .isEqualTo(original.request().lease().canonicalJson()); + assertThat(request.getExpectedLifecycleEpoch()) + .isEqualTo(Long.toString(original.request().expectedLifecycleEpoch())); + assertThat(request.getExpectedRowVersion()) + .isEqualTo(Long.toString(original.request().expectedRowVersion())); + return AcquireCanonicalPlayerAdmissionHoldResponse.newBuilder() + .setRequestId(request.getRequestId()) + .setOriginalLeaseSha256(original.request().lease().sha256()) + .setHoldEvidenceJson(ByteString.copyFrom(original.canonicalBytes())) + .setHoldEvidenceSha256(original.sha256()) + .build(); + }); + when(stub.readCanonicalPlayerAdmissionHold(any())) + .thenAnswer( + invocation -> { + net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldRequest + request = invocation.getArgument(0); + correlations.add(request.getRequestId()); + assertThat(request.getOriginalLeaseJson().toStringUtf8()) + .isEqualTo(original.request().lease().canonicalJson()); + return response(request.getRequestId(), original); + }); + var client = client(stub, dir, "test"); + assertThat(client.acquire(original.request()).canonicalBytes()) + .containsExactly(original.canonicalBytes()); + assertThat(client.read(original.request()).canonicalBytes()) + .containsExactly(original.canonicalBytes()); + assertThat(client.readExact(original).canonicalBytes()) + .containsExactly(original.canonicalBytes()); + assertThat(correlations).doesNotHaveDuplicates(); + for (String id : correlations) { + assertThat(UUID.fromString(id).version()).isEqualTo(4); + assertThat(id) + .isNotEqualTo(original.request().attemptId().toString()) + .isNotEqualTo(original.request().leaseId().toString()); + } + verify(stub, org.mockito.Mockito.times(3)).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void rejectsChangedCorrelationDigestUnknownFieldsMissingAndMalformedRead(@TempDir Path dir) + throws Exception { + var original = hold(); + List> changes = + List.of( + r -> r.toBuilder().setRequestId(UUID.randomUUID().toString()).build(), + r -> r.toBuilder().setRequestId("not-uuid").build(), + r -> r.toBuilder().setOriginalLeaseSha256("b".repeat(64)).build(), + r -> r.toBuilder().setHoldEvidenceSha256("c".repeat(64)).build(), + r -> r.toBuilder().clearHoldEvidenceJson().clearHoldEvidenceSha256().build(), + r -> + r.toBuilder() + .setHoldEvidenceJson(ByteString.copyFrom(new byte[] {(byte) 0xc3, 0x28})) + .build(), + r -> + r.toBuilder() + .setHoldEvidenceJson( + ByteString.copyFrom( + new byte + [WorldCanonicalPlayerAdmissionHoldEvidence.MAX_EVIDENCE_BYTES + 1])) + .build(), + r -> + r.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build()); + for (var change : changes) { + var stub = stub(); + when(stub.readCanonicalPlayerAdmissionHold(any())) + .thenAnswer( + invocation -> { + net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldRequest + request = invocation.getArgument(0); + return change.apply(response(request.getRequestId(), original)); + }); + assertThatThrownBy(() -> client(stub, dir, "test").read(original.request())) + .isInstanceOf(IllegalStateException.class); + } + } + + @Test + void rejectsValidSubstitutedLeaseEpochAndRetainedHoldIdentities(@TempDir Path dir) + throws Exception { + var original = hold(); + var world = original.worldEvidence(); + var changedWorld = + new WorldCanonicalInstanceLifecycleEvidence( + world.request(), + world.launchBinding(), + world.startLocation(), + world.runtimeRoomInstanceId(), + "ACTIVE", + world.lifecycleEpoch() + 1, + world.rowVersion(), + world.captureId(), + world.graphSha256(), + world.preparationInputDigest()); + var epoch = + new WorldCanonicalPlayerAdmissionHoldEvidence( + original.holdId(), + original.holdFence(), + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + original.request().lease(), + changedWorld.lifecycleEpoch(), + changedWorld.rowVersion()), + changedWorld); + var changedCarrier = new LinkedHashMap<>(original.request().lease().carrier()); + changedCarrier.put("requestId", UUID.randomUUID().toString()); + var lease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + var changedLease = + new WorldCanonicalPlayerAdmissionHoldEvidence( + original.holdId(), + original.holdFence(), + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + lease, world.lifecycleEpoch(), world.rowVersion()), + world); + for (var changed : + List.of( + epoch, + changedLease, + new WorldCanonicalPlayerAdmissionHoldEvidence( + UUID.randomUUID(), original.holdFence(), original.request(), world), + new WorldCanonicalPlayerAdmissionHoldEvidence( + original.holdId(), UUID.randomUUID(), original.request(), world))) { + var stub = stub(); + when(stub.readCanonicalPlayerAdmissionHold(any())) + .thenAnswer( + invocation -> { + net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldRequest + request = invocation.getArgument(0); + return response(request.getRequestId(), changed).toBuilder() + .setOriginalLeaseSha256(original.request().lease().sha256()) + .build(); + }); + assertThatThrownBy(() -> client(stub, dir, "test").readExact(original)) + .isInstanceOf(IllegalStateException.class); + } + } + + @Test + void transactionSynchronizationAndWrongNamespaceDenyBeforeRpc(@TempDir Path dir) + throws Exception { + var original = hold(); + var stub = stub(); + var client = client(stub, dir, "test"); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.acquire(original.request())) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.read(original.request())) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.clear(); + assertThatThrownBy(() -> client(stub, dir, "other").read(original.request())) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(stub); + } + + @Test + void propagatesUnavailableAndDeniesUninitializedClosedAndPlaintext(@TempDir Path dir) + throws Exception { + var original = hold(); + var stub = stub(); + var failure = Status.UNAVAILABLE.asRuntimeException(); + when(stub.readCanonicalPlayerAdmissionHold(any())).thenThrow(failure); + assertThatThrownBy(() -> client(stub, dir, "test").read(original.request())).isSameAs(failure); + var tls = tls(dir); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldGameplayAdmissionHoldClient( + new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "test")) + .isInstanceOf(IllegalArgumentException.class); + var uninitialized = + new WorldGameplayAdmissionHoldClient( + new ServiceEndpointsProperties(), tls(dir), mock(GrpcChannelFactory.class), "test"); + assertThatThrownBy(() -> uninitialized.read(original.request())) + .isInstanceOf(IllegalStateException.class); + uninitialized.close(); + assertThatThrownBy(uninitialized::init).isInstanceOf(IllegalStateException.class); + } + + private static WorldCanonicalPlayerAdmissionHoldServiceGrpc + .WorldCanonicalPlayerAdmissionHoldServiceBlockingStub + stub() { + var stub = + mock( + WorldCanonicalPlayerAdmissionHoldServiceGrpc + .WorldCanonicalPlayerAdmissionHoldServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static WorldGameplayAdmissionHoldClient client( + WorldCanonicalPlayerAdmissionHoldServiceGrpc + .WorldCanonicalPlayerAdmissionHoldServiceBlockingStub + stub, + Path dir, + String namespace) + throws Exception { + var client = + new WorldGameplayAdmissionHoldClient( + new ServiceEndpointsProperties(), tls(dir), mock(GrpcChannelFactory.class), namespace); + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + field = WorldGameplayAdmissionHoldClient.class.getDeclaredField("initialized"); + field.setAccessible(true); + field.setBoolean(client, true); + return client; + } + + private static CommonGrpcClientProperties tls(Path dir) throws Exception { + // Readable placeholder files support mocked transport only. + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(dir.resolve("client.crt"), "test").toString()); + tls.setPrivateKey(Files.writeString(dir.resolve("client.key"), "test").toString()); + tls.setCaCert(Files.writeString(dir.resolve("ca.crt"), "test").toString()); + return tls; + } + + private static ReadCanonicalPlayerAdmissionHoldResponse response( + String correlation, WorldCanonicalPlayerAdmissionHoldEvidence original) { + return ReadCanonicalPlayerAdmissionHoldResponse.newBuilder() + .setRequestId(correlation) + .setOriginalLeaseSha256(original.request().lease().sha256()) + .setHoldEvidenceJson(ByteString.copyFrom(original.canonicalBytes())) + .setHoldEvidenceSha256(original.sha256()) + .build(); + } + + private static WorldCanonicalPlayerAdmissionHoldEvidence hold() throws Exception { + var world = lifecycleEvidence(); + var carrier = carrier(); + var boundScope = new LinkedHashMap<>(scope(carrier)); + boundScope.put("worldSlug", world.request().worldSlug()); + boundScope.put( + "playableStateNamespaceId", world.request().playableStateNamespaceId().toString()); + carrier.put("bindingScope", boundScope); + var lease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + return new WorldCanonicalPlayerAdmissionHoldEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + lease, world.lifecycleEpoch(), world.rowVersion()), + world); + } + + // Only synthetic fixture construction is adapted from existing Common Core codec tests below. + + private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID TENANT_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REVISION_ID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID REGION_TEMPLATE_ID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID ZONE_TEMPLATE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID ROOM_TEMPLATE_ID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID REGION_REVISION_ID = uuid("12345678-1234-4234-8234-123456789001"); + private static final UUID ZONE_REVISION_ID = uuid("12345678-1234-4234-8234-123456789002"); + private static final UUID ROOM_REVISION_ID = uuid("12345678-1234-4234-8234-123456789003"); + private static final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + private static WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence() throws Exception { + WorldPublishedStartLocationEvidence selector = publishedSelector(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.request().targetNamespace(), + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + RoomTemplateRef startLocation = selectorReceipt.startLocation(); + Request request = + new Request( + Request.SCHEMA_VERSION, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + startLocation, + 1042L, + "ACTIVE", + 3L, + 0L, + uuid("33333333-3333-4333-8333-333333333333"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "e".repeat(64)); + } + + static WorldPublishedStartLocationEvidence publishedSelector() throws Exception { + WorldDraftTerminalReadEvidence.Request terminalRequest = freshGraphRequest(); + OwnerReadback committed = committedReadback(terminalRequest, true); + var account = terminalRequest.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + List tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + account.tenantId(), + account.versionId(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + account.commitId().toString(), + "b".repeat(64), + 3, + tuples); + var applied = JSON.readTree(committed.result()); + byte[] receipt = + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()); + return new WorldPublishedStartLocationEvidence( + request, receipt, committed.fullBinding(), committed.result()); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request, boolean freshGraph) throws Exception { + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var operation = new ByteArrayOutputStream(); + var frames = new java.io.DataOutputStream(operation); + java.util.function.Consumer frame = + bytes -> { + try { + frames.writeInt(bytes.length); + frames.write(bytes); + } catch (java.io.IOException impossible) { + throw new AssertionError(impossible); + } + }; + java.util.function.Consumer text = + value -> frame.accept(value.getBytes(StandardCharsets.UTF_8)); + text.accept("world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) text.accept(id.toString()); + frame.accept(draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + Long.toString(draft.target().gameDesignVersionRowId()), + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "a".repeat(64), + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "b".repeat(64), + "c".repeat(64))) text.accept(value); + text.accept(sha256(account.canonicalBytes())); + frame.accept(account.canonicalBytes()); + byte[] graph = freshGraph ? graphBytes(request, draft) : historicalGraphBytes(account); + String graphDigest = sha256(graph); + var result = new java.util.LinkedHashMap(); + result.put( + "schema", freshGraph ? "world-draft-graph-applied/v2" : "world-draft-graph-applied/v1"); + result.put("status", "APPLIED"); + result.put("operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + if (freshGraph) { + var receipt = receipt(request, draft, graphDigest); + byte[] receiptBytes = canonical(receipt); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.get("receiptDigest").textValue()); + } + result.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) + .toList()); + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + canonical(JSON.valueToTree(result))); + } + + private static WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { + DraftCommitBinding draft = freshGraphBinding(); + return new WorldDraftTerminalReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), accountBinding(draft)); + } + + private static DraftCommitBinding freshGraphBinding() throws Exception { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "startLocation", + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + "1", + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_TEMPLATE_ID, null)), + new RevisionPayload( + "2", + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_TEMPLATE_ID, null))), + List.of( + affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private static String worldRevisionPayload( + UUID revisionId, String family, UUID templateId, String declaration) throws Exception { + var payload = new java.util.LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", COMMIT_ID.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(payload); + } + + private static List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private static byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private static byte[] historicalGraphBytes(DraftAuthorizationFenceBinding binding) { + return ("{\"schemaVersion\":\"2\",\"canonicalTenantId\":\"" + + binding.tenantId() + + "\",\"canonicalVersionId\":\"" + + binding.versionId() + + "\",\"rows\":[{}]}") + .getBytes(StandardCharsets.UTF_8); + } + + private static byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new java.util.LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new java.util.ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + var mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new java.util.LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", OPERATION_ID.toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private static tools.jackson.databind.node.ObjectNode receipt( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, String graphDigest) + throws Exception { + var account = request.accountBinding(); + var selector = + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()); + String accountBindingDigest = sha256(request.originalAccountBinding()); + String receiptDigest = + startLocationReceiptDigest( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + accountBindingDigest, + draft.digest(), + TENANT_ID, + VERSION_ID, + ROOM_TEMPLATE_ID, + graphDigest); + var value = new java.util.LinkedHashMap(); + value.put("schema", "world-draft-start-location-receipt/v1"); + value.put("targetNamespace", request.targetNamespace()); + value.put("operationId", account.operationId().toString()); + value.put("requestId", account.requestId().toString()); + value.put("commitId", account.commitId().toString()); + value.put("authorizationFenceId", account.fenceId().toString()); + value.put("accountBindingDigest", accountBindingDigest); + value.put("bindingDigest", draft.digest()); + value.put("startLocation", selector); + value.put("graphDigest", graphDigest); + value.put("receiptDigest", receiptDigest); + return (tools.jackson.databind.node.ObjectNode) JSON.valueToTree(value); + } + + private static String startLocationReceiptDigest( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + String accountBindingDigest, + String bindingDigest, + UUID tenantId, + UUID versionId, + UUID roomTemplateId, + String graphDigest) + throws Exception { + var framed = new ByteArrayOutputStream(); + for (String value : + List.of( + "world-draft-start-location-receipt/v1", + targetNamespace, + operationId.toString(), + requestId.toString(), + commitId.toString(), + fenceId.toString(), + accountBindingDigest, + bindingDigest, + tenantId.toString(), + versionId.toString(), + roomTemplateId.toString(), + graphDigest)) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + framed.writeBytes(bytes); + } + return sha256(framed.toByteArray()); + } + + private static byte[] canonical(tools.jackson.databind.JsonNode value) throws Exception { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + static Map carrier() { + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", "test"); + value.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + value.put("requestId", ID); + value.put("leaseId", ACCOUNT); + value.put("leaseFence", "1"); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "tenantId", + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, ID); + scope.put("accountId", ACCOUNT); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "9007199254740993"); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + Map.of(ID, "1"), + "privateRealmGrantVersions", + List.of())); + value.put("issuanceFence", "1"); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + "1")); + value.put( + "outboxCheckpoints", + List.of( + checkpoint("account/" + ACCOUNT, "0"), + checkpoint("issuer/firemud-account-service", "0"), + checkpoint("membership/" + ACCOUNT + "/" + ID, "1"), checkpoint("tenant/" + ID, "1"))); + long now = System.currentTimeMillis(); + value.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", ACCOUNT), + Map.entry("operationId", ID), + Map.entry("issuanceRequestId", ID), + Map.entry("tokenJti", ID), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("issuedAt", Long.toString(now / 1000)), + Map.entry("notBefore", Long.toString(now / 1000)), + Map.entry("expiresAt", Long.toString(now / 1000 + 300)))); + value.put("evaluatedAt", Long.toString(now)); + value.put("expiresAt", Long.toString(now + 15000)); + return value; + } + + @SuppressWarnings("unchecked") + static Map scope(Map carrier) { + return (Map) carrier.get("bindingScope"); + } + + private static Map checkpoint(String suffix, String sequence) { + return Map.of( + "outboxStreamKey", "account:auth-authority:v1:" + suffix, "outboxSequence", sequence); + } +} diff --git a/services/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..a5a8e37767 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java @@ -0,0 +1,501 @@ +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.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) { + + public static final String SCHEMA = "account-draft-authorization-fence/v1"; + + public DraftAuthorizationFenceBinding { + 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"); + } + } + + /** Reconstructs only the exact existing immutable V57 framing; this grants no authorization. */ + public static DraftAuthorizationFenceBinding fromStored(byte[] original) { + byte[] stored = bytes(original); + FrameReader reader = new FrameReader(stored); + reader.expect(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())); + } + reader.expect("GAME_DESIGN"); + reader.expect("WORLD"); + reader.requireEnd(); + + DraftAuthorizationFenceBinding binding = + new DraftAuthorizationFenceBinding( + operationId, + requestId, + commitId, + fenceId, + actorAccountId, + tenantId, + versionId, + baseCommitId, + expectedDraftEpoch, + gameDesignBinding, + normalizedInput, + inputDigest, + sources); + 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 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, SCHEMA); + 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()); + } + frame(output, "GAME_DESIGN"); + frame(output, "WORLD"); + return output.toByteArray(); + } + + public enum SourceKind { + ISSUER, + ACCOUNT, + TENANT, + MEMBERSHIP, + GLOBAL_ROLES, + CREATOR_PARTY, + HOSTED_TERMS + } + + /** + * Independent owner counters/checkpoints and exact existing source evidence; no inferred epochs. + */ + public record SourceEvidence( + SourceKind kind, + String scopeId, + String generation, + String sourceVersion, + String checkpointStream, + String checkpointSequence, + byte[] evidence) { + public SourceEvidence { + Objects.requireNonNull(kind); + text(scopeId); + // Preserve the exact configured issuer, including its supported 512-character Unicode + // identity. Bound the complete index key in bytes rather than truncating or aliasing it. + if ((kind.name() + ":" + scopeId).getBytes(StandardCharsets.UTF_8).length > 2048) { + throw new IllegalArgumentException("Source participation key exceeds 2048 UTF-8 bytes"); + } + if (kind == SourceKind.ACCOUNT + || kind == SourceKind.TENANT + || kind == SourceKind.GLOBAL_ROLES) { + canonicalUuid(scopeId); + } + if (kind == SourceKind.MEMBERSHIP) { + String[] pair = scopeId.split("/", -1); + if (pair.length != 2) { + throw new IllegalArgumentException("Canonical membership pair required"); + } + canonicalUuid(pair[0]); + canonicalUuid(pair[1]); + } + if (generation != null) { + decimal(generation, false); + } + decimal(sourceVersion, false); + if ((checkpointStream == null) != (checkpointSequence == null)) { + throw new IllegalArgumentException("Checkpoint fields must be applicable together"); + } + if (checkpointStream != null) { + text(checkpointStream); + decimal(checkpointSequence, true); + } + evidence = bytes(evidence); + } + + @Override + public byte[] evidence() { + return evidence.clone(); + } + + public String key() { + return kind.name() + ":" + scopeId; + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : List.of("account-draft-source-evidence/v1", kind.name(), scopeId)) { + frame(output, value); + } + frame(output, generation == null ? "ABSENT" : "PRESENT"); + if (generation != null) { + frame(output, generation); + } + frame(output, sourceVersion); + frame(output, checkpointStream == null ? "ABSENT" : "PRESENT"); + if (checkpointStream != null) { + frame(output, checkpointStream); + frame(output, checkpointSequence); + } + frame(output, evidence); + return output.toByteArray(); + } + + /** Decodes only the exact immutable framing written by this source owner. */ + public static SourceEvidence fromStored(byte[] stored) { + FrameReader reader = new FrameReader(stored); + reader.expect("account-draft-source-evidence/v1"); + SourceKind kind = SourceKind.valueOf(reader.text()); + String scope = reader.text(); + String generation = reader.optionalText(); + String version = reader.text(); + String stream = reader.optionalText(); + String sequence = stream == null ? null : reader.text(); + SourceEvidence source = + new SourceEvidence(kind, scope, generation, version, stream, sequence, reader.bytes()); + reader.requireEnd(); + if (!Arrays.equals(stored, source.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored source evidence"); + } + return source; + } + } + + /** Bounded exact frame decoding for persisted source evidence and source-change intent. */ + public static final class FrameReader { + private final ByteBuffer input; + + public FrameReader(byte[] stored) { + input = ByteBuffer.wrap(DraftAuthorizationFenceBinding.bytes(stored)); + } + + public byte[] bytes() { + if (input.remaining() < Integer.BYTES) { + throw new IllegalArgumentException("Truncated immutable source frame"); + } + int size = input.getInt(); + if (size < 0 || size > input.remaining()) { + throw new IllegalArgumentException("Invalid immutable source frame size"); + } + byte[] value = new byte[size]; + input.get(value); + return value; + } + + public String text() { + byte[] value = bytes(); + String text = new String(value, StandardCharsets.UTF_8); + DraftAuthorizationFenceBinding.text(text); + if (!Arrays.equals(value, text.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Invalid UTF-8 source frame"); + } + return text; + } + + public String optionalText() { + String presence = text(); + if ("ABSENT".equals(presence)) { + return null; + } + if (!"PRESENT".equals(presence)) { + throw new IllegalArgumentException("Invalid immutable source presence"); + } + return text(); + } + + public void expect(String expected) { + if (!expected.equals(text())) { + throw new IllegalArgumentException("Unsupported immutable source schema"); + } + } + + public int remaining() { + return input.remaining(); + } + + public void requireEnd() { + if (input.hasRemaining()) { + throw new IllegalArgumentException("Trailing immutable source frames"); + } + } + } + + public enum Owner { + GAME_DESIGN, + WORLD + } + + public enum Outcome { + COMMITTED, + DEFINITIVELY_ABORTED + } + + /** 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); + reader.expect("account-draft-owner-readback/v1"); + 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(); + readback.requireBinding(DraftAuthorizationFenceBinding.fromStored(readback.fullBinding())); + 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"); + } + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : + List.of( + "account-draft-owner-readback/v1", + owner.name(), + outcome.name(), + operationId.toString(), + commitId.toString(), + fenceId.toString(), + inputDigest)) { + frame(output, value); + } + frame(output, fullBinding); + frame(output, result); + return output.toByteArray(); + } + } + + 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/WorldDraftTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java new file mode 100644 index 0000000000..21aac2639d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java @@ -0,0 +1,99 @@ +package net.firedevops.firemud.common.authoring; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; + +/** + * Validated World terminal-read value; peer authentication is supplied only by transport guards. + */ +public record WorldDraftTerminalReadEvidence( + Request request, Optional ownerReadback) { + public WorldDraftTerminalReadEvidence { + Objects.requireNonNull(request, "request"); + ownerReadback = Objects.requireNonNull(ownerReadback, "ownerReadback"); + ownerReadback.ifPresent( + value -> { + if (value.owner() != DraftAuthorizationFenceBinding.Owner.WORLD + || (value.outcome() != DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED + && value.outcome() != DraftAuthorizationFenceBinding.Outcome.COMMITTED)) { + throw new IllegalArgumentException("World readback must be an exact terminal outcome"); + } + DraftAuthorizationFenceBinding binding = request.accountBinding(); + value.requireBinding(binding); + if (!Arrays.equals(value.fullBinding(), request.originalAccountBinding())) { + throw new IllegalArgumentException("World readback differs from the original binding"); + } + if (value.outcome() == DraftAuthorizationFenceBinding.Outcome.COMMITTED) { + WorldDraftTerminalReadGrpcCodec.requireCommittedResult(request, value); + } + }); + } + + /** The canonical original Account binding and a separate caller-owned fresh read identity. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + byte[] originalAccountBinding) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World terminal read schema version"); + } + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + requireNonNil(readRequestId, "readRequestId"); + if (originalAccountBinding == null || originalAccountBinding.length == 0) { + throw new IllegalArgumentException("Complete original Account binding is required"); + } + originalAccountBinding = originalAccountBinding.clone(); + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.requestId()) + || readRequestId.equals(binding.commitId()) + || readRequestId.equals(binding.fenceId())) { + throw new IllegalArgumentException("World terminal read requires a fresh request identity"); + } + } + + public static Request create(String targetNamespace, byte[] originalAccountBinding) { + return new Request( + SCHEMA_VERSION, targetNamespace, UUID.randomUUID(), originalAccountBinding); + } + + @Override + public byte[] originalAccountBinding() { + return originalAccountBinding.clone(); + } + + public DraftAuthorizationFenceBinding accountBinding() { + return DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && readRequestId.equals(that.readRequestId) + && Arrays.equals(originalAccountBinding, that.originalAccountBinding); + } + + @Override + public int hashCode() { + int result = Objects.hash(schemaVersion, targetNamespace, readRequestId); + return 31 * result + Arrays.hashCode(originalAccountBinding); + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException("Non-nil " + label + " is required"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..a826e79d17 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java @@ -0,0 +1,736 @@ +package net.firedevops.firemud.common.authoring; + +import com.google.protobuf.Message; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadStatus; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Closed request mapping and exact echo/outcome validation for authenticated World readback. */ +public final class WorldDraftTerminalReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String APPLIED_V1 = "world-draft-graph-applied/v1"; + private static final String APPLIED_V2 = "world-draft-graph-applied/v2"; + private static final java.util.List FRESH_GRAPH_FAMILIES = + java.util.List.of( + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", + "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", + "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", + "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING"); + private static final Set APPLIED_V1_FIELDS = + Set.of( + "schema", + "status", + "operationBytesBase64", + "graphBytesBase64", + "graphDigest", + "appliedEpochs"); + private static final Set APPLIED_V2_FIELDS = + Set.of( + "schema", + "status", + "operationBytesBase64", + "graphBytesBase64", + "graphDigest", + "startLocationReceiptBase64", + "startLocationReceiptDigest", + "appliedEpochs"); + private static final Set FRESH_GRAPH_DECLARATION_FIELDS = + Set.of("tenantId", "versionId", "startLocation", "familyCounts"); + private static final Set ROOM_TEMPLATE_REF_FIELDS = + Set.of("tenantId", "versionId", "roomTemplateId"); + private static final Set FAMILY_COUNT_FIELDS = Set.of("family", "count"); + private static final Set GRAPH_ROW_FIELDS = Set.of("mapping", "content"); + private static final Set GRAPH_MAPPING_FIELDS = + Set.of( + "id", + "target_namespace", + "canonical_tenant_id", + "canonical_version_id", + "family", + "template_id", + "private_row_key", + "tenant_id", + "version_id", + "version_identity_operation_id", + "request_id", + "commit_id", + "revision_id", + "revision_order"); + private static final Set WORLD_MUTATION_FIELDS = + Set.of( + "logicalRevisionId", + "commitId", + "operation", + "aggregateType", + "aggregateId", + "expectedDraftRevisionEpoch", + "scopeType", + "scopeId", + "expectedDraftScopeRevisionEpoch", + "scopeMutationPolicy", + "freshGraphDeclaration", + "region", + "zone", + "room", + "roomExit", + "generationRule", + "worldEntitySpawnBinding", + "worldGenerationSubtree"); + private static final tools.jackson.databind.ObjectMapper JSON = + JsonMapper.builder() + .enable(tools.jackson.core.StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(tools.jackson.databind.DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private WorldDraftTerminalReadGrpcCodec() {} + + public static ReadWorldDraftTerminalOutcomeRequest toRequest( + WorldDraftTerminalReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadWorldDraftTerminalOutcomeRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(request.originalAccountBinding())) + .build(); + } + + /** Decodes only after the receiver has authenticated its exact same-namespace Account peer. */ + public static WorldDraftTerminalReadEvidence.Request fromRequest( + ReadWorldDraftTerminalOutcomeRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadWorldDraftTerminalOutcomeRequest"); + try { + return new WorldDraftTerminalReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + request.getOriginalAccountBinding().toByteArray()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("World terminal read request is invalid", exception); + } + } + + /** Emits only UNKNOWN or exact canonical World committed/definitive-abort readback. */ + public static ReadWorldDraftTerminalOutcomeResponse toResponse( + WorldDraftTerminalReadEvidence.Request request, + Optional ownerReadback) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(ownerReadback, "ownerReadback"); + var builder = + ReadWorldDraftTerminalOutcomeResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(request.originalAccountBinding())); + if (ownerReadback.isEmpty()) { + return builder + .setStatus(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN) + .build(); + } + var readback = ownerReadback.orElseThrow(); + requireExactOwnerReadback(request, readback); + return builder + .setStatus( + readback.outcome() == Outcome.COMMITTED + ? WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED + : WorldDraftTerminalReadStatus + .WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED) + .setOwnerReadbackBytes(com.google.protobuf.ByteString.copyFrom(readback.canonicalBytes())) + .build(); + } + + /** Validates the complete echo and independently framed World owner result. */ + public static WorldDraftTerminalReadEvidence fromResponse( + WorldDraftTerminalReadEvidence.Request request, + ReadWorldDraftTerminalOutcomeResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadWorldDraftTerminalOutcomeResponse"); + if (response.getSchemaVersion() != request.schemaVersion() + || !response.getTargetNamespace().equals(request.targetNamespace()) + || !response.getReadRequestId().equals(request.readRequestId().toString()) + || !Arrays.equals( + response.getOriginalAccountBinding().toByteArray(), request.originalAccountBinding())) { + throw new IllegalArgumentException("World terminal response changed the exact read request"); + } + Optional readback; + switch (response.getStatus()) { + case WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN -> { + if (!response.getOwnerReadbackBytes().isEmpty()) { + throw new IllegalArgumentException("UNKNOWN World readback cannot carry a result"); + } + readback = Optional.empty(); + } + case WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED, + WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED -> { + if (response.getOwnerReadbackBytes().isEmpty()) { + throw new IllegalArgumentException("World terminal readback bytes are required"); + } + var decoded = + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + response.getOwnerReadbackBytes().toByteArray()); + requireExactOwnerReadback(request, decoded); + Outcome expected = + response.getStatus() + == WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED + ? Outcome.COMMITTED + : Outcome.DEFINITIVELY_ABORTED; + if (decoded.outcome() != expected) { + throw new IllegalArgumentException( + "World terminal status differs from canonical owner outcome"); + } + readback = Optional.of(decoded); + } + case WORLD_DRAFT_TERMINAL_READ_STATUS_UNSPECIFIED, UNRECOGNIZED -> + throw new IllegalArgumentException("Unsupported World terminal read status"); + default -> throw new IllegalArgumentException("Unsupported World terminal read status"); + } + return new WorldDraftTerminalReadEvidence(request, readback); + } + + private static void requireExactOwnerReadback( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback readback) { + DraftAuthorizationFenceBinding binding = request.accountBinding(); + if (readback.owner() != Owner.WORLD + || (readback.outcome() != Outcome.DEFINITIVELY_ABORTED + && readback.outcome() != Outcome.COMMITTED)) { + throw new IllegalArgumentException( + "World terminal response is not an exact World terminal outcome"); + } + readback.requireBinding(binding); + if (!readback.operationId().equals(binding.operationId()) + || !readback.commitId().equals(binding.commitId()) + || !readback.fenceId().equals(binding.fenceId()) + || !readback.inputDigest().equals(binding.inputDigest()) + || !Arrays.equals(readback.fullBinding(), request.originalAccountBinding()) + || readback.result().length == 0) { + throw new IllegalArgumentException( + "World terminal response differs from the complete original Account binding"); + } + if (readback.outcome() == Outcome.COMMITTED) requireCommittedResult(request, readback); + } + + /** + * Checks this World carrier only; mutation/source semantics remain at the authenticated owner. + */ + static void requireCommittedResult( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback readback) { + try { + byte[] bytes = readback.result(); + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(json))) + throw new IllegalArgumentException("Noncanonical World APPLIED result"); + JsonNode result = JSON.readTree(bytes); + String schema = text(result, "schema"); + boolean v2 = APPLIED_V2.equals(schema); + if (!v2 && !APPLIED_V1.equals(schema)) { + throw new IllegalArgumentException("Unsupported World APPLIED result schema"); + } + fields(result, v2 ? APPLIED_V2_FIELDS : APPLIED_V1_FIELDS); + exactText(result, "status", "APPLIED"); + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), + account.inputDigest()); + if (!Arrays.equals(draft.canonicalBytes(), account.normalizedInput()) + || !draft.requestId().equals(account.requestId()) + || !draft.commitId().equals(account.commitId()) + || !draft.target().canonicalTenantId().equals(account.tenantId()) + || !draft.target().canonicalVersionId().equals(account.versionId())) { + throw new IllegalArgumentException("World applied input differs from original binding"); + } + OriginalFreshGraph originalGraph = readOriginalFreshGraph(draft, v2); + if (v2 != (originalGraph != null)) { + throw new IllegalArgumentException( + "World APPLIED schema does not match the original fresh graph declaration"); + } + FrameReader operation = new FrameReader(base64(result, "operationBytesBase64")); + operation.expect("world-draft-terminal-operation/v1"); + for (UUID id : + java.util.List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) operation.expect(id.toString()); + operation.expectBytes(draft.canonicalBytes()); + operation.expect(request.targetNamespace()); + operation.expect(account.tenantId().toString()); + operation.expect(account.versionId().toString()); + UUID versionIdentityOperationId = operation.canonicalUuid(); + operation.expect(Long.toString(draft.target().gameDesignVersionRowId())); + operation.canonicalUuid(); // Intake request + operation.canonicalUuid(); // Intake operation + operation.digest(); // Intake request digest + operation.canonicalUuid(); // Source operation + operation.digest(); // Source evidence digest + operation.digest(); // Intake receipt digest + operation.expect(sha256(request.originalAccountBinding())); + operation.expectBytes(request.originalAccountBinding()); + operation.requireEnd(); + byte[] graph = base64(result, "graphBytesBase64"); + if (v2) { + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(graph)); + } + String graphDigest = sha256(graph); + exactText(result, "graphDigest", graphDigest); + JsonNode graphValue = JSON.readTree(graph); + fields( + graphValue, Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows")); + exactText(graphValue, "schemaVersion", "2"); + exactText(graphValue, "canonicalTenantId", account.tenantId().toString()); + exactText(graphValue, "canonicalVersionId", account.versionId().toString()); + if (!graphValue.get("rows").isArray() || graphValue.get("rows").isEmpty()) + throw new IllegalArgumentException("World applied graph is absent"); + if (v2) { + validateDeclaredGraphRows( + graphValue.get("rows"), + originalGraph, + request.targetNamespace(), + account, + versionIdentityOperationId); + validateStartLocationReceipt(result, graphDigest, originalGraph, request, draft, account); + } + var expected = draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT); + JsonNode epochs = result.get("appliedEpochs"); + if (!epochs.isArray() || expected.isEmpty() || epochs.size() != expected.size()) + throw new IllegalArgumentException("World applied epoch vector is incomplete"); + for (int i = 0; i < expected.size(); i++) { + var unit = expected.get(i); + JsonNode epoch = epochs.get(i); + fields( + epoch, + Set.of( + "aggregateType", + "aggregateId", + "scopeType", + "scopeId", + "expectedEpoch", + "resultingEpoch")); + exactText(epoch, "aggregateType", unit.aggregateType()); + exactText(epoch, "aggregateId", unit.aggregateId()); + exactText(epoch, "scopeType", unit.scopeType()); + exactText(epoch, "scopeId", unit.scopeId()); + exactText(epoch, "expectedEpoch", unit.expectedEpoch()); + exactText( + epoch, + "resultingEpoch", + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString()); + } + } catch (java.io.IOException | NoSuchAlgorithmException | RuntimeException invalid) { + throw new IllegalArgumentException( + "World committed readback has an invalid or substituted canonical APPLIED result", + invalid); + } + } + + private static OriginalFreshGraph readOriginalFreshGraph( + DraftCommitBinding draft, boolean requireCompleteDeclaration) throws java.io.IOException { + Map nodes = new LinkedHashMap<>(); + JsonNode declaration = null; + for (DraftCommitBinding.RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + JsonNode mutation; + try { + mutation = JSON.readTree(revision.payload()); + } catch (RuntimeException invalidPayload) { + if (requireCompleteDeclaration) throw invalidPayload; + // Retained v1 payloads predate a common JSON shape; they cannot declare a new typed + // selector. + continue; + } + if (mutation == null || !mutation.isObject()) { + if (requireCompleteDeclaration) { + throw new IllegalArgumentException("Original World mutation payload is not an object"); + } + continue; + } + JsonNode graphDeclaration = mutation.get("freshGraphDeclaration"); + if (!requireCompleteDeclaration) { + if (graphDeclaration != null) { + throw new IllegalArgumentException( + "Historical World APPLIED v1 cannot downgrade a declared fresh graph"); + } + continue; + } + fieldsKnown(mutation, WORLD_MUTATION_FIELDS); + exactText(mutation, "logicalRevisionId", revision.revisionId().toString()); + exactText(mutation, "commitId", draft.commitId().toString()); + String family = text(mutation, "aggregateType"); + if (!FRESH_GRAPH_FAMILIES.contains(family)) { + throw new IllegalArgumentException("Unsupported family in declared World graph input"); + } + UUID templateId = parseCanonicalNonNilUuid(text(mutation, "aggregateId"), "aggregateId"); + String key = family + ":" + templateId; + if (nodes.putIfAbsent( + key, + new OriginalGraphNode( + family, templateId, revision.revisionId(), revision.revisionOrder())) + != null) { + throw new IllegalArgumentException("Original declared World graph repeats a template"); + } + if (graphDeclaration != null) { + if (declaration != null) { + throw new IllegalArgumentException( + "Original World input has multiple graph declarations"); + } + declaration = graphDeclaration; + } + } + if (!requireCompleteDeclaration) return null; + if (declaration == null || nodes.isEmpty()) { + throw new IllegalArgumentException( + "World v2 requires an original complete graph declaration"); + } + return parseOriginalFreshGraph(declaration, nodes, draft); + } + + private static OriginalFreshGraph parseOriginalFreshGraph( + JsonNode declaration, Map nodes, DraftCommitBinding draft) { + fields(declaration, FRESH_GRAPH_DECLARATION_FIELDS); + UUID tenantId = parseCanonicalNonNilUuid(text(declaration, "tenantId"), "declaration tenantId"); + UUID versionId = + parseCanonicalNonNilUuid(text(declaration, "versionId"), "declaration versionId"); + if (!tenantId.equals(draft.target().canonicalTenantId()) + || !versionId.equals(draft.target().canonicalVersionId())) { + throw new IllegalArgumentException("Original World graph declaration has another scope"); + } + JsonNode selector = declaration.get("startLocation"); + fields(selector, ROOM_TEMPLATE_REF_FIELDS); + UUID selectorTenant = + parseCanonicalNonNilUuid(text(selector, "tenantId"), "start selector tenantId"); + UUID selectorVersion = + parseCanonicalNonNilUuid(text(selector, "versionId"), "start selector versionId"); + UUID roomTemplateId = + parseCanonicalNonNilUuid(text(selector, "roomTemplateId"), "start selector roomTemplateId"); + if (!tenantId.equals(selectorTenant) || !versionId.equals(selectorVersion)) { + throw new IllegalArgumentException("Original World start selector has another scope"); + } + JsonNode counts = declaration.get("familyCounts"); + if (counts == null || !counts.isArray() || counts.size() != FRESH_GRAPH_FAMILIES.size()) { + throw new IllegalArgumentException("Original World graph declaration is incomplete"); + } + for (int i = 0; i < FRESH_GRAPH_FAMILIES.size(); i++) { + JsonNode entry = counts.get(i); + fields(entry, FAMILY_COUNT_FIELDS); + String family = text(entry, "family"); + JsonNode countNode = entry.get("count"); + if (!FRESH_GRAPH_FAMILIES.get(i).equals(family) + || countNode == null + || !countNode.isIntegralNumber() + || !countNode.canConvertToInt() + || countNode.intValue() < 0) { + throw new IllegalArgumentException( + "Original World graph family counts must be present, ordered and nonnegative"); + } + int actualCount = + (int) nodes.values().stream().filter(node -> node.family().equals(family)).count(); + if (actualCount != countNode.intValue()) { + throw new IllegalArgumentException( + "Original World graph family count differs from its complete typed input"); + } + } + OriginalGraphNode selectedRoom = + nodes.get("WORLD_DESIGN_AGGREGATE_TYPE_ROOM:" + roomTemplateId); + if (selectedRoom == null) { + throw new IllegalArgumentException( + "Original World start selector is absent from its ROOM graph"); + } + return new OriginalFreshGraph( + tenantId, + versionId, + roomTemplateId, + selectedRoom, + Map.copyOf(nodes), + List.copyOf(nodes.values())); + } + + private static void validateDeclaredGraphRows( + JsonNode rows, + OriginalFreshGraph original, + String targetNamespace, + DraftAuthorizationFenceBinding binding, + UUID versionIdentityOperationId) { + if (rows.size() != original.nodes().size()) { + throw new IllegalArgumentException( + "World v2 graph rows differ from the complete original input"); + } + Set seenNodes = new HashSet<>(); + Set seenMappingIds = new HashSet<>(); + Set seenPrivateRowKeys = new HashSet<>(); + Long privateTenantId = null; + Long privateVersionId = null; + boolean selectedRoomFound = false; + int rowIndex = 0; + for (JsonNode row : rows) { + fields(row, GRAPH_ROW_FIELDS); + JsonNode mapping = row.get("mapping"); + fields(mapping, GRAPH_MAPPING_FIELDS); + if (row.get("content") == null || !row.get("content").isObject()) { + throw new IllegalArgumentException("World v2 graph row content is absent"); + } + exactText(mapping, "target_namespace", targetNamespace); + exactText(mapping, "canonical_tenant_id", binding.tenantId().toString()); + exactText(mapping, "canonical_version_id", binding.versionId().toString()); + exactText(mapping, "request_id", binding.requestId().toString()); + exactText(mapping, "commit_id", binding.commitId().toString()); + String family = text(mapping, "family"); + if (!FRESH_GRAPH_FAMILIES.contains("WORLD_DESIGN_AGGREGATE_TYPE_" + family)) { + throw new IllegalArgumentException("World v2 graph row has an unsupported family"); + } + UUID templateId = parseCanonicalNonNilUuid(text(mapping, "template_id"), "graph template_id"); + String nodeKey = "WORLD_DESIGN_AGGREGATE_TYPE_" + family + ":" + templateId; + OriginalGraphNode originalNode = original.nodes().get(nodeKey); + if (originalNode == null + || !original.orderedNodes().get(rowIndex).equals(originalNode) + || !seenNodes.add(nodeKey) + || !originalNode.revisionId().toString().equals(text(mapping, "revision_id")) + || !originalNode.revisionOrder().equals(text(mapping, "revision_order"))) { + throw new IllegalArgumentException( + "World v2 graph row differs from its exact original revision"); + } + UUID graphVersionIdentityOperationId = + parseCanonicalNonNilUuid( + text(mapping, "version_identity_operation_id"), "graph Version identity operation"); + if (!versionIdentityOperationId.equals(graphVersionIdentityOperationId)) { + throw new IllegalArgumentException( + "World v2 graph uses another Version identity operation"); + } + long mappingId = positiveLong(mapping, "id"); + long tenantId = positiveLong(mapping, "tenant_id"); + long versionId = positiveLong(mapping, "version_id"); + long privateRowKey = positiveLong(mapping, "private_row_key"); + if (privateTenantId == null) { + privateTenantId = tenantId; + privateVersionId = versionId; + } else if (privateTenantId != tenantId || privateVersionId != versionId) { + throw new IllegalArgumentException( + "World v2 graph rows cross private tenant or Version scope"); + } + if (!seenMappingIds.add(mappingId) || !seenPrivateRowKeys.add(family + ":" + privateRowKey)) { + throw new IllegalArgumentException("World v2 graph contains a repeated private mapping"); + } + if (originalNode.equals(original.selectedRoom()) + && "ROOM".equals(family) + && templateId.equals(original.roomTemplateId())) { + selectedRoomFound = true; + } + rowIndex++; + } + if (!selectedRoomFound || seenNodes.size() != original.nodes().size()) { + throw new IllegalArgumentException("World v2 graph omits the exact selected ROOM row"); + } + } + + private static void validateStartLocationReceipt( + JsonNode result, + String graphDigest, + OriginalFreshGraph original, + WorldDraftTerminalReadEvidence.Request request, + DraftCommitBinding draft, + DraftAuthorizationFenceBinding binding) + throws NoSuchAlgorithmException { + var receipt = + WorldDraftStartLocationEvidence.fromStored(base64(result, "startLocationReceiptBase64")); + if (!receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.operationId().equals(binding.operationId()) + || !receipt.requestId().equals(binding.requestId()) + || !receipt.commitId().equals(binding.commitId()) + || !receipt.authorizationFenceId().equals(binding.fenceId()) + || !receipt.accountBindingDigest().equals(sha256(request.originalAccountBinding())) + || !receipt.bindingDigest().equals(draft.digest()) + || !receipt.startLocation().tenantId().equals(original.tenantId()) + || !receipt.startLocation().versionId().equals(original.versionId()) + || !receipt.startLocation().roomTemplateId().equals(original.roomTemplateId()) + || !receipt.graphDigest().equals(graphDigest)) { + throw new IllegalArgumentException( + "World start-location receipt differs from its original Account-bound graph"); + } + exactText(result, "startLocationReceiptDigest", receipt.receiptDigest()); + } + + private static long positiveLong(JsonNode value, String field) { + JsonNode actual = value.get(field); + if (actual == null + || !actual.isIntegralNumber() + || !actual.canConvertToLong() + || actual.longValue() <= 0) { + throw new IllegalArgumentException("World graph requires positive private mapping " + field); + } + return actual.longValue(); + } + + private static String text(JsonNode value, String field) { + JsonNode actual = value == null ? null : value.get(field); + if (actual == null || !actual.isTextual()) { + throw new IllegalArgumentException("World APPLIED carrier requires text " + field); + } + return actual.textValue(); + } + + private static void fieldsKnown(JsonNode value, Set fields) { + if (value == null + || !value.isObject() + || value.properties().stream().anyMatch(entry -> !fields.contains(entry.getKey()))) { + throw new IllegalArgumentException("Original World mutation has unsupported fields"); + } + } + + private record OriginalGraphNode( + String family, UUID templateId, UUID revisionId, String revisionOrder) {} + + private record OriginalFreshGraph( + UUID tenantId, + UUID versionId, + UUID roomTemplateId, + OriginalGraphNode selectedRoom, + Map nodes, + List orderedNodes) {} + + private static void fields(JsonNode value, Set fields) { + if (value == null + || !value.isObject() + || value.size() != fields.size() + || value.properties().stream().anyMatch(entry -> !fields.contains(entry.getKey()))) + throw new IllegalArgumentException("World APPLIED carrier fields differ"); + } + + private static void exactText(JsonNode value, String field, String expected) { + if (value.get(field) == null + || !value.get(field).isTextual() + || !expected.equals(value.get(field).textValue())) + throw new IllegalArgumentException("World APPLIED carrier differs at " + field); + } + + private static String sha256(byte[] value) throws NoSuchAlgorithmException { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static byte[] base64(JsonNode value, String field) { + if (value.get(field) == null || !value.get(field).isTextual()) + throw new IllegalArgumentException("World APPLIED bytes missing"); + String encoded = value.get(field).textValue(); + byte[] decoded = Base64.getDecoder().decode(encoded); + if (decoded.length == 0 || !Base64.getEncoder().encodeToString(decoded).equals(encoded)) + throw new IllegalArgumentException("Noncanonical World APPLIED Base64"); + return decoded; + } + + private static final class FrameReader { + private final ByteBuffer bytes; + + private FrameReader(byte[] value) { + bytes = ByteBuffer.wrap(value); + } + + private byte[] frame() { + if (bytes.remaining() < Integer.BYTES) + throw new IllegalArgumentException("Truncated World operation"); + int size = bytes.getInt(); + if (size <= 0 || size > bytes.remaining()) + throw new IllegalArgumentException("Invalid World operation frame"); + byte[] value = new byte[size]; + bytes.get(value); + return value; + } + + private String text() { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(frame())) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException("Invalid World operation UTF-8", invalid); + } + } + + private void expect(String expected) { + if (!expected.equals(text())) + throw new IllegalArgumentException("Substituted World operation"); + } + + private void expectBytes(byte[] expected) { + if (!Arrays.equals(expected, frame())) + throw new IllegalArgumentException("Substituted World operation bytes"); + } + + private UUID canonicalUuid() { + return parseCanonicalNonNilUuid(text(), "World owner identity"); + } + + private void digest() { + if (!text().matches("(?:sha256:)?[0-9a-f]{64}")) + throw new IllegalArgumentException("Invalid World owner digest"); + } + + private void requireEnd() { + if (bytes.hasRemaining()) + throw new IllegalArgumentException("Trailing World operation bytes"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required", exception); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java new file mode 100644 index 0000000000..5a6be36581 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java @@ -0,0 +1,568 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** Closed immutable launch binding evidence for an exact Game Design authored-world source. */ +public record AuthoredWorldLaunchDescriptorEvidence( + int schemaVersion, + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + long gameTemplateId, + boolean requestedScriptPatchVersionPresent, + String requestedScriptPatchVersion, + boolean sourceVersionIdPresent, + Long sourceVersionId, + boolean targetVersionIdPresent, + Long targetVersionId, + boolean requestedRuntimeFlagsJsonPresent, + String requestedRuntimeFlagsJson, + String requestDigest, + String launchDescriptorId, + long versionId, + boolean scriptPatchVersionPresent, + String scriptPatchVersion, + String runtimeFlagsJson, + String generationConfigRevision, + long versionStateEpoch, + long releaseBundleId, + String publishedReleaseBundleRef, + boolean remapSetIdPresent, + String remapSetId, + String resultDigest) { + public static final int SCHEMA_VERSION = 1; + private static final String REQUEST_DOMAIN = + "game-design-authored-world-launch-descriptor-request/v1"; + private static final String RESULT_DOMAIN = + "game-design-authored-world-launch-descriptor-result/v1"; + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private record Field(String name, String value) {} + + /** The exact request values, including presence for every optional field. */ + public record Request( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + long gameTemplateId, + boolean requestedScriptPatchVersionPresent, + String requestedScriptPatchVersion, + boolean sourceVersionIdPresent, + Long sourceVersionId, + boolean targetVersionIdPresent, + Long targetVersionId, + boolean requestedRuntimeFlagsJsonPresent, + String requestedRuntimeFlagsJson) { + public Request { + validateRequest( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + } + + public String requestDigest() { + return AuthoredWorldLaunchDescriptorEvidence.requestDigest(this); + } + } + + public AuthoredWorldLaunchDescriptorEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world launch descriptor schema"); + } + Request request = + new Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + requireOptional(scriptPatchVersionPresent, scriptPatchVersion, "scriptPatchVersion"); + requireOptional(remapSetIdPresent, remapSetId, "remapSetId"); + requireText(launchDescriptorId, "launchDescriptorId"); + requirePositive(versionId, "versionId"); + requireText(runtimeFlagsJson, "runtimeFlagsJson"); + requireText(generationConfigRevision, "generationConfigRevision"); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + requirePositive(releaseBundleId, "releaseBundleId"); + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef"); + requireDigest(requestDigest, "requestDigest"); + if (!request.requestDigest().equals(requestDigest)) { + throw new IllegalArgumentException("Request digest does not match the exact request tuple"); + } + requireDigest(resultDigest, "resultDigest"); + } + + /** Recomputes both closed digests after construction or deserialization. */ + public void requireValid() { + if (!requestDigest(this.request()).equals(requestDigest) + || !resultDigest(this).equals(resultDigest)) { + throw new IllegalArgumentException("Result digest does not match the immutable descriptor"); + } + } + + public Request request() { + return new Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + } + + public static AuthoredWorldLaunchDescriptorEvidence create( + Request request, + String launchDescriptorId, + long versionId, + boolean scriptPatchVersionPresent, + String scriptPatchVersion, + String runtimeFlagsJson, + String generationConfigRevision, + long versionStateEpoch, + long releaseBundleId, + String publishedReleaseBundleRef, + boolean remapSetIdPresent, + String remapSetId) { + Objects.requireNonNull(request, "request"); + AuthoredWorldLaunchDescriptorEvidence provisional = + new AuthoredWorldLaunchDescriptorEvidence( + SCHEMA_VERSION, + request.targetNamespace(), + request.controlPlaneRequestId(), + request.canonicalTenantId(), + request.worldSlug(), + request.authoredWorldSourceOperationId(), + request.authoredWorldSourceEvidenceDigest(), + request.gameTemplateId(), + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion(), + request.sourceVersionIdPresent(), + request.sourceVersionId(), + request.targetVersionIdPresent(), + request.targetVersionId(), + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson(), + request.requestDigest(), + launchDescriptorId, + versionId, + scriptPatchVersionPresent, + scriptPatchVersion, + runtimeFlagsJson, + generationConfigRevision, + versionStateEpoch, + releaseBundleId, + publishedReleaseBundleRef, + remapSetIdPresent, + remapSetId, + "sha256:" + "0".repeat(64)); + AuthoredWorldLaunchDescriptorEvidence evidence = + new AuthoredWorldLaunchDescriptorEvidence( + provisional.schemaVersion(), + provisional.targetNamespace(), + provisional.controlPlaneRequestId(), + provisional.canonicalTenantId(), + provisional.worldSlug(), + provisional.authoredWorldSourceOperationId(), + provisional.authoredWorldSourceEvidenceDigest(), + provisional.gameTemplateId(), + provisional.requestedScriptPatchVersionPresent(), + provisional.requestedScriptPatchVersion(), + provisional.sourceVersionIdPresent(), + provisional.sourceVersionId(), + provisional.targetVersionIdPresent(), + provisional.targetVersionId(), + provisional.requestedRuntimeFlagsJsonPresent(), + provisional.requestedRuntimeFlagsJson(), + provisional.requestDigest(), + provisional.launchDescriptorId(), + provisional.versionId(), + provisional.scriptPatchVersionPresent(), + provisional.scriptPatchVersion(), + provisional.runtimeFlagsJson(), + provisional.generationConfigRevision(), + provisional.versionStateEpoch(), + provisional.releaseBundleId(), + provisional.publishedReleaseBundleRef(), + provisional.remapSetIdPresent(), + provisional.remapSetId(), + resultDigest(provisional)); + evidence.requireValid(); + return evidence; + } + + public static String requestDigest(Request request) { + Objects.requireNonNull(request, "request"); + return digest( + REQUEST_DOMAIN, + field("schemaVersion", Integer.toString(SCHEMA_VERSION)), + field("targetNamespace", request.targetNamespace()), + field("controlPlaneRequestId", request.controlPlaneRequestId()), + field("canonicalTenantId", request.canonicalTenantId().toString()), + field("worldSlug", request.worldSlug()), + field( + "authoredWorldSourceOperationId", request.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", request.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(request.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", request.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", request.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + request.sourceVersionIdPresent(), + decimal(request.sourceVersionId())), + optionalPresence("targetVersionId", request.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + request.targetVersionIdPresent(), + decimal(request.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", request.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson())); + } + + /** Computes the result digest while deliberately excluding only {@code resultDigest}. */ + public static String resultDigest(AuthoredWorldLaunchDescriptorEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return digest( + RESULT_DOMAIN, + field("schemaVersion", Integer.toString(evidence.schemaVersion())), + field("targetNamespace", evidence.targetNamespace()), + field("controlPlaneRequestId", evidence.controlPlaneRequestId()), + field("canonicalTenantId", evidence.canonicalTenantId().toString()), + field("worldSlug", evidence.worldSlug()), + field( + "authoredWorldSourceOperationId", evidence.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", evidence.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(evidence.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", evidence.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + evidence.requestedScriptPatchVersionPresent(), + evidence.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", evidence.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + evidence.sourceVersionIdPresent(), + decimal(evidence.sourceVersionId())), + optionalPresence("targetVersionId", evidence.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + evidence.targetVersionIdPresent(), + decimal(evidence.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", evidence.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + evidence.requestedRuntimeFlagsJsonPresent(), + evidence.requestedRuntimeFlagsJson()), + field("requestDigest", evidence.requestDigest()), + field("launchDescriptorId", evidence.launchDescriptorId()), + field("versionId", Long.toString(evidence.versionId())), + optionalPresence("scriptPatchVersion", evidence.scriptPatchVersionPresent()), + optionalValue( + "scriptPatchVersion", + evidence.scriptPatchVersionPresent(), + evidence.scriptPatchVersion()), + field("runtimeFlagsJson", evidence.runtimeFlagsJson()), + field("generationConfigRevision", evidence.generationConfigRevision()), + field("versionStateEpoch", Long.toString(evidence.versionStateEpoch())), + field("releaseBundleId", Long.toString(evidence.releaseBundleId())), + field("publishedReleaseBundleRef", evidence.publishedReleaseBundleRef()), + optionalPresence("remapSetId", evidence.remapSetIdPresent()), + optionalValue("remapSetId", evidence.remapSetIdPresent(), evidence.remapSetId())); + } + + /** Returns the exact UTF-8 request preimage for shared producer and consumer proof. */ + public static byte[] requestPreimage(Request request) { + return preimage( + REQUEST_DOMAIN, + field("schemaVersion", Integer.toString(SCHEMA_VERSION)), + field("targetNamespace", request.targetNamespace()), + field("controlPlaneRequestId", request.controlPlaneRequestId()), + field("canonicalTenantId", request.canonicalTenantId().toString()), + field("worldSlug", request.worldSlug()), + field( + "authoredWorldSourceOperationId", request.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", request.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(request.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", request.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", request.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + request.sourceVersionIdPresent(), + decimal(request.sourceVersionId())), + optionalPresence("targetVersionId", request.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + request.targetVersionIdPresent(), + decimal(request.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", request.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson())); + } + + /** Returns the exact UTF-8 result preimage, excluding only the result digest itself. */ + public static byte[] resultPreimage(AuthoredWorldLaunchDescriptorEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return preimage( + RESULT_DOMAIN, + field("schemaVersion", Integer.toString(evidence.schemaVersion())), + field("targetNamespace", evidence.targetNamespace()), + field("controlPlaneRequestId", evidence.controlPlaneRequestId()), + field("canonicalTenantId", evidence.canonicalTenantId().toString()), + field("worldSlug", evidence.worldSlug()), + field( + "authoredWorldSourceOperationId", evidence.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", evidence.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(evidence.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", evidence.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + evidence.requestedScriptPatchVersionPresent(), + evidence.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", evidence.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + evidence.sourceVersionIdPresent(), + decimal(evidence.sourceVersionId())), + optionalPresence("targetVersionId", evidence.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + evidence.targetVersionIdPresent(), + decimal(evidence.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", evidence.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + evidence.requestedRuntimeFlagsJsonPresent(), + evidence.requestedRuntimeFlagsJson()), + field("requestDigest", evidence.requestDigest()), + field("launchDescriptorId", evidence.launchDescriptorId()), + field("versionId", Long.toString(evidence.versionId())), + optionalPresence("scriptPatchVersion", evidence.scriptPatchVersionPresent()), + optionalValue( + "scriptPatchVersion", + evidence.scriptPatchVersionPresent(), + evidence.scriptPatchVersion()), + field("runtimeFlagsJson", evidence.runtimeFlagsJson()), + field("generationConfigRevision", evidence.generationConfigRevision()), + field("versionStateEpoch", Long.toString(evidence.versionStateEpoch())), + field("releaseBundleId", Long.toString(evidence.releaseBundleId())), + field("publishedReleaseBundleRef", evidence.publishedReleaseBundleRef()), + optionalPresence("remapSetId", evidence.remapSetIdPresent()), + optionalValue("remapSetId", evidence.remapSetIdPresent(), evidence.remapSetId())); + } + + private static void validateRequest( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + long gameTemplateId, + boolean requestedPatchPresent, + String requestedPatch, + boolean sourceVersionPresent, + Long sourceVersion, + boolean targetVersionPresent, + Long targetVersion, + boolean runtimeFlagsPresent, + String runtimeFlags) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + if (controlPlaneRequestId.isBlank()) { + throw new IllegalArgumentException("controlPlaneRequestId is required"); + } + if (strictUtf8(controlPlaneRequestId).length > 64) { + throw new IllegalArgumentException("controlPlaneRequestId exceeds its stored byte bound"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(sourceOperationId, "authoredWorldSourceOperationId"); + requireDigest(sourceEvidenceDigest, "authoredWorldSourceEvidenceDigest"); + requirePositive(gameTemplateId, "gameTemplateId"); + requireOptional(requestedPatchPresent, requestedPatch, "requestedScriptPatchVersion"); + requireOptional(sourceVersionPresent, sourceVersion, "sourceVersionId"); + if (sourceVersionPresent) { + requirePositive(sourceVersion, "sourceVersionId"); + } + requireOptional(targetVersionPresent, targetVersion, "targetVersionId"); + if (targetVersionPresent) { + requirePositive(targetVersion, "targetVersionId"); + } + requireOptional(runtimeFlagsPresent, runtimeFlags, "requestedRuntimeFlagsJson"); + } + + private static Field optionalPresence(String name, boolean present) { + return field(name + ".present", Boolean.toString(present)); + } + + private static Field optionalValue(String name, boolean present, String value) { + return field(name + ".value", present ? Objects.requireNonNull(value, name) : ""); + } + + private static Field field(String name, String value) { + return new Field(name, value); + } + + private static String digest(String domain, Field... fields) { + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage(domain, fields))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static byte[] preimage(String domain, Field... fields) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + writeSegment(bytes, domain); + for (Field field : fields) { + writeSegment(bytes, field.name()); + writeSegment(bytes, field.value()); + } + return bytes.toByteArray(); + } + + private static void writeSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = strictUtf8(value); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must contain valid Unicode", exception); + } + } + + private static String decimal(Long value) { + return value == null ? "" : Long.toString(value); + } + + private static void requireOptional(boolean present, Object value, String name) { + if (present != (value != null)) { + throw new IllegalArgumentException(name + " presence does not match its value"); + } + if (value instanceof String text) { + strictUtf8(text); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requirePositive(Long value, String name) { + if (value == null || value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + strictUtf8(value); + } + + private static void requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a lowercase SHA-256 digest"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/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/tenant/AuthoredWorldSourceDigest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java new file mode 100644 index 0000000000..205007381c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceDigest.java @@ -0,0 +1,147 @@ +package net.firedevops.firemud.common.tenant; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Canonical request and receipt digests for Game Design authored-world source evidence. */ +public final class AuthoredWorldSourceDigest { + private static final String REQUEST_DOMAIN = "game-design-authored-world-source-request/v1"; + private static final String RECEIPT_DOMAIN = "game-design-authored-world-source-receipt/v1"; + private static final Pattern CANONICAL_SLUG = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AuthoredWorldSourceDigest() {} + + public static String requestDigest( + String targetNamespace, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + validateRequestTuple( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + return GameTenantCreationDigest.digest( + REQUEST_DOMAIN, + targetNamespace, + registrationRequestId.toString(), + canonicalTenantId.toString(), + tenantSlug, + worldSlug, + worldDisplayName); + } + + public static String evidenceDigest( + String targetNamespace, + UUID registrationRequestId, + UUID operationId, + String requestDigest, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + validateRequestTuple( + targetNamespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + requireNonNil(operationId, "operationId"); + if (!GameTenantCreationDigest.isDigest(requestDigest)) { + throw new IllegalArgumentException("requestDigest must be a lowercase SHA-256 digest"); + } + if (sourceGameRowId <= 0) { + throw new IllegalArgumentException("sourceGameRowId must be positive"); + } + validateSourceGameTenantKey(sourceGameTenantKey); + if (!"NEW_GAME_ROW".equals(provenanceKind) && !"RETAINED_GAME_V30".equals(provenanceKind)) { + throw new IllegalArgumentException("Authored-world source provenance kind is not recognized"); + } + return GameTenantCreationDigest.digest( + RECEIPT_DOMAIN, + targetNamespace, + registrationRequestId.toString(), + operationId.toString(), + requestDigest, + canonicalTenantId.toString(), + tenantSlug, + worldSlug, + worldDisplayName, + Long.toString(sourceGameRowId), + sourceGameTenantKey, + provenanceKind); + } + + public static void validateReadSelector( + String targetNamespace, UUID canonicalTenantId, String worldSlug) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + GameTenantCreationDigest.utf8ByteLength(targetNamespace); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + validateSlug(worldSlug, "worldSlug"); + } + + private static void validateRequestTuple( + String targetNamespace, + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + GameTenantCreationDigest.utf8ByteLength(targetNamespace); + requireNonNil(registrationRequestId, "registrationRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + validateSlug(tenantSlug, "tenantSlug"); + validateSlug(worldSlug, "worldSlug"); + validateDisplayName(worldDisplayName); + } + + private static void validateSlug(String value, String label) { + Objects.requireNonNull(value, label); + int byteLength = GameTenantCreationDigest.utf8ByteLength(value); + if (byteLength == 0 || byteLength > 120 || !CANONICAL_SLUG.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical routing selector"); + } + } + + private static void validateDisplayName(String value) { + Objects.requireNonNull(value, "worldDisplayName"); + if (value.isBlank() || value.length() > 200 || value.codePointCount(0, value.length()) > 100) { + throw new IllegalArgumentException( + "worldDisplayName must be nonblank and contain at most 100 Unicode code points"); + } + GameTenantCreationDigest.utf8ByteLength(value); + } + + private static void validateSourceGameTenantKey(String value) { + Objects.requireNonNull(value, "sourceGameTenantKey"); + if (value.isBlank() || value.length() > 72 || value.codePointCount(0, value.length()) > 36) { + throw new IllegalArgumentException("sourceGameTenantKey is outside the owner key bounds"); + } + GameTenantCreationDigest.utf8ByteLength(value); + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must not be nil"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/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/WorldCanonicalInstanceLifecycleEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java new file mode 100644 index 0000000000..62750d0aa0 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java @@ -0,0 +1,475 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Exact, non-admitting World lifecycle owner readback for an authenticated canonical caller. + * + *

Decoding this carrier does not authenticate World, establish current Account authority, or + * grant lifecycle activation or gameplay admission. The transport endpoint owns workload + * authentication; the consumer must keep admission and its current-authority checks separate. + */ +public record WorldCanonicalInstanceLifecycleEvidence( + Request request, + CompleteLaunchBindingEvidence launchBinding, + RoomTemplateRef startLocation, + long runtimeRoomInstanceId, + String lifecycleStatus, + long lifecycleEpoch, + long rowVersion, + UUID captureId, + String graphSha256, + String preparationInputDigest) { + public static final String SCHEMA = "world-canonical-instance-lifecycle-evidence/v1"; + public static final String REQUEST_SCHEMA = "world-canonical-instance-lifecycle-read-request/v1"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern PREFIXED_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern BARE_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Set EVIDENCE_FIELDS = + Set.of( + "schema", + "request", + "launchBindingBytesBase64", + "startLocation", + "runtimeRoomInstanceId", + "lifecycleStatus", + "lifecycleEpoch", + "rowVersion", + "captureId", + "graphSha256", + "preparationInputDigest"); + private static final Set REQUEST_FIELDS = + Set.of( + "schemaVersion", + "readRequestId", + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "canonicalGameInstanceId", + "playableStateNamespaceId", + "playableStateScope", + "publicProduction", + "controlPlaneRequestId", + "canonicalVersionId", + "expectedDescriptorRequestDigest", + "expectedDescriptorResultDigest", + "expectedReleaseAttestationDigest"); + private static final Set REQUEST_ENVELOPE_FIELDS = Set.of("schema", "request"); + private static final Set ROOM_TEMPLATE_REF_FIELDS = + Set.of("tenantId", "versionId", "roomTemplateId"); + private static final Set LIFECYCLE_STATUSES = + Set.of("PREPARING", "ACTIVE", "FAILED_PRE_ACTIVATION", "TERMINATING", "TERMINATED"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + + public WorldCanonicalInstanceLifecycleEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(launchBinding, "launchBinding"); + Objects.requireNonNull(startLocation, "startLocation"); + if (runtimeRoomInstanceId <= 0) { + throw new IllegalArgumentException("runtimeRoomInstanceId must be positive"); + } + if (lifecycleStatus == null || !LIFECYCLE_STATUSES.contains(lifecycleStatus)) { + throw new IllegalArgumentException("Unsupported World lifecycle status"); + } + if (lifecycleEpoch <= 0) { + throw new IllegalArgumentException("World lifecycleEpoch must be positive"); + } + if (rowVersion < 0) { + throw new IllegalArgumentException("World lifecycle rowVersion must be nonnegative"); + } + requireNonNil(captureId, "captureId"); + requireDigest(graphSha256, BARE_SHA256, "graphSha256"); + requireDigest(preparationInputDigest, PREFIXED_SHA256, "preparationInputDigest"); + requireExactBinding(request, launchBinding, startLocation, graphSha256); + } + + /** Closed canonical representation with the complete descriptor and separate attestation. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("request", requestJson(request)); + value.put( + "launchBindingBytesBase64", + Base64.getEncoder().encodeToString(closedLaunchBindingBytes(launchBinding))); + value.put("startLocation", roomTemplateRefJson(startLocation)); + value.put("runtimeRoomInstanceId", Long.toString(runtimeRoomInstanceId)); + value.put("lifecycleStatus", lifecycleStatus); + value.put("lifecycleEpoch", Long.toString(lifecycleEpoch)); + value.put("rowVersion", Long.toString(rowVersion)); + value.put("captureId", captureId.toString()); + value.put("graphSha256", graphSha256); + value.put("preparationInputDigest", preparationInputDigest); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World canonical lifecycle evidence cannot be encoded", impossible); + } + } + + /** Decodes closed retained bytes; this does not authenticate the producing World workload. */ + public static WorldCanonicalInstanceLifecycleEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root, EVIDENCE_FIELDS, "World canonical lifecycle evidence"); + if (!SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported World canonical lifecycle evidence schema"); + } + Request request = parseRequest(root.get("request")); + CompleteLaunchBindingEvidence launchBinding = + parseLaunchBinding(base64(root, "launchBindingBytesBase64")); + WorldCanonicalInstanceLifecycleEvidence evidence = + new WorldCanonicalInstanceLifecycleEvidence( + request, + launchBinding, + parseRoomTemplateRef(root.get("startLocation")), + positiveLong(text(root, "runtimeRoomInstanceId"), "runtimeRoomInstanceId"), + text(root, "lifecycleStatus"), + positiveLong(text(root, "lifecycleEpoch"), "lifecycleEpoch"), + nonNegativeLong(text(root, "rowVersion"), "rowVersion"), + parseUuid(text(root, "captureId"), "captureId"), + text(root, "graphSha256"), + text(root, "preparationInputDigest")); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("World canonical lifecycle evidence is not canonical"); + } + return evidence; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World canonical lifecycle evidence is invalid", invalid); + } + } + + private static void requireExactBinding( + Request request, + CompleteLaunchBindingEvidence binding, + RoomTemplateRef startLocation, + String graphSha256) { + AuthoredWorldLaunchDescriptorEvidence descriptor = binding.descriptor(); + AuthoredWorldReleaseAttestationEvidence release = binding.releaseAttestation(); + descriptor.requireValid(); + release.requireValid(descriptor); + if (!request.targetNamespace().equals(descriptor.targetNamespace()) + || !request.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !request.worldSlug().equals(descriptor.worldSlug()) + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request.expectedReleaseAttestationDigest().equals(release.evidenceDigest()) + || !request.canonicalVersionId().equals(release.canonicalVersionId())) { + throw new IllegalArgumentException( + "World lifecycle request differs from the complete launch binding"); + } + if (release.schemaVersion() != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + || release.worldStartLocationEvidence() == null) { + throw new IllegalArgumentException( + "World lifecycle evidence requires the complete selector/v2 release attestation"); + } + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored( + release.worldStartLocationEvidence().selectorReceiptBytes()); + String selectedGraphSha256 = selectorReceipt.graphDigest().substring("sha256:".length()); + if (!selectorReceipt.startLocation().equals(startLocation) + || !selectedGraphSha256.equals(graphSha256)) { + throw new IllegalArgumentException( + "World lifecycle ROOM selector or graph digest differs from the complete release selector"); + } + } + + private static byte[] closedLaunchBindingBytes(CompleteLaunchBindingEvidence binding) { + try { + // Preserve every original descriptor/release value, including long numeric fields, inside + // the opaque outer base64 envelope instead of subjecting those owner bytes to RFC 8785's + // JavaScript-number range. + return JSON.writeValueAsString(binding).getBytes(StandardCharsets.UTF_8); + } catch (tools.jackson.core.JacksonException impossible) { + throw new IllegalStateException("Complete launch binding cannot be encoded", impossible); + } + } + + private static CompleteLaunchBindingEvidence parseLaunchBinding(byte[] stored) { + try { + JsonNode node = JSON.readTree(strictUtf8(stored)); + requireFields(node, Set.of("descriptor", "releaseAttestation"), "complete launch binding"); + CompleteLaunchBindingEvidence binding = + JSON.treeToValue(node, CompleteLaunchBindingEvidence.class); + if (!Arrays.equals(stored, closedLaunchBindingBytes(binding))) { + throw new IllegalArgumentException( + "Nested complete launch binding bytes are not canonical"); + } + return binding; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException( + "Nested complete launch binding bytes are invalid", invalid); + } + } + + private static Request parseRequest(JsonNode node) { + requireFields(node, REQUEST_FIELDS, "World canonical lifecycle request"); + JsonNode publicProduction = node.get("publicProduction"); + if (publicProduction == null || !publicProduction.isBoolean()) { + throw new IllegalArgumentException("publicProduction must be present as a boolean"); + } + return new Request( + intValue(node, "schemaVersion"), + parseUuid(text(node, "readRequestId"), "readRequestId"), + text(node, "targetNamespace"), + parseUuid(text(node, "canonicalTenantId"), "canonicalTenantId"), + text(node, "worldSlug"), + parseUuid(text(node, "canonicalGameInstanceId"), "canonicalGameInstanceId"), + parseUuid(text(node, "playableStateNamespaceId"), "playableStateNamespaceId"), + text(node, "playableStateScope"), + publicProduction.booleanValue(), + text(node, "controlPlaneRequestId"), + parseUuid(text(node, "canonicalVersionId"), "canonicalVersionId"), + text(node, "expectedDescriptorRequestDigest"), + text(node, "expectedDescriptorResultDigest"), + text(node, "expectedReleaseAttestationDigest")); + } + + private static RoomTemplateRef parseRoomTemplateRef(JsonNode node) { + requireFields(node, ROOM_TEMPLATE_REF_FIELDS, "World lifecycle startLocation"); + return new RoomTemplateRef( + parseUuid(text(node, "tenantId"), "startLocation.tenantId"), + parseUuid(text(node, "versionId"), "startLocation.versionId"), + parseUuid(text(node, "roomTemplateId"), "startLocation.roomTemplateId")); + } + + private static Map requestJson(Request request) { + Map value = new LinkedHashMap<>(); + value.put("schemaVersion", request.schemaVersion()); + value.put("readRequestId", request.readRequestId().toString()); + value.put("targetNamespace", request.targetNamespace()); + value.put("canonicalTenantId", request.canonicalTenantId().toString()); + value.put("worldSlug", request.worldSlug()); + value.put("canonicalGameInstanceId", request.canonicalGameInstanceId().toString()); + value.put("playableStateNamespaceId", request.playableStateNamespaceId().toString()); + value.put("playableStateScope", request.playableStateScope()); + value.put("publicProduction", request.publicProduction()); + value.put("controlPlaneRequestId", request.controlPlaneRequestId()); + value.put("canonicalVersionId", request.canonicalVersionId().toString()); + value.put("expectedDescriptorRequestDigest", request.expectedDescriptorRequestDigest()); + value.put("expectedDescriptorResultDigest", request.expectedDescriptorResultDigest()); + value.put("expectedReleaseAttestationDigest", request.expectedReleaseAttestationDigest()); + return value; + } + + private static Map roomTemplateRefJson(RoomTemplateRef reference) { + Map value = new LinkedHashMap<>(); + value.put("tenantId", reference.tenantId().toString()); + value.put("versionId", reference.versionId().toString()); + value.put("roomTemplateId", reference.roomTemplateId().toString()); + return value; + } + + private static byte[] base64(JsonNode node, String field) { + try { + return Base64.getDecoder().decode(text(node, field)); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Invalid base64 field " + field, invalid); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual() || value.textValue().isBlank()) { + throw new IllegalArgumentException(field + " is required"); + } + return value.textValue(); + } + + private static int intValue(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw new IllegalArgumentException(field + " must be an integer"); + } + return value.intValue(); + } + + private static long positiveLong(String value, String field) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static long nonNegativeLong(String value, String field) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical nonnegative decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException( + "Canonical World lifecycle bytes are not strict UTF-8", invalid); + } + } + + private static UUID parseUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value, Pattern pattern, String label) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException(label + " is not a canonical SHA-256 digest"); + } + } + + private static void requireFields(JsonNode object, Set fields, String label) { + if (object == null || !object.isObject()) { + throw new IllegalArgumentException(label + " must be an object"); + } + Set actual = new java.util.HashSet<>(); + object.propertyNames().forEach(actual::add); + if (!actual.equals(fields)) { + throw new IllegalArgumentException(label + " has missing or unsupported fields"); + } + } + + /** Exact shared request envelope for the read-only World lifecycle capture. */ + public record Request( + int schemaVersion, + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + String playableStateScope, + boolean publicProduction, + String controlPlaneRequestId, + UUID canonicalVersionId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationDigest) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World canonical lifecycle read schema"); + } + requireNonNil(readRequestId, "readRequestId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException( + "This lifecycle carrier accepts SHARED scope only; private/playtest proof is unavailable"); + } + if (!publicProduction) { + throw new IllegalArgumentException( + "This lifecycle carrier requires public-production evidence"); + } + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireDigest( + expectedDescriptorRequestDigest, PREFIXED_SHA256, "expectedDescriptorRequestDigest"); + requireDigest( + expectedDescriptorResultDigest, PREFIXED_SHA256, "expectedDescriptorResultDigest"); + requireDigest( + expectedReleaseAttestationDigest, PREFIXED_SHA256, "expectedReleaseAttestationDigest"); + } + + /** Closed canonical request bytes used by the standalone World read RPC. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", REQUEST_SCHEMA); + value.put("request", requestJson(this)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World canonical lifecycle request cannot be encoded", impossible); + } + } + + /** Decodes only a complete closed request; this does not authenticate its sender. */ + public static Request fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root, REQUEST_ENVELOPE_FIELDS, "World canonical lifecycle read request"); + if (!REQUEST_SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException( + "Unsupported World canonical lifecycle request schema"); + } + Request request = parseRequest(root.get("request")); + if (!Arrays.equals(stored, request.canonicalBytes())) { + throw new IllegalArgumentException("World canonical lifecycle request is not canonical"); + } + return request; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World canonical lifecycle request is invalid", invalid); + } + } + + private static void requireText(String value, String label, int maxLength) { + if (value == null || value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(label + " is required and must fit its limit"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/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..2db322fe14 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java @@ -0,0 +1,556 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Exact World selector readback for an immutable frozen publication selection. + * + *

This evidence does not establish current Account permission, complete release evidence, + * activation, or admission. Decoding and relation checks do not authenticate the producer. The + * explicit mTLS client is responsible for authenticating World before accepting it. + */ +public record WorldPublishedStartLocationEvidence( + Request request, + byte[] selectorReceiptBytes, + byte[] originalAccountBindingBytes, + byte[] appliedResultBytes) { + public static final String SCHEMA = "world-published-start-location-evidence/v1"; + private static final int APPLIED_INTAKE_REQUEST_ID_FRAME = 13; + + private static final Set EVIDENCE_FIELDS = + Set.of( + "schema", + "request", + "selectorReceiptBytesBase64", + "originalAccountBindingBytesBase64", + "appliedResultBytesBase64"); + private static final Set REQUEST_FIELDS = + Set.of( + "targetNamespace", + "canonicalTenantId", + "canonicalVersionId", + "intakeRequestId", + "publicationFence", + "publicationRequestId", + "requestDigest", + "versionStateEpoch", + "publishWorkflowId", + "appliedCommitId", + "contentDigest", + "digestSchemaVersion", + "worldAffectedTuples"); + private static final Set TUPLE_FIELDS = + Set.of("owner", "aggregateType", "aggregateId", "scopeType", "scopeId", "expectedEpoch"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public WorldPublishedStartLocationEvidence { + Objects.requireNonNull(request, "request"); + selectorReceiptBytes = bytes(selectorReceiptBytes, "selectorReceiptBytes"); + originalAccountBindingBytes = bytes(originalAccountBindingBytes, "originalAccountBindingBytes"); + appliedResultBytes = bytes(appliedResultBytes, "appliedResultBytes"); + requireRelation(request, selectorReceiptBytes, originalAccountBindingBytes, appliedResultBytes); + } + + @Override + public byte[] selectorReceiptBytes() { + return selectorReceiptBytes.clone(); + } + + @Override + public byte[] originalAccountBindingBytes() { + return originalAccountBindingBytes.clone(); + } + + @Override + public byte[] appliedResultBytes() { + return appliedResultBytes.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof WorldPublishedStartLocationEvidence that)) return false; + return request.equals(that.request) + && Arrays.equals(selectorReceiptBytes, that.selectorReceiptBytes) + && Arrays.equals(originalAccountBindingBytes, that.originalAccountBindingBytes) + && Arrays.equals(appliedResultBytes, that.appliedResultBytes); + } + + @Override + public int hashCode() { + int result = Objects.hash(request); + result = 31 * result + Arrays.hashCode(selectorReceiptBytes); + result = 31 * result + Arrays.hashCode(originalAccountBindingBytes); + result = 31 * result + Arrays.hashCode(appliedResultBytes); + return result; + } + + /** Canonical, closed durable representation; this encoding does not authenticate World. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("request", requestJson(request)); + value.put( + "selectorReceiptBytesBase64", Base64.getEncoder().encodeToString(selectorReceiptBytes)); + value.put( + "originalAccountBindingBytesBase64", + Base64.getEncoder().encodeToString(originalAccountBindingBytes)); + value.put("appliedResultBytesBase64", Base64.getEncoder().encodeToString(appliedResultBytes)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World published selector evidence cannot be encoded", impossible); + } + } + + /** + * Decodes and validates retained bytes, but does not establish authenticated producer provenance. + */ + public static WorldPublishedStartLocationEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(stored); + requireFields(root, EVIDENCE_FIELDS, "published World selector evidence"); + if (!SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported published World selector evidence schema"); + } + var evidence = + new WorldPublishedStartLocationEvidence( + parseRequest(root.get("request")), + base64(root, "selectorReceiptBytesBase64"), + base64(root, "originalAccountBindingBytesBase64"), + base64(root, "appliedResultBytesBase64")); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("Published World selector evidence is not canonical"); + } + return evidence; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Published World selector evidence is invalid", invalid); + } + } + + private static void requireRelation( + Request request, byte[] receiptBytes, byte[] accountBytes, byte[] appliedBytes) { + var account = DraftAuthorizationFenceBinding.fromStored(accountBytes); + if (!request.canonicalTenantId().equals(account.tenantId()) + || !request.canonicalVersionId().equals(account.versionId()) + || !request.appliedCommitId().equals(account.commitId().toString())) { + throw new IllegalArgumentException( + "Published World selection differs from original Account binding"); + } + + DraftCommitBinding draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + if (!Arrays.equals(draft.canonicalBytes(), account.normalizedInput()) + || !draft.requestId().equals(account.requestId()) + || !draft.commitId().equals(account.commitId()) + || !draft.target().canonicalTenantId().equals(request.canonicalTenantId()) + || !draft.target().canonicalVersionId().equals(request.canonicalVersionId())) { + throw new IllegalArgumentException( + "Published World selection differs from original Draft binding"); + } + List boundTuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .sorted( + Comparator.comparing(OwnedAffectedTuple::owner) + .thenComparing(OwnedAffectedTuple::aggregateType) + .thenComparing(OwnedAffectedTuple::aggregateId) + .thenComparing(OwnedAffectedTuple::scopeType) + .thenComparing(OwnedAffectedTuple::scopeId) + .thenComparing(OwnedAffectedTuple::expectedEpoch)) + .toList(); + if (!request.worldAffectedTuples().equals(boundTuples)) { + throw new IllegalArgumentException( + "Published World selection changed the complete World affected set"); + } + + var terminalRequest = + WorldDraftTerminalReadEvidence.Request.create(request.targetNamespace(), accountBytes); + var terminalReadback = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + accountBytes, + appliedBytes); + var terminalResponse = + WorldDraftTerminalReadGrpcCodec.toResponse( + terminalRequest, java.util.Optional.of(terminalReadback)); + WorldDraftTerminalReadGrpcCodec.fromResponse(terminalRequest, terminalResponse); + + JsonNode applied = readApplied(appliedBytes); + if (!"APPLIED".equals(text(applied, "status"))) { + throw new IllegalArgumentException( + "Published World selector requires the original APPLIED result"); + } + if (!request.intakeRequestId().equals(appliedIntakeRequestId(applied))) { + throw new IllegalArgumentException( + "Published World selection differs from the original APPLIED intake request"); + } + byte[] resultReceipt = base64(applied, "startLocationReceiptBase64"); + if (!Arrays.equals(receiptBytes, resultReceipt)) { + throw new IllegalArgumentException( + "Published World selector differs from original APPLIED receipt"); + } + WorldDraftStartLocationEvidence receipt = + WorldDraftStartLocationEvidence.fromStored(receiptBytes); + if (!receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.operationId().equals(account.operationId()) + || !receipt.requestId().equals(account.requestId()) + || !receipt.commitId().equals(account.commitId()) + || !receipt.authorizationFenceId().equals(account.fenceId()) + || !receipt.accountBindingDigest().equals(prefixedSha256(accountBytes)) + || !receipt.bindingDigest().equals(draft.digest()) + || !receipt.startLocation().tenantId().equals(request.canonicalTenantId()) + || !receipt.startLocation().versionId().equals(request.canonicalVersionId()) + || !receipt.graphDigest().equals(text(applied, "graphDigest"))) { + throw new IllegalArgumentException( + "Published World selector receipt differs from selected APPLIED commit"); + } + } + + private static JsonNode readApplied(byte[] bytes) { + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + return JSON.readTree(json); + } catch (IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World APPLIED result is invalid", invalid); + } + } + + /** Reads the immutable intake identity from the exact operation frame already codec-validated. */ + private static UUID appliedIntakeRequestId(JsonNode applied) { + ByteBuffer operation = ByteBuffer.wrap(base64(applied, "operationBytesBase64")); + String intakeRequestId = null; + for (int frameIndex = 0; frameIndex <= APPLIED_INTAKE_REQUEST_ID_FRAME; frameIndex++) { + if (operation.remaining() < Integer.BYTES) { + throw new IllegalArgumentException("World APPLIED operation frame is truncated"); + } + int frameLength = operation.getInt(); + if (frameLength < 0 || frameLength > operation.remaining()) { + throw new IllegalArgumentException("World APPLIED operation frame has an invalid length"); + } + byte[] frame = new byte[frameLength]; + operation.get(frame); + if (frameIndex == 0 + && !"world-draft-terminal-operation/v1" + .equals(new String(frame, StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Unsupported World APPLIED operation frame schema"); + } + if (frameIndex == APPLIED_INTAKE_REQUEST_ID_FRAME) { + try { + intakeRequestId = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(frame)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException( + "World APPLIED intake request frame is invalid", invalid); + } + } + } + return parseUuid(intakeRequestId, "APPLIED intakeRequestId"); + } + + private static String prefixedSha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private static Request parseRequest(JsonNode node) { + requireFields(node, REQUEST_FIELDS, "published World selector request"); + JsonNode tuples = node.get("worldAffectedTuples"); + if (tuples == null || !tuples.isArray()) { + throw new IllegalArgumentException("World affected tuple array is required"); + } + List affected = new ArrayList<>(); + for (JsonNode tuple : tuples) { + requireFields(tuple, TUPLE_FIELDS, "World affected tuple"); + affected.add( + new OwnedAffectedTuple( + text(tuple, "owner"), + text(tuple, "aggregateType"), + text(tuple, "aggregateId"), + text(tuple, "scopeType"), + text(tuple, "scopeId"), + text(tuple, "expectedEpoch"))); + } + Request decoded = + new Request( + text(node, "targetNamespace"), + parseUuid(text(node, "canonicalTenantId"), "canonicalTenantId"), + parseUuid(text(node, "canonicalVersionId"), "canonicalVersionId"), + parseUuid(text(node, "intakeRequestId"), "intakeRequestId"), + parseUuid(text(node, "publicationFence"), "publicationFence"), + text(node, "publicationRequestId"), + text(node, "requestDigest"), + positiveLong(text(node, "versionStateEpoch"), "versionStateEpoch"), + text(node, "publishWorkflowId"), + text(node, "appliedCommitId"), + text(node, "contentDigest"), + intValue(node, "digestSchemaVersion"), + affected); + if (!decoded.worldAffectedTuples().equals(affected)) { + throw new IllegalArgumentException("World affected tuples are not in canonical order"); + } + return decoded; + } + + private static Map requestJson(Request request) { + Map value = new LinkedHashMap<>(); + value.put("targetNamespace", request.targetNamespace()); + value.put("canonicalTenantId", request.canonicalTenantId().toString()); + value.put("canonicalVersionId", request.canonicalVersionId().toString()); + value.put("intakeRequestId", request.intakeRequestId().toString()); + value.put("publicationFence", request.publicationFence().toString()); + value.put("publicationRequestId", request.publicationRequestId()); + value.put("requestDigest", request.requestDigest()); + value.put("versionStateEpoch", Long.toString(request.versionStateEpoch())); + value.put("publishWorkflowId", request.publishWorkflowId()); + value.put("appliedCommitId", request.appliedCommitId()); + value.put("contentDigest", request.contentDigest()); + value.put("digestSchemaVersion", request.digestSchemaVersion()); + value.put( + "worldAffectedTuples", + request.worldAffectedTuples().stream() + .map( + tuple -> { + Map item = new LinkedHashMap<>(); + item.put("owner", tuple.owner()); + item.put("aggregateType", tuple.aggregateType()); + item.put("aggregateId", tuple.aggregateId()); + item.put("scopeType", tuple.scopeType()); + item.put("scopeId", tuple.scopeId()); + item.put("expectedEpoch", tuple.expectedEpoch()); + return item; + }) + .toList()); + return value; + } + + private static byte[] base64(JsonNode node, String field) { + try { + return Base64.getDecoder().decode(text(node, field)); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Invalid base64 field " + field, invalid); + } + } + + private static byte[] bytes(byte[] value, String name) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException(name + " is required"); + } + return value.clone(); + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual() || value.textValue().isBlank()) { + throw new IllegalArgumentException(field + " is required"); + } + return value.textValue(); + } + + private static long positiveLong(String value, String field) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static int intValue(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw new IllegalArgumentException(field + " must be an integer"); + } + return value.intValue(); + } + + private static UUID parseUuid(String value, String label) { + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical UUID", invalid); + } + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private static void requireFields(JsonNode object, Set fields, String label) { + if (object == null || !object.isObject()) { + throw new IllegalArgumentException(label + " must be an object"); + } + Set actual = new java.util.HashSet<>(); + object.propertyNames().forEach(actual::add); + if (!actual.equals(fields)) { + throw new IllegalArgumentException(label + " has missing or unsupported fields"); + } + } + + /** Exact transport-neutral immutable selection input. */ + public record Request( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID intakeRequestId, + UUID publicationFence, + String publicationRequestId, + String requestDigest, + long versionStateEpoch, + String publishWorkflowId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + List worldAffectedTuples) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + requireUuid(canonicalTenantId, "canonicalTenantId"); + requireUuid(canonicalVersionId, "canonicalVersionId"); + requireUuid(intakeRequestId, "intakeRequestId"); + requireUuid(publicationFence, "publicationFence"); + requireText(publicationRequestId, "publicationRequestId"); + requireSha256(requestDigest, "requestDigest"); + if (versionStateEpoch <= 0) + throw new IllegalArgumentException("versionStateEpoch must be positive"); + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(appliedCommitId, "appliedCommitId"); + requireSha256(contentDigest, "contentDigest"); + if (digestSchemaVersion != 2 && digestSchemaVersion != 3) { + throw new IllegalArgumentException("Unsupported World digest schema version"); + } + Objects.requireNonNull(worldAffectedTuples, "worldAffectedTuples"); + List ordered = new ArrayList<>(worldAffectedTuples); + ordered.sort( + Comparator.comparing(OwnedAffectedTuple::owner) + .thenComparing(OwnedAffectedTuple::aggregateType) + .thenComparing(OwnedAffectedTuple::aggregateId) + .thenComparing(OwnedAffectedTuple::scopeType) + .thenComparing(OwnedAffectedTuple::scopeId) + .thenComparing(OwnedAffectedTuple::expectedEpoch)); + if (ordered.stream().distinct().count() != ordered.size()) { + throw new IllegalArgumentException("duplicate World affected tuple"); + } + worldAffectedTuples = List.copyOf(ordered); + } + + private static void requireUuid(UUID value, String name) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireText(String value, String name) { + if (value == null || value.isBlank()) + throw new IllegalArgumentException(name + " is required"); + } + + private static void requireSha256(String value, String name) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be 64 lowercase hexadecimal digits"); + } + } + } + + public record OwnedAffectedTuple( + String owner, + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch) { + public OwnedAffectedTuple { + if (!"WORLD_MANAGEMENT".equals(owner)) { + throw new IllegalArgumentException("Published selector tuples must name WORLD_MANAGEMENT"); + } + requireTupleText(aggregateType, "aggregateType"); + requireTupleText(aggregateId, "aggregateId"); + Objects.requireNonNull(scopeType, "scopeType"); + Objects.requireNonNull(scopeId, "scopeId"); + if (scopeType.isEmpty() != scopeId.isEmpty()) { + throw new IllegalArgumentException("scopeType and scopeId must both be present or absent"); + } + if (expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || new java.math.BigInteger(expectedEpoch) + .compareTo(java.math.BigInteger.valueOf(Long.MAX_VALUE)) + > 0) { + throw new IllegalArgumentException("expectedEpoch must be canonical non-negative decimal"); + } + } + + private static void requireTupleText(String value, String name) { + if (value == null || value.isBlank()) + throw new IllegalArgumentException(name + " is required"); + } + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidence.java b/services/common-security/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidence.java new file mode 100644 index 0000000000..ba635250e4 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidence.java @@ -0,0 +1,312 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.JsonParser; +import tools.jackson.core.JsonToken; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Distinct World-owned player-admission lifecycle hold. This is neither a first-pointer hold nor + * Account authorization, Game Session's binding decision, or gameplay admission permission. + * + *

The complete original lease and exact World owner evidence remain immutable. Its deadline is + * diagnostic only. Release requires independently authenticated exact Account terminal evidence AND + * Game Session installation/cleanup evidence; those producers do not exist in this slice. + */ +public record WorldCanonicalPlayerAdmissionHoldEvidence( + UUID holdId, + UUID holdFence, + Request request, + WorldCanonicalInstanceLifecycleEvidence worldEvidence) { + public static final String SCHEMA = "world-canonical-player-admission-hold-evidence/v1"; + public static final int MAX_EVIDENCE_BYTES = 1024 * 1024; + public static final int MAX_LIFECYCLE_BYTES = 512 * 1024; + private static final Set FIELDS = + Set.of( + "schema", + "schemaVersion", + "holdId", + "holdFence", + "request", + "worldLifecycleEvidenceBase64"); + private static final Set REQUEST_FIELDS = + Set.of( + "accountLeaseJson", "accountLeaseSha256", "expectedLifecycleEpoch", "expectedRowVersion"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public WorldCanonicalPlayerAdmissionHoldEvidence { + requireOpaque(holdId); + requireOpaque(holdFence); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(worldEvidence, "worldEvidence"); + request.requireExactActiveWorld(worldEvidence); + } + + /** Closed outer carrier; nested original Account and World bytes are preserved exactly. */ + public byte[] canonicalBytes() { + byte[] lifecycle = worldEvidence.canonicalBytes(); + requireBound(lifecycle, MAX_LIFECYCLE_BYTES); + Map value = + Map.of( + "schema", + SCHEMA, + "schemaVersion", + "1", + "holdId", + holdId.toString(), + "holdFence", + holdFence.toString(), + "request", + Map.of( + "accountLeaseJson", + request.lease().canonicalJson(), + "accountLeaseSha256", + request.lease().sha256(), + "expectedLifecycleEpoch", + Long.toString(request.expectedLifecycleEpoch()), + "expectedRowVersion", + Long.toString(request.expectedRowVersion())), + "worldLifecycleEvidenceBase64", + Base64.getEncoder().encodeToString(lifecycle)); + try { + byte[] result = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + requireBound(result, MAX_EVIDENCE_BYTES); + return result; + } catch (IOException failure) { + throw new IllegalStateException("Cannot encode canonical World player hold", failure); + } + } + + /** Separate digest of the complete canonical outer bytes; never a self-referential field. */ + public String sha256() { + return digest(canonicalBytes()); + } + + /** Shape and exact binding only: decoding does not authenticate World or authorize admission. */ + public static WorldCanonicalPlayerAdmissionHoldEvidence fromCanonical( + byte[] bytes, String sha256) { + requireBound(bytes, MAX_EVIDENCE_BYTES); + if (sha256 == null || !sha256.matches("[0-9a-f]{64}") || !digest(bytes).equals(sha256)) { + throw new IllegalArgumentException("World hold evidence SHA256 differs from original bytes"); + } + return parseCanonical(bytes); + } + + public static WorldCanonicalPlayerAdmissionHoldEvidence parseCanonical(byte[] bytes) { + requireBound(bytes, MAX_EVIDENCE_BYTES); + String json = strictUtf8(bytes); + try { + try (JsonParser parser = JSON.createParser(json)) { + int depth = 0; + JsonToken token; + while ((token = parser.nextToken()) != null) { + if ((token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) && ++depth > 4) + throw new IllegalArgumentException("World hold evidence exceeds closed nesting bound"); + if (token == JsonToken.END_OBJECT || token == JsonToken.END_ARRAY) depth--; + } + } + JsonNode root = JSON.readTree(json); + exact(root, FIELDS); + if (!SCHEMA.equals(text(root, "schema")) || !"1".equals(text(root, "schemaVersion"))) { + throw new IllegalArgumentException("Unsupported World player hold evidence schema"); + } + JsonNode bound = root.get("request"); + exact(bound, REQUEST_FIELDS); + var lease = + AccountGameplayAdmissionLeaseEvidence.parseCanonical(text(bound, "accountLeaseJson")); + if (!lease.sha256().equals(text(bound, "accountLeaseSha256"))) { + throw new IllegalArgumentException( + "World hold request substituted its original Account lease digest"); + } + var request = + new Request( + lease, + decimal(text(bound, "expectedLifecycleEpoch"), true), + decimal(text(bound, "expectedRowVersion"), false)); + String encoded = text(root, "worldLifecycleEvidenceBase64"); + byte[] lifecycle = Base64.getDecoder().decode(encoded); + requireBound(lifecycle, MAX_LIFECYCLE_BYTES); + if (!Base64.getEncoder().encodeToString(lifecycle).equals(encoded)) { + throw new IllegalArgumentException("World lifecycle evidence base64 is not canonical"); + } + var result = + new WorldCanonicalPlayerAdmissionHoldEvidence( + UUID.fromString(text(root, "holdId")), + UUID.fromString(text(root, "holdFence")), + request, + WorldCanonicalInstanceLifecycleEvidence.fromStored(lifecycle)); + if (!Arrays.equals(bytes, result.canonicalBytes())) { + throw new IllegalArgumentException("World hold evidence bytes are not canonical"); + } + return result; + } catch (tools.jackson.core.JacksonException failure) { + throw new IllegalArgumentException("Malformed World player hold evidence", failure); + } + } + + private static String digest(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA256 is unavailable", failure); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException failure) { + throw new IllegalArgumentException("World hold evidence must be strict UTF-8", failure); + } + } + + private static void requireBound(byte[] bytes, int maximum) { + if (bytes == null || bytes.length == 0 || bytes.length > maximum) { + throw new IllegalArgumentException( + "World hold evidence exceeds its byte bound or is missing"); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual() || value.textValue().isEmpty()) { + throw new IllegalArgumentException("World hold evidence requires textual " + field); + } + return value.textValue(); + } + + private static void exact(JsonNode node, Set fields) { + if (node == null || !node.isObject()) { + throw new IllegalArgumentException("World hold evidence contains unknown or missing fields"); + } + Set actual = new java.util.HashSet<>(); + node.propertyNames().forEach(actual::add); + if (!actual.equals(fields)) + throw new IllegalArgumentException("World hold evidence contains unknown or missing fields"); + } + + public static long decimal(String value, boolean positive) { + if (value == null + || !value.matches(positive ? "[1-9][0-9]*" : "0|[1-9][0-9]*") + || value.length() > 19) { + throw new IllegalArgumentException("World hold counters require canonical decimal strings"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException failure) { + throw new IllegalArgumentException("World hold counter exceeds signed-long range", failure); + } + } + + /** Retained lease deadline triggers recovery diagnostics, never automatic release. */ + public long diagnosticExpiresAtMillis() { + return Long.parseLong((String) request.lease().carrier().get("expiresAt")); + } + + /** + * Complete original Account lease plus independently expected World lifecycle tuple. Account's + * regionEpoch is a separate domain and is never interpreted as this World lifecycle epoch. + */ + public record Request( + AccountGameplayAdmissionLeaseEvidence lease, + long expectedLifecycleEpoch, + long expectedRowVersion) { + public Request { + Objects.requireNonNull(lease, "lease"); + if (expectedLifecycleEpoch <= 0 || expectedRowVersion < 0) { + throw new IllegalArgumentException("Expected World lifecycle tuple is invalid"); + } + if (!(lease.carrier().get("bindingScope") instanceof Map scope) + || !"SHARED".equals(scope.get("playableStateScope")) + || !(lease.carrier().get("membershipBaseline") instanceof Map baseline) + || !"ACTIVE".equals(baseline.get("membershipLifecycleState"))) { + throw new IllegalArgumentException("Unsupported or non-admitting original lease scope"); + } + } + + public UUID leaseId() { + return UUID.fromString((String) lease.carrier().get("leaseId")); + } + + public UUID attemptId() { + return UUID.fromString((String) lease.carrier().get("requestId")); + } + + public UUID canonicalGameInstanceId() { + return UUID.fromString((String) scope().get("gameInstanceId")); + } + + public String targetNamespace() { + return (String) lease.carrier().get("targetNamespace"); + } + + public boolean sameBinding(Request other) { + return other != null + && lease.hasSameIdentity(other.lease) + && expectedLifecycleEpoch == other.expectedLifecycleEpoch + && expectedRowVersion == other.expectedRowVersion; + } + + public void requireExactActiveWorld(WorldCanonicalInstanceLifecycleEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + requireExactWorldSelector(evidence.request()); + if (!"ACTIVE".equals(evidence.lifecycleStatus()) + || expectedLifecycleEpoch != evidence.lifecycleEpoch() + || expectedRowVersion != evidence.rowVersion()) { + throw new IllegalArgumentException("World target is not the exact expected ACTIVE tuple"); + } + } + + public void requireExactWorldSelector( + WorldCanonicalInstanceLifecycleEvidence.Request selector) { + if (!targetNamespace().equals(selector.targetNamespace()) + || !scope().get("tenantId").equals(selector.canonicalTenantId().toString()) + || !scope().get("worldSlug").equals(selector.worldSlug()) + || !scope().get("gameInstanceId").equals(selector.canonicalGameInstanceId().toString()) + || !scope() + .get("playableStateNamespaceId") + .equals(selector.playableStateNamespaceId().toString()) + || !scope().get("playableStateScope").equals(selector.playableStateScope()) + || !selector.publicProduction()) { + throw new IllegalArgumentException("Original lease differs from canonical World scope"); + } + } + + @SuppressWarnings("unchecked") + private Map scope() { + return (Map) lease.carrier().get("bindingScope"); + } + } + + private static void requireOpaque(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Hold identity and fence must be opaque UUIDs"); + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java new file mode 100644 index 0000000000..f3e1e396a2 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java @@ -0,0 +1,804 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request; +import org.junit.jupiter.api.Test; + +/** Real nested codecs over explicitly synthetic source/application/release and lease fixtures. */ +class WorldCanonicalPlayerAdmissionHoldEvidenceTest { + private static final String ID = "11111111-1111-4111-8111-111111111111"; + private static final String ACCOUNT = "22222222-2222-4222-8222-222222222222"; + + @Test + void closedCanonicalRoundtripPreservesEveryOriginalNestedByteAndDigest() throws Exception { + var original = hold(); + byte[] bytes = original.canonicalBytes(); + var decoded = WorldCanonicalPlayerAdmissionHoldEvidence.fromCanonical(bytes, original.sha256()); + assertThat(decoded).isEqualTo(original); + assertThat(decoded.canonicalBytes()).containsExactly(bytes); + assertThat(decoded.request().lease().canonicalJson()) + .isEqualTo(original.request().lease().canonicalJson()); + assertThat(decoded.request().lease().sha256()).isEqualTo(original.request().lease().sha256()); + assertThat(decoded.worldEvidence().canonicalBytes()) + .containsExactly(original.worldEvidence().canonicalBytes()); + assertThat(decoded.diagnosticExpiresAtMillis()).isEqualTo(original.diagnosticExpiresAtMillis()); + bytes[0] ^= 1; + assertThat(original.canonicalBytes()).isEqualTo(decoded.canonicalBytes()); + } + + @Test + void rejectsUnknownMissingDuplicateAndNoncanonicalOuterBytes() throws Exception { + var original = hold(); + var root = JSON.readTree(original.canonicalBytes()); + var unknown = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) unknown).put("unknown", "value"); + assertRejected(canonical(unknown)); + var missing = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) missing).remove("schemaVersion"); + assertRejected(canonical(missing)); + var nestedUnknown = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) nestedUnknown.get("request")).put("unknown", "value"); + assertRejected(canonical(nestedUnknown)); + String text = new String(original.canonicalBytes(), StandardCharsets.UTF_8); + assertRejected( + text.replace("\"schemaVersion\":\"1\"", "\"schemaVersion\":\"1\",\"schemaVersion\":\"1\"") + .getBytes(StandardCharsets.UTF_8)); + assertRejected((" " + text).getBytes(StandardCharsets.UTF_8)); + assertRejected((text + "{}").getBytes(StandardCharsets.UTF_8)); + assertRejected( + text.replace("\"schemaVersion\":\"1\"", "\"schemaVersion\":1") + .getBytes(StandardCharsets.UTF_8)); + } + + @Test + void substitutedLeaseDigestOriginalScopeWorldEpochAndOpaqueIdentityFailClosed() throws Exception { + var original = hold(); + var root = JSON.readTree(original.canonicalBytes()); + var leaseDigest = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) leaseDigest.get("request")) + .put("accountLeaseSha256", "b".repeat(64)); + assertRejected(canonical(leaseDigest)); + var changedCarrier = new LinkedHashMap<>(original.request().lease().carrier()); + var changedScope = new LinkedHashMap<>(scope(changedCarrier)); + changedScope.put("worldSlug", "another-world"); + changedCarrier.put("bindingScope", changedScope); + var changedLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + var changed = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) changed.get("request")) + .put("accountLeaseJson", changedLease.canonicalJson()); + ((tools.jackson.databind.node.ObjectNode) changed.get("request")) + .put("accountLeaseSha256", changedLease.sha256()); + assertRejected(canonical(changed)); + var epoch = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) epoch.get("request")) + .put("expectedLifecycleEpoch", "4"); + assertRejected(canonical(epoch)); + var uuid = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) uuid) + .put("holdId", "00000000-0000-1000-8000-000000000001"); + assertRejected(canonical(uuid)); + assertThatThrownBy( + () -> + WorldCanonicalPlayerAdmissionHoldEvidence.fromCanonical( + original.canonicalBytes(), "c".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void exactDecimalStringsPreserveHighAndMaximumLongsAndRejectEveryOtherShape() throws Exception { + var original = hold(); + for (long value : List.of(9_007_199_254_740_993L, Long.MAX_VALUE)) { + var world = original.worldEvidence(); + var preciseWorld = + new WorldCanonicalInstanceLifecycleEvidence( + world.request(), + world.launchBinding(), + world.startLocation(), + world.runtimeRoomInstanceId(), + "ACTIVE", + value, + value, + world.captureId(), + world.graphSha256(), + world.preparationInputDigest()); + var precise = + new WorldCanonicalPlayerAdmissionHoldEvidence( + original.holdId(), + original.holdFence(), + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + original.request().lease(), value, value), + preciseWorld); + assertThat(WorldCanonicalPlayerAdmissionHoldEvidence.parseCanonical(precise.canonicalBytes())) + .isEqualTo(precise); + } + for (String invalid : List.of("01", "-1", "+1", "1.0", "1e0", " 1", "9223372036854775808")) { + var changed = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) changed.get("request")) + .put("expectedRowVersion", invalid); + assertRejected(canonical(changed)); + } + var numeric = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) numeric.get("request")) + .put("expectedLifecycleEpoch", 3); + assertRejected(canonical(numeric)); + var zeroEpoch = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) zeroEpoch.get("request")) + .put("expectedLifecycleEpoch", "0"); + assertRejected(canonical(zeroEpoch)); + } + + @Test + void rejectsUtf8Base64ByteAndNestingBoundsWithoutMockedNestedDecoders() throws Exception { + assertRejected(new byte[] {(byte) 0xc3, 0x28}); + assertRejected(new byte[WorldCanonicalPlayerAdmissionHoldEvidence.MAX_EVIDENCE_BYTES + 1]); + assertRejected("{\"request\":{\"a\":{\"b\":{\"c\":{}}}}}".getBytes(StandardCharsets.UTF_8)); + var original = hold(); + var invalidBase64 = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) invalidBase64) + .put("worldLifecycleEvidenceBase64", "%%%"); + assertRejected(canonical(invalidBase64)); + var oversizedLifecycle = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) oversizedLifecycle) + .put( + "worldLifecycleEvidenceBase64", + Base64.getEncoder() + .encodeToString( + new byte[WorldCanonicalPlayerAdmissionHoldEvidence.MAX_LIFECYCLE_BYTES + 1])); + assertRejected(canonical(oversizedLifecycle)); + var corruptedWorld = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) corruptedWorld) + .put( + "worldLifecycleEvidenceBase64", + Base64.getEncoder().encodeToString("{}".getBytes(StandardCharsets.UTF_8))); + assertRejected(canonical(corruptedWorld)); + } + + private static void assertRejected(byte[] bytes) throws Exception { + String digest = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + assertThatThrownBy(() -> WorldCanonicalPlayerAdmissionHoldEvidence.fromCanonical(bytes, digest)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static WorldCanonicalPlayerAdmissionHoldEvidence hold() throws Exception { + var world = lifecycleEvidence(); + var carrier = carrier(); + var boundScope = new LinkedHashMap<>(scope(carrier)); + boundScope.put("worldSlug", world.request().worldSlug()); + boundScope.put( + "playableStateNamespaceId", world.request().playableStateNamespaceId().toString()); + carrier.put("bindingScope", boundScope); + var lease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + return new WorldCanonicalPlayerAdmissionHoldEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + lease, world.lifecycleEpoch(), world.rowVersion()), + world); + } + + // Only synthetic fixture construction is adapted from existing Common Core codec tests below. + + private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID TENANT_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REVISION_ID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID REGION_TEMPLATE_ID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID ZONE_TEMPLATE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID ROOM_TEMPLATE_ID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID REGION_REVISION_ID = uuid("12345678-1234-4234-8234-123456789001"); + private static final UUID ZONE_REVISION_ID = uuid("12345678-1234-4234-8234-123456789002"); + private static final UUID ROOM_REVISION_ID = uuid("12345678-1234-4234-8234-123456789003"); + private static final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + private static WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence() throws Exception { + WorldPublishedStartLocationEvidence selector = publishedSelector(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.request().targetNamespace(), + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + RoomTemplateRef startLocation = selectorReceipt.startLocation(); + Request request = + new Request( + Request.SCHEMA_VERSION, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + startLocation, + 1042L, + "ACTIVE", + 3L, + 0L, + uuid("33333333-3333-4333-8333-333333333333"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "e".repeat(64)); + } + + static WorldPublishedStartLocationEvidence publishedSelector() throws Exception { + WorldDraftTerminalReadEvidence.Request terminalRequest = freshGraphRequest(); + OwnerReadback committed = committedReadback(terminalRequest, true); + var account = terminalRequest.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + List tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + account.tenantId(), + account.versionId(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + account.commitId().toString(), + "b".repeat(64), + 3, + tuples); + var applied = JSON.readTree(committed.result()); + byte[] receipt = + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()); + return new WorldPublishedStartLocationEvidence( + request, receipt, committed.fullBinding(), committed.result()); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request, boolean freshGraph) throws Exception { + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var operation = new ByteArrayOutputStream(); + var frames = new java.io.DataOutputStream(operation); + java.util.function.Consumer frame = + bytes -> { + try { + frames.writeInt(bytes.length); + frames.write(bytes); + } catch (java.io.IOException impossible) { + throw new AssertionError(impossible); + } + }; + java.util.function.Consumer text = + value -> frame.accept(value.getBytes(StandardCharsets.UTF_8)); + text.accept("world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) text.accept(id.toString()); + frame.accept(draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + Long.toString(draft.target().gameDesignVersionRowId()), + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "a".repeat(64), + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "b".repeat(64), + "c".repeat(64))) text.accept(value); + text.accept(sha256(account.canonicalBytes())); + frame.accept(account.canonicalBytes()); + byte[] graph = freshGraph ? graphBytes(request, draft) : historicalGraphBytes(account); + String graphDigest = sha256(graph); + var result = new java.util.LinkedHashMap(); + result.put( + "schema", freshGraph ? "world-draft-graph-applied/v2" : "world-draft-graph-applied/v1"); + result.put("status", "APPLIED"); + result.put("operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + if (freshGraph) { + var receipt = receipt(request, draft, graphDigest); + byte[] receiptBytes = canonical(receipt); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.get("receiptDigest").textValue()); + } + result.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) + .toList()); + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + canonical(JSON.valueToTree(result))); + } + + private static WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { + DraftCommitBinding draft = freshGraphBinding(); + return new WorldDraftTerminalReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), accountBinding(draft)); + } + + private static DraftCommitBinding freshGraphBinding() throws Exception { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "startLocation", + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + "1", + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_TEMPLATE_ID, null)), + new RevisionPayload( + "2", + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_TEMPLATE_ID, null))), + List.of( + affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private static String worldRevisionPayload( + UUID revisionId, String family, UUID templateId, String declaration) throws Exception { + var payload = new java.util.LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", COMMIT_ID.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(payload); + } + + private static List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private static byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private static byte[] historicalGraphBytes(DraftAuthorizationFenceBinding binding) { + return ("{\"schemaVersion\":\"2\",\"canonicalTenantId\":\"" + + binding.tenantId() + + "\",\"canonicalVersionId\":\"" + + binding.versionId() + + "\",\"rows\":[{}]}") + .getBytes(StandardCharsets.UTF_8); + } + + private static byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new java.util.LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new java.util.ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + var mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new java.util.LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", OPERATION_ID.toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private static tools.jackson.databind.node.ObjectNode receipt( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, String graphDigest) + throws Exception { + var account = request.accountBinding(); + var selector = + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()); + String accountBindingDigest = sha256(request.originalAccountBinding()); + String receiptDigest = + startLocationReceiptDigest( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + accountBindingDigest, + draft.digest(), + TENANT_ID, + VERSION_ID, + ROOM_TEMPLATE_ID, + graphDigest); + var value = new java.util.LinkedHashMap(); + value.put("schema", "world-draft-start-location-receipt/v1"); + value.put("targetNamespace", request.targetNamespace()); + value.put("operationId", account.operationId().toString()); + value.put("requestId", account.requestId().toString()); + value.put("commitId", account.commitId().toString()); + value.put("authorizationFenceId", account.fenceId().toString()); + value.put("accountBindingDigest", accountBindingDigest); + value.put("bindingDigest", draft.digest()); + value.put("startLocation", selector); + value.put("graphDigest", graphDigest); + value.put("receiptDigest", receiptDigest); + return (tools.jackson.databind.node.ObjectNode) JSON.valueToTree(value); + } + + private static String startLocationReceiptDigest( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + String accountBindingDigest, + String bindingDigest, + UUID tenantId, + UUID versionId, + UUID roomTemplateId, + String graphDigest) + throws Exception { + var framed = new ByteArrayOutputStream(); + for (String value : + List.of( + "world-draft-start-location-receipt/v1", + targetNamespace, + operationId.toString(), + requestId.toString(), + commitId.toString(), + fenceId.toString(), + accountBindingDigest, + bindingDigest, + tenantId.toString(), + versionId.toString(), + roomTemplateId.toString(), + graphDigest)) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + framed.writeBytes(bytes); + } + return sha256(framed.toByteArray()); + } + + private static byte[] canonical(tools.jackson.databind.JsonNode value) throws Exception { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + static Map carrier() { + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", "test"); + value.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + value.put("requestId", ID); + value.put("leaseId", ACCOUNT); + value.put("leaseFence", "1"); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "tenantId", + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, ID); + scope.put("accountId", ACCOUNT); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "9007199254740993"); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + Map.of(ID, "1"), + "privateRealmGrantVersions", + List.of())); + value.put("issuanceFence", "1"); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + "1")); + value.put( + "outboxCheckpoints", + List.of( + checkpoint("account/" + ACCOUNT, "0"), + checkpoint("issuer/firemud-account-service", "0"), + checkpoint("membership/" + ACCOUNT + "/" + ID, "1"), checkpoint("tenant/" + ID, "1"))); + long now = System.currentTimeMillis(); + value.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", ACCOUNT), + Map.entry("operationId", ID), + Map.entry("issuanceRequestId", ID), + Map.entry("tokenJti", ID), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("issuedAt", Long.toString(now / 1000)), + Map.entry("notBefore", Long.toString(now / 1000)), + Map.entry("expiresAt", Long.toString(now / 1000 + 300)))); + value.put("evaluatedAt", Long.toString(now)); + value.put("expiresAt", Long.toString(now + 15000)); + return value; + } + + @SuppressWarnings("unchecked") + static Map scope(Map carrier) { + return (Map) carrier.get("bindingScope"); + } + + private static Map checkpoint(String suffix, String sequence) { + return Map.of( + "outboxStreamKey", "account:auth-authority:v1:" + suffix, "outboxSequence", sequence); + } +} From 17e8f609dcbe4ef4dc096b8bfe82557a68bbe9ef Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 13:14:18 +1300 Subject: [PATCH 11/16] Protect exact negative admission lease readback --- .../account-service/runtime-and-data.md | 2 + .../player-access-and-session.md | 4 +- .../AccountGameplayAdmissionReadOwner.java | 99 +++++++++ ...ountGameplayAdmissionLeaseGrpcService.java | 77 ++++++- ...issionLeasePersistenceIntegrationTest.java | 100 ++++++++- ...AccountGameplayAdmissionReadOwnerTest.java | 203 ++++++++++++++++++ ...GameplayAdmissionLeaseGrpcServiceTest.java | 144 +++++++++++-- 7 files changed, 606 insertions(+), 23 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwner.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwnerTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index c0c7b547c0..f926a712b5 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +The admission transport also prepares unregistered exact negative-state readback and cancellation. Readback requires the original complete lease and authenticated same-namespace Game Session caller, returns only retained `PENDING` or `ABORTED` evidence and preserves its original expiry and cleanup identity. Missing, conflicting or raw storage `COMMITTED` state remains denied; historical negative readback is not current authorization, cleanup completion or an enabled RPC. Detailed proof and the still-missing positive owner belong to the [Account admission tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-admission-lease-prerequisite). + The admission prerequisite prepares an unregistered Account client for the distinct [World player-admission serving hold](../world-management-service/api-contracts.md#player-admission-serving-hold). It uses file-backed workload mTLS, verifies the exact same-namespace World server before releasing request evidence, and compares the original lease, target, expected World lifecycle epoch/row version, response correlation, and complete closed hold evidence. Calls run outside Account transactions and synchronization; absent or inconsistent readback remains unresolved. The client does not finalize Account authority, release a World hold, register a runtime RPC or admit gameplay. Executed proof and the remaining current-source/physical-COMMIT gates belong to the [Account admission tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-admission-lease-prerequisite). The credential-bound LOGIN source-only owner prepares or exactly replays one immutable Account operation, then invokes signer, Coordination Redis and response-recovery owners outside its credential-verification transaction. V81 adds the retained digest-key identifier and schema-qualified credential binding without converting historical unbound operations into authority. All components remain explicitly unwired; public gameplay authentication, trusted source-context production, key provisioning and physical PostgreSQL/Redis/fresh-image proof remain incomplete. See the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#credential-bound-account-login-owner) for this cut's proof status; canonical issuance and response-recovery predicates remain in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). 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 549cce6597..320f07aea8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -22,7 +22,9 @@ V87 adds unregistered Account-owned allocation and exact operation storage. Its The additive Account lease protobuf and Common Security wire codec wrap the existing canonical lease bytes and digest unchanged. Method-specific outcomes distinguish retained operations, domain denials and storage-only nonobservation; the wire does not register an RPC, authenticate a receipt or supply authorization. Unknown fields, malformed UTF-8, changed bytes/digest, unsupported counters and contradictory terminal presence are rejected. Game Session's separate exact lease-bound decision callback remains its owner boundary, not a pointer-read substitute. -The unregistered cancellation owner verifies the concrete same-namespace Game Session peer and the original canonical lease/caller binding before opening its own writable SERIALIZABLE Account transaction. It atomically records `PENDING` as `ABORTED` with one retained orphan-cleanup identity; an exact retry recovers the original bytes and decision presence without reminting. Changed operation evidence or decision correlation conflicts, absent operations remain unresolved, and `COMMITTED` cannot be turned into an abort or returned as admission evidence. The abort-only gRPC adapter distinguishes typed domain denial from validation, authentication and dependency errors. It remains unregistered; acquire, finalize, read and reconcile remain unimplemented. Unit collaborators and synthetic peer contexts are not physical SQL or mTLS proof, and cancellation does not retire a token or deliver Game Session cleanup. +The unregistered cancellation owner verifies the concrete same-namespace Game Session peer and the original canonical lease/caller binding before opening its own writable SERIALIZABLE Account transaction. It atomically records `PENDING` as `ABORTED` with one retained orphan-cleanup identity; an exact retry recovers the original bytes and decision presence without reminting. Changed operation evidence or decision correlation conflicts, absent operations remain unresolved, and `COMMITTED` cannot be turned into an abort or returned as admission evidence. The unregistered gRPC adapter distinguishes typed abort-domain denial from validation, authentication and dependency errors. Acquire, finalize and reconcile remain unimplemented. Unit collaborators and synthetic peer contexts are not physical SQL or mTLS proof, and cancellation does not retire a token or deliver Game Session cleanup. + +The separate unregistered exact-read owner requires the complete original `expected_lease`, matching outer request ID and same-namespace Game Session caller before an owned writable SERIALIZABLE Account-first read. It returns only exact `PENDING` or `ABORTED` evidence, preserving original bytes, deadline, optional decision and pending cleanup identity even after expiry. Missing or conflicting state and raw storage `COMMITTED` fail closed; this supported narrow read does not return `not_observed`, prove cleanup or retirement, allocate another identity, renew an attempt or admit gameplay. Five owner unit definitions, three added transport definitions and one added PostgreSQL definition cover the negative seam; existing lost-abort-ack and expiry PostgreSQL cases additionally exercise actual readback. Their peer and carrier fixtures are explicitly synthetic. Local full Account checks, formatting, static analysis, integration-source compilation, boot packaging and documentation checks passed in 2m52s: 1,158 unit cases and seven non-database integration cases executed, with three unit skips and 151 PostgreSQL skips. The five owner cases and all nine adapter cases passed; the new SQL assertions have not executed locally. The positive owner still requires complete current sources and the separate durable-COMMIT-before-expiry confirmation boundary; storage visibility alone is insufficient. The unregistered Account `GameSessionGameplayAdmissionDecisionClient` consumes that existing Game Session callback. It requires file-backed mTLS and the exact same-namespace Game Session server identity before releasing request headers or the original lease bytes, then verifies the response identity independently. Its bounded read rejects ambient Account transactions, changed decision IDs, schema/status/unknown fields, bytes and digest. The result remains a point-in-time `PROVISIONAL` observation, not held World or Account authority, a durable Account finalization result, or admission permission. Its socket tests use an explicitly labeled transport-only Game Session double and fabricated lease-shape fixtures; they cannot establish the real owner database or current target predicates. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwner.java new file mode 100644 index 0000000000..3eab991cbe --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwner.java @@ -0,0 +1,99 @@ +package net.firedevops.firemud.accountservice.repository; + +import io.grpc.Status; +import java.util.Objects; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered, non-authorizing exact readback for retained negative admission state. + * + *

The owner accepts only the original same-namespace Game Session workload and a complete + * expected lease carrier. It returns exact PENDING or ABORTED storage evidence; missing operations, + * identity mismatches, and raw storage COMMITTED are unresolved and never become admission results. + */ +public final class AccountGameplayAdmissionReadOwner { + private final AccountGameplayAdmissionLeaseRepository repository; + private final TransactionTemplate transaction; + private final String namespace; + + public AccountGameplayAdmissionReadOwner( + AccountGameplayAdmissionLeaseRepository repository, + PlatformTransactionManager transactionManager, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + } + + public AccountGameplayAdmissionLeaseOperation read(ReadGameplayAdmissionLeaseRequest request) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + if (!GrpcPeerIdentity.isValidNamespace(namespace) + || !peer.uri().equals("spiffe://firemud/ns/" + namespace + "/sa/game-session-service")) + throw Status.PERMISSION_DENIED + .withDescription("Game Session workload required") + .asRuntimeException(); + if (request == null + || !request.hasExpectedLease() + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Malformed Account admission lease read request"); + } + + var evidence = + AccountGameplayAdmissionLeaseWireCodec.parseReference(request.getExpectedLease()); + if (!request.getRequestId().equals(evidence.carrier().get("requestId"))) { + throw new IllegalArgumentException("Malformed Account admission lease read request"); + } + if (!namespace.equals(evidence.carrier().get("targetNamespace")) + || !peer.uri().equals(evidence.carrier().get("callerWorkload"))) { + throw Status.PERMISSION_DENIED + .withDescription("Admission lease caller mismatch") + .asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Owned Account transaction required") + .asRuntimeException(); + } + + return Objects.requireNonNull( + transaction.execute( + ignored -> { + AccountGameplayAdmissionLeaseOperation stored; + try { + stored = + repository + .readExact(evidence) + .orElseThrow(AccountGameplayAdmissionReadOwner::unresolved); + } catch (AccountGameplayAdmissionLeaseRepository.IdentityConflictException failure) { + throw unresolved(); + } catch (IllegalArgumentException failure) { + // The request was already parsed; a parser failure here is corrupt stored evidence. + throw unresolved(); + } + if (stored.state() == State.COMMITTED) throw unresolved(); + return stored; + })); + } + + private static RuntimeException unresolved() { + return Status.FAILED_PRECONDITION + .withDescription("Exact Account admission lease readback unavailable") + .asRuntimeException(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcService.java index 063e68c4a0..a7e1ad4732 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcService.java @@ -8,19 +8,92 @@ import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseResponse; import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseServiceGrpc; import net.firedevops.firemud.account.v1.GameplayAdmissionLeaseState; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseResponse; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionAbortOwner; import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionAbortOwner.AbortDeniedException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionReadOwner; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; import net.firedevops.firemud.shared.v1.ErrorDetail; -/** Unregistered abort-only transport. Every other inherited method remains unimplemented. */ +/** Unregistered negative-state read and abort transport; positive admission methods stay absent. */ public final class AccountGameplayAdmissionLeaseGrpcService extends AccountGameplayAdmissionLeaseServiceGrpc.AccountGameplayAdmissionLeaseServiceImplBase { private final AccountGameplayAdmissionAbortOwner owner; + private final AccountGameplayAdmissionReadOwner readOwner; - public AccountGameplayAdmissionLeaseGrpcService(AccountGameplayAdmissionAbortOwner owner) { + public AccountGameplayAdmissionLeaseGrpcService( + AccountGameplayAdmissionAbortOwner owner, AccountGameplayAdmissionReadOwner readOwner) { this.owner = Objects.requireNonNull(owner); + this.readOwner = Objects.requireNonNull(readOwner); + } + + @Override + public void readGameplayAdmissionLease( + ReadGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + ReadGameplayAdmissionLeaseResponse response; + try { + var read = readOwner.read(request); + if (read.state() == State.COMMITTED) + throw Status.FAILED_PRECONDITION + .withDescription("Exact Account admission lease readback unavailable") + .asRuntimeException(); + response = + ReadGameplayAdmissionLeaseResponse.newBuilder() + .setOperation( + AccountGameplayAdmissionLeaseWireCodec.encodeOperation( + read.evidence(), + read.state() == State.PENDING + ? GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_PENDING + : GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED, + read.bindingDecisionId(), + read.orphanCleanupId())) + .build(); + } catch (StatusRuntimeException failure) { + observer.onError(sanitizedReadFailure(failure)); + return; + } catch (IllegalArgumentException failure) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Malformed Account admission lease read request") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Account admission lease read unavailable") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static StatusRuntimeException sanitizedReadFailure(StatusRuntimeException failure) { + return switch (Status.fromThrowable(failure).getCode()) { + case UNAUTHENTICATED -> + Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + case PERMISSION_DENIED -> + Status.PERMISSION_DENIED + .withDescription("Game Session workload required") + .asRuntimeException(); + case INVALID_ARGUMENT -> + Status.INVALID_ARGUMENT + .withDescription("Malformed Account admission lease read request") + .asRuntimeException(); + case FAILED_PRECONDITION -> + Status.FAILED_PRECONDITION + .withDescription("Exact Account admission lease readback unavailable") + .asRuntimeException(); + default -> + Status.UNAVAILABLE + .withDescription("Account admission lease read unavailable") + .asRuntimeException(); + }; } @Override diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index dcf719d48f..f3d5460223 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -4,6 +4,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.time.Instant; import java.util.LinkedHashMap; import java.util.List; @@ -16,6 +18,7 @@ import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; import net.firedevops.firemud.accountservice.entity.Account; @@ -60,9 +63,9 @@ void actualAbortOwnerRecoversLostResponseAndRetainsOriginalDecisionAndCleanup() var context = context(null); var original = pending(context, account(context)); var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); - var owner = - new AccountGameplayAdmissionAbortOwner( - repository, new DataSourceTransactionManager(context.dataSource()), "test"); + var transactionManager = new DataSourceTransactionManager(context.dataSource()); + var owner = new AccountGameplayAdmissionAbortOwner(repository, transactionManager, "test"); + var readOwner = new AccountGameplayAdmissionReadOwner(repository, transactionManager, "test"); UUID decision = UUID.randomUUID(); var request = AbortGameplayAdmissionLeaseRequest.newBuilder() @@ -72,6 +75,15 @@ void actualAbortOwnerRecoversLostResponseAndRetainsOriginalDecisionAndCleanup() // The trusted context is synthetic: this exercises real SQL ownership, never actual mTLS. syntheticAbortPeer().call(() -> owner.abort(request)); // Discard the first response. var stored = tx(context, () -> repository.readExact(original).orElseThrow()); + var recoveredAfterLostAbortAck = + syntheticReadPeer().call(() -> readOwner.read(readRequest(original))); + assertThat(recoveredAfterLostAbortAck).isEqualTo(stored); + assertThat(recoveredAfterLostAbortAck.state()).isEqualTo(State.ABORTED); + assertThat(recoveredAfterLostAbortAck.evidence().canonicalJson()) + .isEqualTo(original.canonicalJson()); + assertThat(recoveredAfterLostAbortAck.evidence().sha256()).isEqualTo(original.sha256()); + assertThat(recoveredAfterLostAbortAck.orphanCleanupId()).isEqualTo(stored.orphanCleanupId()); + assertThat(recoveredAfterLostAbortAck.hasPendingOrphanCleanup()).isTrue(); var replay = syntheticAbortPeer().call(() -> owner.abort(request)); assertThat(replay).isEqualTo(stored); assertThat(replay.state()).isEqualTo(State.ABORTED); @@ -196,6 +208,38 @@ void concurrentActualAbortOwnersRetainOneCleanupAndDenySubstitutionOrCommittedLe assertThat(committed.orphanCleanupId()).isNull(); } + @Test + void exactReadRejectsMissingRawCommittedAndMismatchedOperations() { + var context = context(null); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var readOwner = + new AccountGameplayAdmissionReadOwner( + repository, new DataSourceTransactionManager(context.dataSource()), "test"); + + var allocation = + tx(context, () -> repository.allocate(account, UUID.randomUUID(), UUID.randomUUID())); + var missing = evidence(allocation); + assertFailedExactRead(readOwner, missing); + assertThat(tx(context, () -> repository.readExact(missing))).isEmpty(); + + var original = pending(context, account); + var changedCarrier = new LinkedHashMap<>(original.carrier()); + changedCarrier.put( + "leaseFence", Long.toString(Long.parseLong((String) changedCarrier.get("leaseFence")) + 1)); + assertFailedExactRead( + readOwner, AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier)); + assertThat(tx(context, () -> repository.readExact(original).orElseThrow().state())) + .isEqualTo(State.PENDING); + + var committedEvidence = pending(context, account); + var committed = + tx(context, () -> repository.recordCommitted(committedEvidence, UUID.randomUUID())); + assertThat(committed.state()).isEqualTo(State.COMMITTED); + assertFailedExactRead(readOwner, committedEvidence); + assertThat(tx(context, () -> repository.readExact(committedEvidence))).contains(committed); + } + /** Synthetic trusted caller only; the existing carriers remain fabricated storage fixtures. */ private static io.grpc.Context syntheticAbortPeer() { return io.grpc.Context.current() @@ -205,6 +249,33 @@ private static io.grpc.Context syntheticAbortPeer() { .orElseThrow()); } + /** Synthetic peer only; neither this identity nor the fabricated carrier proves mTLS. */ + private static io.grpc.Context syntheticReadPeer() { + return io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") + .orElseThrow()); + } + + private static ReadGameplayAdmissionLeaseRequest readRequest( + AccountGameplayAdmissionLeaseEvidence evidence) { + return ReadGameplayAdmissionLeaseRequest.newBuilder() + .setRequestId((String) evidence.carrier().get("requestId")) + .setExpectedLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(evidence)) + .build(); + } + + private static void assertFailedExactRead( + AccountGameplayAdmissionReadOwner owner, AccountGameplayAdmissionLeaseEvidence evidence) { + assertThatThrownBy(() -> syntheticReadPeer().call(() -> owner.read(readRequest(evidence)))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + @Test void lostResponseRecoveryUsesOriginalRequestWithoutReconstructingServerLeaseIdentity() { var context = context(null); @@ -514,13 +585,22 @@ void relaxedAbortShapeStillRejectsMissingCleanupAndCommittedWithoutDecision() { } @Test - void expiredPendingCannotCommitOrRenewButKeepsExactReadbackAndCanAbort() { + void expiredPendingCannotCommitOrRenewButKeepsExactReadbackAndCanAbort() throws Exception { var context = context(null); UUID account = account(context); var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); var evidence = pending(context, account); tx(context, () -> context.dsl().fetchOne("SELECT pg_sleep(16)")); assertThat(tx(context, () -> repository.beginPending(evidence)).evidence()).isEqualTo(evidence); + var readOwner = + new AccountGameplayAdmissionReadOwner( + repository, new DataSourceTransactionManager(context.dataSource()), "test"); + var expiredRead = syntheticReadPeer().call(() -> readOwner.read(readRequest(evidence))); + assertThat(expiredRead.state()).isEqualTo(State.PENDING); + assertThat(expiredRead.evidence().canonicalJson()).isEqualTo(evidence.canonicalJson()); + assertThat(expiredRead.evidence().sha256()).isEqualTo(evidence.sha256()); + assertThat(expiredRead.bindingDecisionId()).isNull(); + assertThat(expiredRead.orphanCleanupId()).isNull(); assertThatThrownBy( () -> tx(context, () -> repository.recordCommitted(evidence, UUID.randomUUID()))) .hasMessageContaining("deadline expired"); @@ -531,9 +611,15 @@ void expiredPendingCannotCommitOrRenewButKeepsExactReadbackAndCanAbort() { var renewed = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed); assertThatThrownBy(() -> tx(context, () -> repository.beginPending(renewed))) .hasMessageContaining("identity conflict"); - assertThat( - tx(context, () -> repository.recordAborted(evidence, null, UUID.randomUUID())).state()) - .isEqualTo(State.ABORTED); + var aborted = tx(context, () -> repository.recordAborted(evidence, null, UUID.randomUUID())); + assertThat(aborted.state()).isEqualTo(State.ABORTED); + var expiredAbortRead = syntheticReadPeer().call(() -> readOwner.read(readRequest(evidence))); + assertThat(expiredAbortRead).isEqualTo(aborted); + assertThat(expiredAbortRead.evidence().canonicalJson()).isEqualTo(evidence.canonicalJson()); + assertThat(expiredAbortRead.evidence().sha256()).isEqualTo(evidence.sha256()); + assertThat(expiredAbortRead.bindingDecisionId()).isNull(); + assertThat(expiredAbortRead.orphanCleanupId()).isEqualTo(aborted.orphanCleanupId()); + assertThat(expiredAbortRead.hasPendingOrphanCleanup()).isTrue(); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwnerTest.java new file mode 100644 index 0000000000..4d05e73c46 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwnerTest.java @@ -0,0 +1,203 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Owner/transaction doubles and fabricated carriers only; no current source authority is proven. + */ +class AccountGameplayAdmissionReadOwnerTest { + private final AccountGameplayAdmissionLeaseRepository repository = + mock(AccountGameplayAdmissionLeaseRepository.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final TransactionStatus transactionStatus = mock(TransactionStatus.class); + private final AccountGameplayAdmissionReadOwner owner = + new AccountGameplayAdmissionReadOwner(repository, manager, "test"); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void returnsOnlyExactPendingOrAbortedHistoricalEvidenceInOwnedSerializableTransactions() + throws Exception { + var original = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID cleanup = UUID.randomUUID(); + var pending = new AccountGameplayAdmissionLeaseOperation(original, State.PENDING, null, null); + var aborted = + new AccountGameplayAdmissionLeaseOperation(original, State.ABORTED, null, cleanup); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.readExact(original)).thenReturn(Optional.of(pending), Optional.of(aborted)); + + var first = peer().call(() -> owner.read(request(original))); + var second = peer().call(() -> owner.read(request(original))); + + assertThat(first).isSameAs(pending); + assertThat(second).isSameAs(aborted); + assertThat(first.evidence().canonicalJson()).isEqualTo(original.canonicalJson()); + assertThat(first.evidence().sha256()).isEqualTo(original.sha256()); + assertThat(first.state()).isEqualTo(State.PENDING); + assertThat(second.state()).isEqualTo(State.ABORTED); + assertThat(second.bindingDecisionId()).isNull(); + assertThat(second.orphanCleanupId()).isEqualTo(cleanup); + assertThat(second.hasPendingOrphanCleanup()).isTrue(); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(manager, times(2)).getTransaction(definition.capture()); + assertThat(definition.getAllValues()) + .allSatisfy( + value -> { + assertThat(value.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(value.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(value.isReadOnly()).isFalse(); + }); + verify(manager, times(2)).commit(transactionStatus); + verify(repository, times(2)).readExact(original); + verify(repository, never()).recordCommitted(any(), any()); + verify(repository, never()).recordAborted(any(), any(), any()); + } + + @Test + void rejectsMissingRowsCommittedStorageAndFullCarrierMismatchAsUnresolved() { + var original = AccountGameplayAdmissionAbortOwnerTest.fixture(); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.readExact(original)) + .thenReturn(Optional.empty()) + .thenReturn( + Optional.of( + new AccountGameplayAdmissionLeaseOperation( + original, State.COMMITTED, UUID.randomUUID(), null))) + .thenThrow(new AccountGameplayAdmissionLeaseRepository.IdentityConflictException()); + var changedCarrier = new LinkedHashMap<>(original.carrier()); + changedCarrier.put("leaseFence", "2"); + var changed = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + when(repository.readExact(changed)) + .thenThrow(new AccountGameplayAdmissionLeaseRepository.IdentityConflictException()); + + for (int attempt = 0; attempt < 3; attempt++) { + assertStatus( + Status.Code.FAILED_PRECONDITION, () -> peer().call(() -> owner.read(request(original)))); + } + assertStatus( + Status.Code.FAILED_PRECONDITION, () -> peer().call(() -> owner.read(request(changed)))); + verify(manager, times(4)).rollback(transactionStatus); + } + + @Test + void wrongPeerAndOriginalCallerNamespaceAreRejectedBeforeTransactionOrRepository() { + var original = AccountGameplayAdmissionAbortOwnerTest.fixture(); + var changedCarrier = new LinkedHashMap<>(original.carrier()); + changedCarrier.put("targetNamespace", "other"); + changedCarrier.put("callerWorkload", "spiffe://firemud/ns/other/sa/game-session-service"); + var otherNamespace = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + + assertStatus(Status.Code.UNAUTHENTICATED, () -> owner.read(request(original))); + for (String uri : + List.of( + "spiffe://firemud/ns/test/sa/account-service", + "spiffe://firemud/ns/other/sa/game-session-service")) { + assertStatus( + Status.Code.PERMISSION_DENIED, () -> peer(uri).call(() -> owner.read(request(original)))); + } + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> peer().call(() -> owner.read(request(otherNamespace)))); + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsMalformedEnvelopeAndOuterRequestMismatchBeforeTransactionOrRepository() { + var original = AccountGameplayAdmissionAbortOwnerTest.fixture(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var reference = AccountGameplayAdmissionLeaseWireCodec.encodeReference(original); + for (var request : + List.of( + ReadGameplayAdmissionLeaseRequest.getDefaultInstance(), + request(original).toBuilder().setUnknownFields(unknown).build(), + request(original).toBuilder() + .setExpectedLease(reference.toBuilder().setUnknownFields(unknown)) + .build(), + request(original).toBuilder().setRequestId(UUID.randomUUID().toString()).build())) { + assertThatThrownBy(() -> peer().call(() -> owner.read(request))) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsAmbientTransactionAndSynchronizationBeforeOpeningOwnedTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> + peer() + .call(() -> owner.read(request(AccountGameplayAdmissionAbortOwnerTest.fixture())))); + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.initSynchronization(); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> + peer() + .call(() -> owner.read(request(AccountGameplayAdmissionAbortOwnerTest.fixture())))); + verifyNoInteractions(repository, manager); + } + + private static ReadGameplayAdmissionLeaseRequest request( + AccountGameplayAdmissionLeaseEvidence evidence) { + return ReadGameplayAdmissionLeaseRequest.newBuilder() + .setRequestId((String) evidence.carrier().get("requestId")) + .setExpectedLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(evidence)) + .build(); + } + + private static void assertStatus(Status.Code expected, ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static Context peer() { + return peer("spiffe://firemud/ns/test/sa/game-session-service"); + } + + private static Context peer(String uri) { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcServiceTest.java index 3fcef5a7c5..15706e3e31 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcServiceTest.java @@ -32,6 +32,7 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionAbortOwner; import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionAbortOwnerTest; import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionLeaseRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionReadOwner; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.junit.jupiter.api.Test; @@ -49,7 +50,7 @@ void encodesExactAbortedCarrierAndUnknownDecisionOnly() { new AccountGameplayAdmissionLeaseOperation( AccountGameplayAdmissionAbortOwnerTest.fixture(), State.ABORTED, null, cleanup)); var observer = new Capture(); - new AccountGameplayAdmissionLeaseGrpcService(owner) + service(owner) .abortGameplayAdmissionLease(AccountGameplayAdmissionAbortOwnerTest.request(), observer); assertThat(observer.failure).isNull(); assertThat(observer.completed).isTrue(); @@ -74,7 +75,7 @@ void committedCannotEscapeAbortTransport() { UUID.randomUUID(), null)); var observer = new Capture(); - new AccountGameplayAdmissionLeaseGrpcService(owner) + service(owner) .abortGameplayAdmissionLease(AccountGameplayAdmissionAbortOwnerTest.request(), observer); assertFailure(observer, Status.Code.UNAVAILABLE); } @@ -95,7 +96,8 @@ void actualOwnerDomainDenialsAreTypedButStorageFailuresAreUnavailable() { when(manager.getTransaction(any())).thenReturn(mock(TransactionStatus.class)); var service = new AccountGameplayAdmissionLeaseGrpcService( - new AccountGameplayAdmissionAbortOwner(repository, manager, "test")); + new AccountGameplayAdmissionAbortOwner(repository, manager, "test"), + mock(AccountGameplayAdmissionReadOwner.class)); UUID decision = UUID.randomUUID(); var aborted = new AccountGameplayAdmissionLeaseOperation( @@ -139,7 +141,8 @@ void actualOwnerDomainDenialsAreTypedButStorageFailuresAreUnavailable() { var unavailable = new Capture(); var failingService = new AccountGameplayAdmissionLeaseGrpcService( - new AccountGameplayAdmissionAbortOwner(failingRepository, manager, "test")); + new AccountGameplayAdmissionAbortOwner(failingRepository, manager, "test"), + mock(AccountGameplayAdmissionReadOwner.class)); peer() .run( () -> @@ -155,7 +158,8 @@ void rejectsMalformedOuterReferenceAndClosedJsonBeforeSql() { var manager = mock(PlatformTransactionManager.class); var service = new AccountGameplayAdmissionLeaseGrpcService( - new AccountGameplayAdmissionAbortOwner(repository, manager, "test")); + new AccountGameplayAdmissionAbortOwner(repository, manager, "test"), + mock(AccountGameplayAdmissionReadOwner.class)); var unknown = UnknownFieldSet.newBuilder() .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) @@ -198,7 +202,7 @@ void rejectsMalformedOuterReferenceAndClosedJsonBeforeSql() { @Test void returnsBoundedRedactedErrorsWithoutSuccessfulOutcome() { var owner = mock(AccountGameplayAdmissionAbortOwner.class); - var service = new AccountGameplayAdmissionLeaseGrpcService(owner); + var service = service(owner); for (var failure : List.of( new IllegalArgumentException("secret evidence"), @@ -217,24 +221,138 @@ void returnsBoundedRedactedErrorsWithoutSuccessfulOutcome() { } @Test - void everyOtherMethodRemainsUnimplemented() { + void acquireFinalizeAndReconcileRemainUnimplemented() { var owner = mock(AccountGameplayAdmissionAbortOwner.class); - var service = new AccountGameplayAdmissionLeaseGrpcService(owner); + var readOwner = mock(AccountGameplayAdmissionReadOwner.class); + var service = new AccountGameplayAdmissionLeaseGrpcService(owner, readOwner); var acquire = new Capture(); var finalize = new Capture(); - var read = new Capture(); var reconcile = new Capture(); service.acquirePublicGameplayAdmissionLease( AcquirePublicGameplayAdmissionLeaseRequest.getDefaultInstance(), acquire); service.finalizeGameplayAdmissionLease( FinalizeGameplayAdmissionLeaseRequest.getDefaultInstance(), finalize); - service.readGameplayAdmissionLease( - ReadGameplayAdmissionLeaseRequest.getDefaultInstance(), read); service.reconcileGameplayAdmissionLease( ReconcileGameplayAdmissionLeaseRequest.getDefaultInstance(), reconcile); - for (var observer : List.of(acquire, finalize, read, reconcile)) + for (var observer : List.of(acquire, finalize, reconcile)) assertFailure(observer, Status.Code.UNIMPLEMENTED); - verifyNoInteractions(owner); + verifyNoInteractions(owner, readOwner); + } + + @Test + void encodesExactPendingAndAbortedReadbackWithoutFabricatingCleanupCompletion() { + var abortOwner = mock(AccountGameplayAdmissionAbortOwner.class); + var readOwner = mock(AccountGameplayAdmissionReadOwner.class); + var service = new AccountGameplayAdmissionLeaseGrpcService(abortOwner, readOwner); + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + var request = readRequest(evidence); + UUID cleanup = UUID.randomUUID(); + for (var operation : + List.of( + new AccountGameplayAdmissionLeaseOperation(evidence, State.PENDING, null, null), + new AccountGameplayAdmissionLeaseOperation(evidence, State.ABORTED, null, cleanup))) { + when(readOwner.read(request)).thenReturn(operation); + var observer = new Capture(); + service.readGameplayAdmissionLease(request, observer); + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.hasOperation()).isTrue(); + assertThat(observer.value.hasNotObserved()).isFalse(); + var encoded = observer.value.getOperation(); + assertThat(AccountGameplayAdmissionLeaseWireCodec.validateOperation(encoded)) + .isEqualTo(evidence); + assertThat(encoded.getLease().getEvidenceCanonicalJson()) + .isEqualTo(com.google.protobuf.ByteString.copyFromUtf8(evidence.canonicalJson())); + assertThat(encoded.getLease().getEvidenceSha256()).isEqualTo(evidence.sha256()); + if (operation.state() == State.PENDING) { + assertThat(encoded.getState()) + .isEqualTo(GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_PENDING); + assertThat(encoded.hasBindingDecisionId()).isFalse(); + assertThat(encoded.hasOrphanCleanupId()).isFalse(); + assertThat(encoded.getPendingOrphanCleanup()).isFalse(); + } else { + assertThat(encoded.getState()) + .isEqualTo(GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED); + assertThat(encoded.hasBindingDecisionId()).isFalse(); + assertThat(encoded.getOrphanCleanupId()).isEqualTo(cleanup.toString()); + assertThat(encoded.getPendingOrphanCleanup()).isTrue(); + } + } + verifyNoInteractions(abortOwner); + } + + @Test + void readFailuresUseRedactedNonOkStatusAndNeverReturnSuccess() { + var abortOwner = mock(AccountGameplayAdmissionAbortOwner.class); + var readOwner = mock(AccountGameplayAdmissionReadOwner.class); + var service = new AccountGameplayAdmissionLeaseGrpcService(abortOwner, readOwner); + var request = readRequest(AccountGameplayAdmissionAbortOwnerTest.fixture()); + for (var failure : + List.of( + Status.FAILED_PRECONDITION.withDescription("secret mismatch").asRuntimeException(), + Status.UNAVAILABLE.withDescription("secret storage").asRuntimeException())) { + doThrow(failure).when(readOwner).read(request); + var observer = new Capture(); + service.readGameplayAdmissionLease(request, observer); + assertFailure(observer, Status.fromThrowable(failure).getCode()); + assertThat(Status.fromThrowable(observer.failure).getDescription()).doesNotContain("secret"); + assertThat(observer.failure.getCause()).isNull(); + } + doThrow(new IllegalStateException("secret storage")).when(readOwner).read(request); + var unavailable = new Capture(); + service.readGameplayAdmissionLease(request, unavailable); + assertFailure(unavailable, Status.Code.UNAVAILABLE); + assertThat(Status.fromThrowable(unavailable.failure).getDescription()).doesNotContain("secret"); + + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + var committedReadOwner = mock(AccountGameplayAdmissionReadOwner.class); + var committedService = + new AccountGameplayAdmissionLeaseGrpcService(abortOwner, committedReadOwner); + when(committedReadOwner.read(request)) + .thenReturn( + new AccountGameplayAdmissionLeaseOperation( + evidence, State.COMMITTED, UUID.randomUUID(), null)); + var committed = new Capture(); + committedService.readGameplayAdmissionLease(request, committed); + assertFailure(committed, Status.Code.FAILED_PRECONDITION); + assertThat(Status.fromThrowable(committed.failure).getDescription()).doesNotContain("secret"); + } + + @Test + void mapsMalformedReadEnvelopeToInvalidArgumentBeforeSql() { + var repository = mock(AccountGameplayAdmissionLeaseRepository.class); + var manager = mock(PlatformTransactionManager.class); + var readOwner = new AccountGameplayAdmissionReadOwner(repository, manager, "test"); + var service = + new AccountGameplayAdmissionLeaseGrpcService( + mock(AccountGameplayAdmissionAbortOwner.class), readOwner); + var observer = new Capture(); + + peer() + .run( + () -> + service.readGameplayAdmissionLease( + ReadGameplayAdmissionLeaseRequest.getDefaultInstance(), observer)); + + assertFailure(observer, Status.Code.INVALID_ARGUMENT); + assertThat(Status.fromThrowable(observer.failure).getDescription()) + .isEqualTo("Malformed Account admission lease read request"); + verifyNoInteractions(repository, manager); + } + + private static AccountGameplayAdmissionLeaseGrpcService service( + AccountGameplayAdmissionAbortOwner abortOwner) { + return new AccountGameplayAdmissionLeaseGrpcService( + abortOwner, mock(AccountGameplayAdmissionReadOwner.class)); + } + + private static ReadGameplayAdmissionLeaseRequest readRequest( + net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence + evidence) { + return ReadGameplayAdmissionLeaseRequest.newBuilder() + .setRequestId((String) evidence.carrier().get("requestId")) + .setExpectedLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(evidence)) + .build(); } private static Context peer() { From 28a1ef9a53be8c8423f34738d05fe3509a61dc57 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 13:40:13 +1300 Subject: [PATCH 12/16] Prepare exact Account admission COMMIT durability confirmation --- .../account-service/api-contracts.md | 6 + .../account-service/runtime-and-data.md | 2 + .../system-architecture-session-behavior.md | 4 + .../player-access-and-session.md | 2 + ...ntGameplayAdmissionCommitConfirmation.java | 116 +++++ ...eplayAdmissionCommitConfirmationOwner.java | 150 ++++++ ...AdmissionCommitConfirmationRepository.java | 113 ++++ ..._admission_durable_commit_confirmation.sql | 312 +++++++++++ ...issionLeasePersistenceIntegrationTest.java | 485 ++++++++++++++++++ ...yAdmissionCommitConfirmationOwnerTest.java | 328 ++++++++++++ ...ssionCommitConfirmationRepositoryTest.java | 254 +++++++++ 11 files changed, 1772 insertions(+) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionCommitConfirmation.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java create mode 100644 services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 5a226f3461..2ba10c807e 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -281,6 +281,12 @@ The canonical membership, entitlement response shape, freshness, and sequence co - `GetTenantEntitlementsTenant` and `GetTenantEntitlementsCrossTenantSupportSafe` remain separate caller-bound and redacted support-safe API variants. They must not be multiplexed with the internal runtime surface. - Internal callers must treat missing required owner fields as contract failure and fail closed; Account's REST/OpenAPI and gRPC/proto sources remain the executable API authorities. +## Admission-Lease Confirmation Preparation + +The admission owner remains unregistered and non-admitting. Its cancellation and exact negative-state readback methods accept only the original same-namespace Game Session workload and complete unchanged lease evidence; `ReadGameplayAdmissionLease` currently requires `expected_lease` and returns only `PENDING` or `ABORTED`, not `not_observed` or raw storage `COMMITTED`. The positive acquire/finalize/read/reconcile surface is not enabled. The canonical expiry and confirmation requirement is owned by [Session Behavior](../../system-architecture-session-behavior.md#admission-lease-durable-confirmation). + +The separate Account-local temporal confirmation preparation stamps the actual finalization transaction and derives immutable proof from independent committed operation readback, ordered PostgreSQL WAL insertion/flush coverage on one primary, and a subsequent conservatively rounded database-time bound before the original expiry. It requires durable storage settings; unavailable or uncovered WAL, same-transaction finalization and late observation remain denied. Receipt creation must commit before a new transaction independently proves and reads the durable receipt; caller-supplied bounds and bare LSNs carried across a reconnect cannot substitute. Original operation, lease, digest, decision and deadline remain unchanged. This is not an authenticated positive admission result, a current restriction-source producer, Game Session installation proof or completed cleanup. Implementation and executed versus unavailable proof belong to the [Account admission tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-admission-lease-prerequisite). + ## Subject-Binding Rules (Normative) - `GET /tenants/{tenantId}/profiles/{accountId}` and `PUT /tenants/{tenantId}/profiles/{accountId}` are tenant-qualified, caller-subject-bound profile routes. They require live membership and the path `accountId` must equal the authenticated account; global roles do not broaden these routes. Cross-account moderation/support views require separate minimized contracts. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index f926a712b5..5c897e799b 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +The admission prerequisite also prepares a separate, unregistered PostgreSQL durability-confirmation owner. It preserves the original finalization identity and deadline, derives temporal proof inside Account storage, and independently reads the committed receipt before returning it. This is only the local implementation consequence of [Session Behavior's durable-confirmation contract](../../system-architecture-session-behavior.md#admission-lease-durable-confirmation), not complete current-source finalization or admission permission. Execution evidence and remaining activation gates belong to the [Account admission tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-admission-lease-prerequisite). + The admission transport also prepares unregistered exact negative-state readback and cancellation. Readback requires the original complete lease and authenticated same-namespace Game Session caller, returns only retained `PENDING` or `ABORTED` evidence and preserves its original expiry and cleanup identity. Missing, conflicting or raw storage `COMMITTED` state remains denied; historical negative readback is not current authorization, cleanup completion or an enabled RPC. Detailed proof and the still-missing positive owner belong to the [Account admission tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-admission-lease-prerequisite). The admission prerequisite prepares an unregistered Account client for the distinct [World player-admission serving hold](../world-management-service/api-contracts.md#player-admission-serving-hold). It uses file-backed workload mTLS, verifies the exact same-namespace World server before releasing request evidence, and compares the original lease, target, expected World lifecycle epoch/row version, response correlation, and complete closed hold evidence. Calls run outside Account transactions and synchronization; absent or inconsistent readback remains unresolved. The client does not finalize Account authority, release a World hold, register a runtime RPC or admit gameplay. Executed proof and the remaining current-source/physical-COMMIT gates belong to the [Account admission tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-admission-lease-prerequisite). diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index cb1c1b4ef8..5a961173ad 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -276,6 +276,10 @@ On reconnect/resume (after the client re-`LOGIN`s and re-`PLAY`s), Game Session For every new binding or reconnect/resume, Account issues an exact-binding admission lease only after validating current lifecycle, billing, `authorityTuple`, `issuanceFence`, the exact unchanged `membershipBaseline`, the complete `outboxCheckpoints` set, token-identity fence, and security authority; reconnect continuity uses the exact-resume-episode `resumeActivationLease` specialization. Each lease has a unique lease ID, a monotonic fence, the immutable `authorityTuple`, `issuanceFence`, unchanged `membershipBaseline`, complete `outboxCheckpoints` set, and a bounded absolute expiry no longer than the admission SLA; the lease identity and request digest cover every one of those exact carriers, and the lease cannot be renewed to extend an admission attempt. Game Session's binding CAS includes and independently exact-compares the complete tuple, `issuanceFence`, unchanged baseline, complete checkpoint set, lease fence, and cutoff evidence and may publish only a provisional record. For reconnect/resume that record is `RESUME_PENDING`; it is never admissible, resumable, or takeover-eligible until Account durably finalizes the exact lease, binding decision, authority tuple, baseline, checkpoint set, fence, and resume-episode identity as `COMMITTED`. Account finalization, abort, reconciliation, retries, and replay comparisons are idempotent by lease ID and request ID and require the same unchanged baseline and digest; a missing, extra, scalarized, differently keyed, or changed baseline member fails closed rather than replaying or committing. Game Session remains the owner of the binding CAS and indexes. If an issuer, account, tenant, membership, grant, billing, token-identity, or security cutoff fences the lease before finalization, the local CAS or late finalization fails closed and the provisional record is removed or remains blocked. If finalization commits first, the binding was admitted under the then-current authority and a later cutoff follows the bounded active-revocation path. If the binding CAS or response is lost, Account reconciliation emits durable orphan evidence and a cleanup request; Gateway and Game Session perform fenced edge and gameplay-binding/index cleanup, respectively. No service infers admission from local presence, and Account does not physically remove Game Session state. Missing, expired, fenced, ambiguous, or uncommitted lease state never admits a binding. This is an ordered idempotent cross-service protocol, not a cross-store atomic transaction. +### Admission-Lease Durable Confirmation + +Account may establish a separate immutable finalization confirmation, but it must prove durable completion of the original finalization COMMIT before a subsequently observed database-time upper bound that is strictly earlier than the lease's original absolute expiry. A visible row alone, statement time, pre-COMMIT check, transaction timeout or local return time is not that proof. Confirmation binds the complete original lease identity/digest and finalization decision without rewriting the operation, response evidence or expiry. Missing, late or ambiguous confirmation remains non-admitting; a new deadline or replacement attempt cannot repair the original attempt. Exact retained confirmation readback preserves its original bound even when performed later, but grants no fresh admission or bypass of current authority, installation or cleanup checks. A temporal storage receipt alone does not establish that the original finalizer authenticated and validated every applicable authority source. Account owns the protected confirmation/readback implementation and its durability proof; Game Session retains binding installation and cleanup ownership. + The `resumeActivationLease` is a durable activation gate, not a grace authorization. A previously accepted binding-continuity bundle may supply only the entitlement input under the bounded exception below; it cannot replace current Account validation for any other predicate, the committed lease, or the fresh delegation JWT. Resume validation must not depend on the previous private player-delegation token remaining valid. After a fresh successful `LOGIN`, Game Session must obtain current Account validation, durably commit the exact `resumeActivationLease`, and obtain a fresh `game-session-account-delegation` token issued by Account; Game Session never mints this token and Account is the sole JWT issuer. Only after the exact activation lease is `COMMITTED` may Game Session atomically replace stored `authTokenHash`, `authTokenIssuedAt`, `authTokenExpiresAt`, `tokenGeneration`, `issuanceFence`, and `rebindHandle`, replace the complete `authorityTuple`, unchanged `membershipBaseline`, and `outboxCheckpoints` set, consume a current disconnection episode that has not been terminalized `auth-revoked`, and transition the binding from `RESUME_PENDING` to admitted. An episode terminalized `auth-revoked` is permanently excluded: it is never restored or consumed, and fresh `LOGIN` plus `PLAY` must establish a new binding. A binding CAS that loses the lease fence or otherwise fails must not leave the replacement token usable; Game Session must invoke Account's idempotent retire/abort path for the orphan token before reporting resume failure. If Account cannot validate the current evidence, commit the activation lease, or issue the fresh delegation JWT, resume returns `AUTH_UNAVAILABLE`; a reachable negative or mismatched result remains a denial/revocation rather than a local fallback. The new token's expiration, complete authority tuple, unchanged baseline, complete checkpoint set, issuance fence, and replacement rebind handle must be persisted before resumed backend calls use the replacement. Resume is rejected for any failed validation above, including subject mismatch, stale or lost gameplay membership or grant, expired or non-resumable gameplay state, an expired resume window, a changed uniqueness key, or revoked issuer, account, tenant, cutoff, or membership authority state. The fresh token's validity remains bounded by its own `exp`; obtaining it does not extend `continuityBindingExpiresAt` or the current episode's `resumeDeadline`. 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 320f07aea8..6fac3cbbd6 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 ### Account Admission-Lease Prerequisite +The separate unregistered durability-confirmation preparation adds V90's database-stamped top-level finalization transaction identity and immutable exact-bound receipt. An independent committed operation, primary database with `fsync` enabled, ordered WAL-insert/flush coverage and subsequently rounded-up database clock establish a bound strictly before the original expiry. Bounded polling against one fixed WAL fence creates no marker, forces no flush and renews no deadline. The protected same-namespace Game Session owner commits receipt creation, then independently commits exact durable readback before returning the temporal value. Retained unstamped commits, rollback, self/subtransaction visibility, late or uncovered proof, changed identity and ambiguous readback remain denied. A retained receipt can be recovered later without rewriting its original evidence; it proves no current authority, World release, Game Session installation or gameplay admission. Seven additive PostgreSQL definitions preserve all eleven existing lease cases and cover real Java-owner/SQL timely and lost-response receipt recovery, late physical COMMIT, same-transaction rejection, retained/rolled-back denial, forged proof and immutability, uncommitted receipt rejection and concurrent exact retention. Local full Account checks, generation, formatting, static analysis, integration-source compilation, boot packaging and documentation checks passed in 2m18s: 1,170 unit and seven non-database integration cases executed, with three unit skips and 158 PostgreSQL skips, zero failures/errors. All eight confirmation-owner and four repository unit cases passed; all eighteen lease PostgreSQL definitions compiled but skipped. Flyway sanity passed twelve sets and 168 versioned files. Physical V90 execution, deterministic uncovered asynchronous WAL, recovery/disabled-fsync and remote-failover durability remain unproved. The preceding exact `17e8f609dcbe4ef4dc096b8bfe82557a68bbe9ef` checkpoint has successful [CI run 37706751965](https://github.com/benhook1013/FireMUD/actions/runs/37706751965) on composed merge `cd66dcf2618404caddba413731d50a32748ed705` against base `7985e8a6f6354587f5c01649ede3d0cecde9fde2`: 1,320 Account cases executed, seven skipped and zero failures/errors. All eleven then-existing lease PostgreSQL cases, six first-JOIN PostgreSQL cases and five World-client mTLS cases executed; that older proof does not establish V90. Acquire/finalize/reconcile RPCs remain unimplemented, raw storage `COMMITTED` remains denied by the negative-state read adapter, and the complete current-restriction producer and Game Session installation/cleanup are still required. + The isolated Account candidate adds an unregistered same-transaction source reader for fresh Game Design tenant provenance and the existing `NON_PAID_DEMO` entitlement class. It captures the actual issuer/Account/tenant/membership sources, persisted Account lifecycle, exact membership event and role snapshot, current entitlement and its separate billing receipt, and the exact SQL token-identity fence. The exact Account row identity and `ACTIVE` lifecycle, active player membership, entitlement admission flags, provenance, issuance fence and receipt/checkpoint consistency are checked through the existing owner repositories; missing, changed or unsupported evidence is denied. Unit fixtures use doubles of those repositories and do not establish PostgreSQL lock or race behavior. Four PostgreSQL source-capture definitions compose the existing first-JOIN, entitlement and issuance owners; their seeded evidence does not prove authenticated Game Design transport, gameplay admission or lease finalization. The unregistered source reader also requires the exact Account/tenant denial predicate from the canonical V86 lifecycle-serving journal. Both `PENDING` and `WORLD_TERMINAL` remain unresolved denial evidence; a World receipt alone does not finalize Account sources. Missing journal data, query failures or a serialization failure deny the observation. The journal's pending-insert guard versions the exact Account row without changing logical Account state, authority counters or outbox evidence, so an older repeatable-read snapshot cannot wait for that writer and then silently miss its committed intent. This is not a lifecycle writer, a World verifier or a source finalizer. Its concurrent PostgreSQL cases require physical execution before claiming that ordering proof. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionCommitConfirmation.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionCommitConfirmation.java new file mode 100644 index 0000000000..672872bbf5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionCommitConfirmation.java @@ -0,0 +1,116 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.math.BigInteger; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; + +/** + * Non-authorizing readback of PostgreSQL's durable confirmation for one original COMMITTED lease. + * + *

This immutable value preserves the exact lease operation and database-stamped proof fields. It + * does not prove current Account authority, cleanup, or permission to admit gameplay. + */ +public record AccountGameplayAdmissionCommitConfirmation( + AccountGameplayAdmissionLeaseOperation operation, + short confirmationVersion, + UUID requestId, + UUID accountId, + UUID leaseId, + long leaseFence, + String evidenceSha256, + UUID bindingDecisionId, + long expiresAtMs, + String finalizationXid, + String walInsertLsn, + String walFlushLsn, + long committedBeforeMs, + String confirmationXid) { + private static final BigInteger UINT32_MAX = + BigInteger.ONE.shiftLeft(32).subtract(BigInteger.ONE); + private static final BigInteger UINT64_MAX = + BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE); + + public AccountGameplayAdmissionCommitConfirmation { + Objects.requireNonNull(operation, "original committed lease operation is required"); + Objects.requireNonNull(requestId, "request ID is required"); + Objects.requireNonNull(accountId, "Account ID is required"); + Objects.requireNonNull(leaseId, "lease ID is required"); + Objects.requireNonNull(evidenceSha256, "evidence digest is required"); + Objects.requireNonNull(bindingDecisionId, "binding decision ID is required"); + Objects.requireNonNull(finalizationXid, "finalization transaction ID is required"); + Objects.requireNonNull(walInsertLsn, "WAL insert LSN is required"); + Objects.requireNonNull(walFlushLsn, "WAL flush LSN is required"); + Objects.requireNonNull(confirmationXid, "confirmation transaction ID is required"); + + var evidence = operation.evidence(); + var carrier = evidence.carrier(); + var scope = (java.util.Map) carrier.get("bindingScope"); + UUID expectedRequest = UUID.fromString((String) carrier.get("requestId")); + UUID expectedLease = UUID.fromString((String) carrier.get("leaseId")); + UUID expectedAccount = UUID.fromString((String) scope.get("accountId")); + long expectedFence = evidence.leaseFence().longValueExact(); + long expectedExpiry = Long.parseLong((String) carrier.get("expiresAt")); + + if (operation.state() != State.COMMITTED + || operation.bindingDecisionId() == null + || confirmationVersion != 1 + || !requestId.equals(expectedRequest) + || !accountId.equals(expectedAccount) + || !leaseId.equals(expectedLease) + || leaseFence <= 0L + || leaseFence != expectedFence + || !evidenceSha256.matches("[0-9a-f]{64}") + || !evidenceSha256.equals(evidence.sha256()) + || !bindingDecisionId.equals(operation.bindingDecisionId()) + || expiresAtMs <= 0L + || expiresAtMs != expectedExpiry + || committedBeforeMs <= 0L + || committedBeforeMs >= expiresAtMs) { + throw invalid(); + } + + requireCanonicalFullXid(finalizationXid); + requireCanonicalFullXid(confirmationXid); + if (finalizationXid.equals(confirmationXid)) throw invalid(); + BigInteger insert = parseLsn(walInsertLsn); + BigInteger flush = parseLsn(walFlushLsn); + if (insert.signum() <= 0 || flush.compareTo(insert) < 0) throw invalid(); + } + + private static void requireCanonicalFullXid(String value) { + if (value.isEmpty() || !value.matches("[1-9][0-9]*")) throw invalid(); + try { + BigInteger xid = new BigInteger(value); + if (xid.signum() <= 0 || xid.compareTo(UINT64_MAX) > 0) throw invalid(); + } catch (NumberFormatException failure) { + throw invalid(); + } + } + + private static BigInteger parseLsn(String value) { + if (!value.matches("(0|[1-9A-F][0-9A-F]{0,7})/(0|[1-9A-F][0-9A-F]{0,7})")) throw invalid(); + try { + int separator = value.indexOf('/'); + BigInteger high = new BigInteger(value.substring(0, separator), 16); + BigInteger low = new BigInteger(value.substring(separator + 1), 16); + if (high.compareTo(UINT32_MAX) > 0 || low.compareTo(UINT32_MAX) > 0) throw invalid(); + return high.shiftLeft(32).add(low); + } catch (NumberFormatException failure) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid durable Account admission commit confirmation"); + } + + @Override + public String toString() { + return "AccountGameplayAdmissionCommitConfirmation[requestId=" + + requestId + + ", confirmationVersion=" + + confirmationVersion + + "]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java new file mode 100644 index 0000000000..d679ff0e9c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.accountservice.repository; + +import io.grpc.Status; +import java.util.Objects; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionCommitConfirmation; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered, non-admitting owner for database proof that an original lease COMMIT preceded its + * unchanged expiry. It evaluates no current source authority and does not finalize or admit. + */ +public final class AccountGameplayAdmissionCommitConfirmationOwner { + private final AccountGameplayAdmissionCommitConfirmationRepository repository; + private final TransactionTemplate createTransaction; + private final TransactionTemplate readTransaction; + private final String namespace; + + public AccountGameplayAdmissionCommitConfirmationOwner( + AccountGameplayAdmissionCommitConfirmationRepository repository, + PlatformTransactionManager transactionManager, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.namespace = namespace; + PlatformTransactionManager manager = Objects.requireNonNull(transactionManager); + createTransaction = transaction(manager); + readTransaction = transaction(manager); + } + + /** + * Creates/replays the temporal receipt, waits for that transaction to commit, then independently + * reads the durable receipt in a fresh transaction before returning it. + */ + public AccountGameplayAdmissionCommitConfirmation confirm( + FinalizeGameplayAdmissionLeaseRequest request) { + RequestIdentity identity = authenticateAndParse(request); + rejectAmbientTransaction(); + try { + AccountGameplayAdmissionCommitConfirmation created = + Objects.requireNonNull( + createTransaction.execute( + ignored -> + repository.confirmCommitted(identity.evidence(), identity.decisionId()))); + AccountGameplayAdmissionCommitConfirmation read = + Objects.requireNonNull( + readTransaction.execute( + ignored -> + repository.readCommitConfirmation( + identity.evidence(), identity.decisionId()))); + if (!created.equals(read)) throw unavailable(); + return read; + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + /** Reads an existing proof only; it never creates or repairs a receipt. */ + public AccountGameplayAdmissionCommitConfirmation read( + FinalizeGameplayAdmissionLeaseRequest request) { + RequestIdentity identity = authenticateAndParse(request); + rejectAmbientTransaction(); + try { + return Objects.requireNonNull( + readTransaction.execute( + ignored -> + repository.readCommitConfirmation(identity.evidence(), identity.decisionId()))); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private RequestIdentity authenticateAndParse(FinalizeGameplayAdmissionLeaseRequest request) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + if (!GrpcPeerIdentity.isValidNamespace(namespace) + || !peer.uri().equals("spiffe://firemud/ns/" + namespace + "/sa/game-session-service")) + throw Status.PERMISSION_DENIED + .withDescription("Game Session workload required") + .asRuntimeException(); + if (request == null || !request.hasLease() || !request.getUnknownFields().asMap().isEmpty()) + throw invalidRequest(); + + AccountGameplayAdmissionLeaseEvidence evidence; + try { + evidence = AccountGameplayAdmissionLeaseWireCodec.parseReference(request.getLease()); + } catch (IllegalArgumentException failure) { + throw invalidRequest(); + } + var decision = canonicalDecision(request.getBindingDecisionId()); + if (!namespace.equals(evidence.carrier().get("targetNamespace")) + || !peer.uri().equals(evidence.carrier().get("callerWorkload"))) + throw Status.PERMISSION_DENIED + .withDescription("Admission lease caller mismatch") + .asRuntimeException(); + return new RequestIdentity(evidence, decision); + } + + private static TransactionTemplate transaction(PlatformTransactionManager manager) { + TransactionTemplate template = new TransactionTemplate(manager); + template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + template.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + template.setReadOnly(false); + return template; + } + + private static void rejectAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION + .withDescription("Owned Account transaction required") + .asRuntimeException(); + } + + private static java.util.UUID canonicalDecision(String text) { + try { + java.util.UUID value = java.util.UUID.fromString(text); + if (!value.toString().equals(text) || value.version() != 4 || value.variant() != 2) + throw new IllegalArgumentException(); + return value; + } catch (RuntimeException failure) { + throw invalidRequest(); + } + } + + private static io.grpc.StatusRuntimeException invalidRequest() { + return Status.INVALID_ARGUMENT + .withDescription("Malformed Account admission confirmation request") + .asRuntimeException(); + } + + private static io.grpc.StatusRuntimeException unavailable() { + return Status.UNAVAILABLE + .withDescription("Durable Account admission commit confirmation unavailable") + .asRuntimeException(); + } + + private record RequestIdentity( + net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence + evidence, + java.util.UUID decisionId) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java new file mode 100644 index 0000000000..04d1a1ecfd --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java @@ -0,0 +1,113 @@ +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.AccountGameplayAdmissionCommitConfirmation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; + +/** + * Unregistered, non-admitting storage confirmation for an already retained COMMITTED lease. + * + *

The database functions alone create or independently read a durability receipt. A raw + * operation state, timestamp, visible receipt row, or returned Java clock value is insufficient. + */ +public final class AccountGameplayAdmissionCommitConfirmationRepository { + private final DSLContext dsl; + private final AccountGameplayAdmissionLeaseRepository leaseRepository; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private injected persistence context; the repository never exposes it") + public AccountGameplayAdmissionCommitConfirmationRepository( + DSLContext dsl, AccountGameplayAdmissionLeaseRepository leaseRepository) { + this.dsl = Objects.requireNonNull(dsl); + this.leaseRepository = Objects.requireNonNull(leaseRepository); + } + + /** Creates or exactly replays a database-stamped receipt for the original proven COMMIT. */ + AccountGameplayAdmissionCommitConfirmation confirmCommitted( + AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { + AccountGameplayAdmissionLeaseOperation operation = exactCommitted(evidence, bindingDecisionId); + Record row = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", + requestId(evidence), + evidence.sha256(), + bindingDecisionId); + return confirmation(row, operation); + } + + /** Reads only a committed, independently durable receipt; this path never creates one. */ + AccountGameplayAdmissionCommitConfirmation readCommitConfirmation( + AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { + AccountGameplayAdmissionLeaseOperation operation = exactCommitted(evidence, bindingDecisionId); + Record row = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_read_commit_confirmation(?, ?, ?)", + requestId(evidence), + evidence.sha256(), + bindingDecisionId); + return confirmation(row, operation); + } + + private AccountGameplayAdmissionLeaseOperation exactCommitted( + AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { + Objects.requireNonNull(evidence); + requireUuidV4(bindingDecisionId); + AccountGameplayAdmissionLeaseOperation operation = + leaseRepository + .readExact(evidence) + .orElseThrow(AccountGameplayAdmissionCommitConfirmationRepository::unavailable); + if (operation.state() != State.COMMITTED + || !bindingDecisionId.equals(operation.bindingDecisionId())) throw unavailable(); + return operation; + } + + private static AccountGameplayAdmissionCommitConfirmation confirmation( + Record row, AccountGameplayAdmissionLeaseOperation operation) { + if (row == null) throw unavailable(); + try { + return new AccountGameplayAdmissionCommitConfirmation( + operation, + required(row, "confirmation_version", Short.class), + required(row, "request_id", UUID.class), + required(row, "account_uuid", UUID.class), + required(row, "lease_id", UUID.class), + required(row, "lease_fence", Long.class), + required(row, "evidence_sha256", String.class), + required(row, "binding_decision_id", UUID.class), + required(row, "expires_at_ms", Long.class), + required(row, "finalization_xid", String.class), + required(row, "wal_insert_lsn", String.class), + required(row, "wal_flush_lsn", String.class), + required(row, "committed_before_ms", Long.class), + required(row, "confirmation_xid", String.class)); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private static T required(Record row, String field, Class type) { + T value = row.get(field, type); + if (value == null) throw unavailable(); + return value; + } + + private static UUID requestId(AccountGameplayAdmissionLeaseEvidence evidence) { + return UUID.fromString((String) evidence.carrier().get("requestId")); + } + + private static void requireUuidV4(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) + throw new IllegalArgumentException("Canonical non-nil UUIDv4 decision identity required"); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Durable Account admission commit confirmation unavailable"); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql b/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql new file mode 100644 index 0000000000..e8c4c0d72a --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql @@ -0,0 +1,312 @@ +-- Temporal storage durability only: neither COMMITTED nor this confirmation grants admission. +-- Retained terminal rows are deliberately not backfilled from xmin or inferred transaction time. +ALTER TABLE account_gameplay_admission_lease_operations ADD COLUMN finalization_xid VARCHAR(20); + +-- [jooq ignore start] +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_finalization_xid_check CHECK ( + CASE WHEN finalization_xid IS NULL THEN TRUE + WHEN finalization_xid ~ '^[1-9][0-9]{0,19}$' THEN + status = 'COMMITTED' AND finalization_xid::numeric <= 18446744073709551615 + ELSE FALSE END); +-- [jooq ignore stop] + +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_confirmation_binding_unique + UNIQUE (request_id, account_uuid, lease_id, lease_fence, evidence_sha256, + binding_decision_id, expires_at_ms, finalization_xid); + +CREATE TABLE account_gameplay_admission_commit_confirmations ( + confirmation_version SMALLINT NOT NULL DEFAULT 1 CHECK (confirmation_version = 1), + request_id UUID PRIMARY KEY, + account_uuid UUID NOT NULL, + lease_id UUID NOT NULL, + lease_fence BIGINT NOT NULL CHECK (lease_fence > 0), + evidence_sha256 VARCHAR(64) NOT NULL CHECK (evidence_sha256 ~ '^[0-9a-f]{64}$'), + binding_decision_id UUID NOT NULL, + expires_at_ms BIGINT NOT NULL CHECK (expires_at_ms > 0), + finalization_xid VARCHAR(20) NOT NULL, + wal_insert_lsn TEXT NOT NULL, + wal_flush_lsn TEXT NOT NULL, + committed_before_ms BIGINT NOT NULL CHECK (committed_before_ms > 0 AND committed_before_ms < expires_at_ms), + confirmation_xid VARCHAR(20) NOT NULL, + FOREIGN KEY (request_id, account_uuid, lease_id, lease_fence, evidence_sha256, + binding_decision_id, expires_at_ms, finalization_xid) + REFERENCES account_gameplay_admission_lease_operations + (request_id, account_uuid, lease_id, lease_fence, evidence_sha256, + binding_decision_id, expires_at_ms, finalization_xid) +); + +-- Only PostgreSQL-specific expressions and procedural enforcement are omitted from simulation. +-- All receipt columns and the exact original-operation foreign key remain visible to jOOQ. +-- [jooq ignore start] +ALTER TABLE account_gameplay_admission_commit_confirmations + ADD CONSTRAINT account_admission_confirmation_proof_shape_check CHECK ( + CASE WHEN finalization_xid ~ '^[1-9][0-9]{0,19}$' + AND confirmation_xid ~ '^[1-9][0-9]{0,19}$' + AND wal_insert_lsn ~ '^(0|[1-9A-F][0-9A-F]{0,7})/(0|[1-9A-F][0-9A-F]{0,7})$' + AND wal_flush_lsn ~ '^(0|[1-9A-F][0-9A-F]{0,7})/(0|[1-9A-F][0-9A-F]{0,7})$' THEN + finalization_xid::numeric <= 18446744073709551615 + AND confirmation_xid::numeric <= 18446744073709551615 + AND finalization_xid <> confirmation_xid + AND wal_insert_lsn::pg_lsn > '0/0'::pg_lsn + AND wal_flush_lsn::pg_lsn >= wal_insert_lsn::pg_lsn + ELSE FALSE END); + +-- Preserve every V87 guard and the V89 terminal shape; stamp only the original transition. +CREATE OR REPLACE FUNCTION account_gameplay_admission_storage_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Account admission storage evidence cannot be removed' USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'account_gameplay_admission_lease_fences' THEN + PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF TG_OP = 'INSERT' THEN + IF NEW.last_fence <> 1 THEN RAISE EXCEPTION 'Lease fence must start at one' USING ERRCODE = '23514'; END IF; + ELSIF NEW.account_uuid IS DISTINCT FROM OLD.account_uuid OR NEW.last_fence <> OLD.last_fence + 1 THEN + RAISE EXCEPTION 'Lease fence must advance exactly once' USING ERRCODE = '23514'; + END IF; + ELSIF TG_TABLE_NAME = 'account_gameplay_admission_lease_allocations' THEN + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Lease allocation is immutable' USING ERRCODE = '23514'; + END IF; + PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF NOT EXISTS (SELECT 1 FROM account_gameplay_admission_lease_fences + WHERE account_uuid = NEW.account_uuid AND last_fence = NEW.lease_fence) THEN + RAISE EXCEPTION 'Lease allocation must bind current Account allocator' USING ERRCODE = '23514'; + END IF; + ELSE + IF TG_OP = 'INSERT' AND NEW.status <> 'PENDING' THEN + RAISE EXCEPTION 'Lease operation must start pending' USING ERRCODE = '23514'; + END IF; + IF (TG_OP = 'INSERT' AND NEW.finalization_xid IS NOT NULL) + OR (TG_OP = 'UPDATE' AND NEW.finalization_xid IS DISTINCT FROM OLD.finalization_xid) THEN + RAISE EXCEPTION 'Account admission finalization transaction is database stamped' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_finalization_xid_db_stamp'; + END IF; + IF TG_OP = 'UPDATE' AND (OLD.status <> 'PENDING' + OR (to_jsonb(NEW) - ARRAY['status', 'binding_decision_id', 'orphan_cleanup_id', 'finalization_xid']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['status', 'binding_decision_id', 'orphan_cleanup_id', 'finalization_xid'])) THEN + RAISE EXCEPTION 'Exact lease evidence and terminal decisions are immutable' USING ERRCODE = '23514'; + END IF; + IF (TG_OP = 'INSERT' OR NEW.status = 'COMMITTED') + AND (NEW.evaluated_at_ms > floor(extract(epoch FROM clock_timestamp()) * 1000) + OR NEW.expires_at_ms <= floor(extract(epoch FROM clock_timestamp()) * 1000)) THEN + RAISE EXCEPTION 'Lease operation storage deadline expired' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' AND NEW.status = 'COMMITTED' THEN + NEW.finalization_xid := pg_current_xact_id()::text; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_gameplay_admission_confirmation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + finalization_status TEXT; + insert_fence pg_lsn; + flush_fence pg_lsn; + observed_before_ms BIGINT; + observation INTEGER; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Account admission confirmation is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_immutable'; + END IF; + IF NEW.confirmation_version IS DISTINCT FROM 1 OR NEW.account_uuid IS NOT NULL + OR NEW.lease_id IS NOT NULL OR NEW.lease_fence IS NOT NULL OR NEW.expires_at_ms IS NOT NULL + OR NEW.finalization_xid IS NOT NULL OR NEW.wal_insert_lsn IS NOT NULL + OR NEW.wal_flush_lsn IS NOT NULL OR NEW.committed_before_ms IS NOT NULL + OR NEW.confirmation_xid IS NOT NULL THEN + RAISE EXCEPTION 'Account admission confirmation proof is database derived' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_db_proof'; + END IF; + SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = NEW.request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_operation_required'; + END IF; + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_owner_required'; + END IF; + SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = NEW.request_id; + IF NOT FOUND OR operation.status <> 'COMMITTED' OR operation.finalization_xid IS NULL + OR NEW.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR NEW.binding_decision_id IS DISTINCT FROM operation.binding_decision_id THEN + RAISE EXCEPTION 'Account admission confirmation exact committed binding required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; + END IF; + BEGIN + finalization_status := pg_xact_status(operation.finalization_xid::xid8); + EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Account admission confirmation finalization proof unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_finalization_unavailable'; + END; + IF finalization_status IS DISTINCT FROM 'committed' THEN + RAISE EXCEPTION 'Account admission confirmation requires independent finalization commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_finalization_independent'; + END IF; + IF pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Account admission confirmation durable primary required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_durable_primary'; + END IF; + -- Independent committed visibility precedes this insert fence; its original COMMIT WAL is + -- therefore no later than the fence. Never carry an unconfirmed fence across connections. + insert_fence := pg_current_wal_insert_lsn(); + IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN + RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; + END IF; + -- A fixed fence permits read-only polling while lock WAL is flushed naturally. The bounded + -- observation budget is not a new lease deadline, and no flush or new marker is forced. + FOR observation IN 1..50 LOOP + flush_fence := pg_current_wal_flush_lsn(); + -- A separate statement AFTER each flush observation is essential: SQL expression order + -- is not a temporal guarantee. CEIL supplies a conservative DB wall-clock upper bound. + observed_before_ms := ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint; + IF observed_before_ms <= 0 OR observed_before_ms >= operation.expires_at_ms THEN + RAISE EXCEPTION 'Account admission confirmation original deadline expired' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_original_deadline'; + END IF; + EXIT WHEN flush_fence IS NOT NULL AND flush_fence >= insert_fence; + IF observation = 50 THEN + RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; + END IF; + PERFORM pg_sleep(0.01); + END LOOP; + NEW.account_uuid := operation.account_uuid; + NEW.lease_id := operation.lease_id; + NEW.lease_fence := operation.lease_fence; + NEW.expires_at_ms := operation.expires_at_ms; + NEW.finalization_xid := operation.finalization_xid; + NEW.wal_insert_lsn := insert_fence::text; + NEW.wal_flush_lsn := flush_fence::text; + NEW.committed_before_ms := observed_before_ms; + NEW.confirmation_xid := pg_current_xact_id()::text; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_admission_confirmation_guard BEFORE INSERT OR UPDATE OR DELETE + ON account_gameplay_admission_commit_confirmations FOR EACH ROW + EXECUTE FUNCTION account_gameplay_admission_confirmation_guard(); +CREATE TRIGGER account_admission_confirmation_truncate_guard BEFORE TRUNCATE + ON account_gameplay_admission_commit_confirmations FOR EACH STATEMENT + EXECUTE FUNCTION account_gameplay_admission_confirmation_guard(); + +CREATE FUNCTION account_gameplay_admission_confirm_committed( + requested_request_id UUID, expected_sha TEXT, expected_decision UUID) +RETURNS SETOF account_gameplay_admission_commit_confirmations LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_commit_confirmations%ROWTYPE; +BEGIN + SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = requested_request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_operation_required'; + END IF; + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_owner_required'; + END IF; + SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = requested_request_id; + IF NOT FOUND OR operation.status <> 'COMMITTED' OR operation.finalization_xid IS NULL + OR expected_sha IS DISTINCT FROM operation.evidence_sha256 + OR expected_decision IS DISTINCT FROM operation.binding_decision_id THEN + RAISE EXCEPTION 'Account admission confirmation exact committed binding required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; + END IF; + SELECT * INTO receipt FROM account_gameplay_admission_commit_confirmations WHERE request_id = requested_request_id; + IF FOUND THEN + IF receipt.account_uuid IS DISTINCT FROM operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid THEN + RAISE EXCEPTION 'Account admission confirmation immutable binding conflict' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_conflict'; + END IF; + RETURN NEXT receipt; + RETURN; + END IF; + -- No supplied timestamps, transaction IDs, WAL positions or renewed deadline are accepted. + INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) + VALUES (requested_request_id, expected_sha, expected_decision) RETURNING * INTO receipt; + RETURN NEXT receipt; +END; +$$; + +CREATE FUNCTION account_gameplay_admission_read_commit_confirmation( + requested_request_id UUID, expected_sha TEXT, expected_decision UUID) +RETURNS SETOF account_gameplay_admission_commit_confirmations LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_commit_confirmations%ROWTYPE; + insert_fence pg_lsn; + flush_fence pg_lsn; + observation INTEGER; +BEGIN + SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = requested_request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_operation_required'; + END IF; + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_owner_required'; + END IF; + SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = requested_request_id; + SELECT * INTO receipt FROM account_gameplay_admission_commit_confirmations WHERE request_id = requested_request_id; + IF NOT FOUND OR operation.status IS DISTINCT FROM 'COMMITTED' + OR expected_sha IS DISTINCT FROM operation.evidence_sha256 + OR expected_decision IS DISTINCT FROM operation.binding_decision_id + OR receipt.account_uuid IS DISTINCT FROM operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid THEN + RAISE EXCEPTION 'Account admission confirmation exact durable receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_receipt_required'; + END IF; + -- MVCC visibility plus exclusion of our own top-level XID also excludes our subtransactions. + -- Historical receipts need not retain pg_xact_status data forever: fresh WAL coverage below + -- covers their independently visible original COMMIT without consulting vacuum-pruned status. + IF receipt.confirmation_xid = pg_current_xact_id()::text THEN + RAISE EXCEPTION 'Account admission confirmation requires independent receipt commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_receipt_independent'; + END IF; + IF pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Account admission confirmation durable primary required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_durable_primary'; + END IF; + insert_fence := pg_current_wal_insert_lsn(); + IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN + RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; + END IF; + FOR observation IN 1..50 LOOP + flush_fence := pg_current_wal_flush_lsn(); + EXIT WHEN flush_fence IS NOT NULL AND flush_fence >= insert_fence; + IF observation = 50 THEN + RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; + END IF; + PERFORM pg_sleep(0.01); + END LOOP; + -- Return immutable historical timing evidence even after expiry; never restamp or renew it. + RETURN NEXT receipt; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index f3d5460223..9c4d66c218 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -18,6 +18,7 @@ import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; @@ -27,6 +28,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; +import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterAll; @@ -669,6 +671,489 @@ void concurrentDuplicatesReplayOneAllocationAndDistinctRequestsAdvanceFence() th } } + @Test + void durableConfirmationStoresOriginalCommitProofAndRecoversLostResponseAfterExpiry() + throws Exception { + var context = context(null); + UUID account = account(context); + var original = pending(context, account); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID decision = UUID.randomUUID(); + tx(context, () -> repository.recordCommitted(original, decision)); + var unchanged = storageSnapshot(context); + var transactionManager = new DataSourceTransactionManager(context.dataSource()); + var confirmationOwner = + new AccountGameplayAdmissionCommitConfirmationOwner( + new AccountGameplayAdmissionCommitConfirmationRepository(context.dsl(), repository), + transactionManager, + "test"); + var request = + FinalizeGameplayAdmissionLeaseRequest.newBuilder() + .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(original)) + .setBindingDecisionId(decision.toString()) + .build(); + + // The exact Game Session peer, carrier and decision are synthetic upstream fixtures. The real + // Java owner creates and independently reads Account SQL proof; this does not prove mTLS. + syntheticReadPeer().call(() -> confirmationOwner.confirm(request)); // Discard the response. + // Inspect stored fields separately; this visible row alone is not durable readback proof. + var receipt = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_admission_commit_confirmations WHERE request_id = ?", + requestId(original))); + assertThat(receipt.get("confirmation_version", Short.class)).isEqualTo((short) 1); + assertThat(receipt.get("request_id", UUID.class)).isEqualTo(requestId(original)); + assertThat(receipt.get("account_uuid", UUID.class)).isEqualTo(account); + assertThat(receipt.get("lease_id", UUID.class)) + .isEqualTo(UUID.fromString((String) original.carrier().get("leaseId"))); + assertThat(receipt.get("lease_fence", Long.class)) + .isEqualTo(original.leaseFence().longValueExact()); + assertThat(receipt.get("evidence_sha256", String.class)).isEqualTo(original.sha256()); + assertThat(receipt.get("binding_decision_id", UUID.class)).isEqualTo(decision); + assertThat(receipt.get("expires_at_ms", Long.class)).isEqualTo(expiresAt(original)); + assertThat(receipt.get("committed_before_ms", Long.class)) + .isPositive() + .isLessThan(expiresAt(original)); + assertThat(receipt.get("finalization_xid", String.class)) + .isEqualTo(operation(context, original).get("finalization_xid", String.class)); + assertThat(receipt.get("confirmation_xid", String.class)) + .isNotEqualTo(receipt.get("finalization_xid", String.class)); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT ?::pg_lsn >= ?::pg_lsn AS covered", + receipt.get("wal_flush_lsn", String.class), + receipt.get("wal_insert_lsn", String.class))) + .get("covered", Boolean.class)) + .isTrue(); + // Recovery opens the real owner's fresh transaction and covers the independently committed + // receipt's WAL before returning the immutable DTO, without reconstructing any proof fields. + var recovered = syntheticReadPeer().call(() -> confirmationOwner.read(request)); + assertThat(recovered.operation().state()).isEqualTo(State.COMMITTED); + assertThat(recovered.operation().evidence().canonicalJson()) + .isEqualTo(original.canonicalJson()); + assertThat(recovered.operation().evidence().sha256()).isEqualTo(original.sha256()); + assertThat(recovered.operation().bindingDecisionId()).isEqualTo(decision); + assertThat(recovered.requestId()).isEqualTo(receipt.get("request_id", UUID.class)); + assertThat(recovered.accountId()).isEqualTo(receipt.get("account_uuid", UUID.class)); + assertThat(recovered.leaseId()).isEqualTo(receipt.get("lease_id", UUID.class)); + assertThat(recovered.leaseFence()).isEqualTo(receipt.get("lease_fence", Long.class)); + assertThat(recovered.confirmationVersion()) + .isEqualTo(receipt.get("confirmation_version", Short.class)); + assertThat(recovered.evidenceSha256()).isEqualTo(receipt.get("evidence_sha256", String.class)); + assertThat(recovered.bindingDecisionId()) + .isEqualTo(receipt.get("binding_decision_id", UUID.class)); + assertThat(recovered.expiresAtMs()).isEqualTo(receipt.get("expires_at_ms", Long.class)); + assertThat(recovered.committedBeforeMs()) + .isEqualTo(receipt.get("committed_before_ms", Long.class)); + assertThat(recovered.finalizationXid()) + .isEqualTo(receipt.get("finalization_xid", String.class)); + assertThat(recovered.confirmationXid()) + .isEqualTo(receipt.get("confirmation_xid", String.class)); + assertThat(recovered.walInsertLsn()).isEqualTo(receipt.get("wal_insert_lsn", String.class)); + assertThat(recovered.walFlushLsn()).isEqualTo(receipt.get("wal_flush_lsn", String.class)); + waitPastDeadline(context, original); + assertThat(tx(context, () -> confirm(context, original, decision))).isEqualTo(receipt); + assertThat(syntheticReadPeer().call(() -> confirmationOwner.read(request))) + .isEqualTo(recovered); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + var readOwner = new AccountGameplayAdmissionReadOwner(repository, transactionManager, "test"); + assertFailedExactRead(readOwner, original); + } + + @Test + void updateBeforeExpiryButPhysicalCommitAfterExpiryCannotCreateConfirmation() { + var context = context(null); + var original = pending(context, account(context), 1000); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID decision = UUID.randomUUID(); + tx( + context, + () -> { + repository.recordCommitted(original, decision); + assertThat(databaseNow(context)).isLessThan(expiresAt(original)); + waitPastDeadline(context, original); + return null; + }); + assertThat(operation(context, original).get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(operation(context, original).get("finalization_xid", String.class)).isNotNull(); + var unchanged = storageSnapshot(context); + assertThatThrownBy(() -> tx(context, () -> confirm(context, original, decision))) + .hasMessageContaining("original deadline expired"); + assertThatThrownBy(() -> tx(context, () -> readConfirmation(context, original, decision))) + .hasMessageContaining("exact durable receipt required"); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + } + + @Test + void sameTransactionAndReleasedSubtransactionCannotConfirmOriginalFinalization() { + var context = context(null); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + for (boolean subtransaction : List.of(false, true)) { + var original = pending(context, account); + UUID decision = UUID.randomUUID(); + tx( + context, + () -> { + if (subtransaction) context.dsl().execute("SAVEPOINT original_finalization"); + repository.recordCommitted(original, decision); + if (subtransaction) context.dsl().execute("RELEASE SAVEPOINT original_finalization"); + var stamp = operation(context, original).get("finalization_xid", String.class); + assertThat(stamp) + .isEqualTo( + Objects.requireNonNull( + context.dsl().fetchOne("SELECT pg_current_xact_id()::text AS xid")) + .get("xid", String.class)); + assertDeniedInSavepoint( + context, + () -> confirm(context, original, decision), + "requires independent finalization commit"); + return null; + }); + } + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + } + + @Test + void missingPendingRolledBackAbortedAndRetainedUnstampedCommitsStayUnproved() { + var context = context("89"); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var retained = pending(context, account); + UUID decision = UUID.randomUUID(); + tx(context, () -> repository.recordCommitted(retained, decision)); + var retainedPending = pending(context, account); + var aborted = pending(context, account); + tx(context, () -> repository.recordAborted(aborted, null, UUID.randomUUID())); + migrate(context, null); + assertThat(operation(context, retained).get("finalization_xid", String.class)).isNull(); + assertThat(operation(context, retainedPending).get("finalization_xid", String.class)).isNull(); + assertThat(operation(context, aborted).get("finalization_xid", String.class)).isNull(); + var rolledBack = pending(context, account); + assertThatThrownBy( + () -> + tx( + context, + () -> { + repository.recordCommitted(rolledBack, decision); + throw new IllegalStateException("roll back physical finalization"); + })) + .hasMessageContaining("roll back physical finalization"); + assertThat(operation(context, rolledBack).get("status", String.class)).isEqualTo("PENDING"); + assertThat(operation(context, rolledBack).get("finalization_xid", String.class)).isNull(); + var unchanged = storageSnapshot(context); + for (var unproved : List.of(retained, retainedPending, aborted, rolledBack)) { + assertThatThrownBy(() -> tx(context, () -> confirm(context, unproved, decision))) + .hasMessageContaining("exact committed binding required"); + assertThatThrownBy(() -> tx(context, () -> readConfirmation(context, unproved, decision))) + .hasMessageContaining("exact durable receipt required"); + } + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", + UUID.randomUUID(), + retained.sha256(), + decision))) + .hasMessageContaining("operation missing"); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + } + + @Test + void confirmationRejectsChangedBindingsAndCallerProofAndRemainsImmutable() { + var context = context(null); + UUID account = account(context); + var original = pending(context, account); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID decision = UUID.randomUUID(); + UUID request = requestId(original); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_operations SET status = 'COMMITTED', binding_decision_id = ?, finalization_xid = '1' WHERE request_id = ?", + decision, + request))) + .hasMessageContaining("finalization transaction is database stamped"); + tx(context, () -> repository.recordCommitted(original, decision)); + var unchanged = storageSnapshot(context); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", + request, + "b".repeat(64), + decision))) + .hasMessageContaining("exact committed binding required"); + assertThatThrownBy(() -> tx(context, () -> confirm(context, original, UUID.randomUUID()))) + .hasMessageContaining("exact committed binding required"); + // Every proof/identity field is database-derived even if supplied values look plausible. + for (String assignment : + List.of( + "account_uuid = '" + account + "'::uuid", + "lease_id = '" + original.carrier().get("leaseId") + "'::uuid", + "lease_fence = 1", + "expires_at_ms = " + expiresAt(original), + "finalization_xid = '1'", + "wal_insert_lsn = '0/1'", + "wal_flush_lsn = '0/1'", + "committed_before_ms = 1", + "confirmation_xid = '1'")) { + String[] fieldAndValue = assignment.split(" = ", 2); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id, " + + fieldAndValue[0] + + ") VALUES (?, ?, ?, " + + fieldAndValue[1] + + ")", + request, + original.sha256(), + decision))) + .hasMessageContaining("proof is database derived"); + } + var receipt = tx(context, () -> confirm(context, original, decision)); + for (String mutation : + List.of( + "UPDATE account_gameplay_admission_commit_confirmations SET committed_before_ms = 1", + "UPDATE account_gameplay_admission_commit_confirmations SET expires_at_ms = expires_at_ms + 1", + "UPDATE account_gameplay_admission_commit_confirmations SET evidence_sha256 = '" + + "b".repeat(64) + + "'", + "DELETE FROM account_gameplay_admission_commit_confirmations", + "TRUNCATE account_gameplay_admission_commit_confirmations")) { + assertThatThrownBy(() -> tx(context, () -> context.dsl().execute(mutation))) + .hasMessageContaining("confirmation is immutable"); + } + assertThatThrownBy( + () -> tx(context, () -> readConfirmation(context, original, UUID.randomUUID()))) + .hasMessageContaining("exact durable receipt required"); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_operations SET finalization_xid = '1' WHERE request_id = ?", + request))) + .hasMessageContaining("finalization transaction is database stamped"); + assertThat(tx(context, () -> readConfirmation(context, original, decision))).isEqualTo(receipt); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + } + + @Test + void sameTransactionReceiptReadAndRolledBackConfirmationCannotProveDurability() { + var context = context(null); + var original = pending(context, account(context)); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID decision = UUID.randomUUID(); + tx(context, () -> repository.recordCommitted(original, decision)); + assertThatThrownBy( + () -> + tx( + context, + () -> { + confirm(context, original, decision); + assertDeniedInSavepoint( + context, + () -> readConfirmation(context, original, decision), + "requires independent receipt commit"); + throw new IllegalStateException("roll back confirmation commit"); + })) + .hasMessageContaining("roll back confirmation commit"); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + assertThatThrownBy(() -> tx(context, () -> readConfirmation(context, original, decision))) + .hasMessageContaining("exact durable receipt required"); + var receipt = tx(context, () -> confirm(context, original, decision)); + assertThat(tx(context, () -> readConfirmation(context, original, decision))).isEqualTo(receipt); + } + + @Test + void concurrentConfirmationsRetainOneOriginalReceiptWithoutAdvancingSources() throws Exception { + var context = context(null); + var original = pending(context, account(context)); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID decision = UUID.randomUUID(); + tx(context, () -> repository.recordCommitted(original, decision)); + var unchanged = storageSnapshot(context); + var start = new CountDownLatch(1); + Callable duplicate = + () -> { + if (!start.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("start timeout"); + return retrySerialization(() -> tx(context, () -> confirm(context, original, decision))); + }; + try (var executor = Executors.newFixedThreadPool(2)) { + var left = executor.submit(duplicate); + var right = executor.submit(duplicate); + start.countDown(); + assertThat(left.get(30, TimeUnit.SECONDS)).isEqualTo(right.get(30, TimeUnit.SECONDS)); + } + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isEqualTo(1); + var retained = tx(context, () -> confirm(context, original, decision)); + assertThat(tx(context, () -> readConfirmation(context, original, decision))) + .isEqualTo(retained); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + } + + private static Record confirm( + Context context, AccountGameplayAdmissionLeaseEvidence original, UUID decision) { + return Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", + requestId(original), + original.sha256(), + decision)); + } + + private static Record readConfirmation( + Context context, AccountGameplayAdmissionLeaseEvidence original, UUID decision) { + return Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_admission_read_commit_confirmation(?, ?, ?)", + requestId(original), + original.sha256(), + decision)); + } + + private static void assertDeniedInSavepoint( + Context context, Supplier action, String expectedMessage) { + context.dsl().execute("SAVEPOINT denied_confirmation"); + try { + assertThatThrownBy(action::get) + .hasMessageContaining(expectedMessage) + .satisfies( + failure -> { + Throwable cause = failure; + while (cause != null && !(cause instanceof java.sql.SQLException)) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(java.sql.SQLException.class); + assertThat(((java.sql.SQLException) cause).getSQLState()).isEqualTo("23514"); + }); + } finally { + context.dsl().execute("ROLLBACK TO SAVEPOINT denied_confirmation"); + context.dsl().execute("RELEASE SAVEPOINT denied_confirmation"); + } + } + + private static Record operation(Context context, AccountGameplayAdmissionLeaseEvidence original) { + return Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_admission_lease_operations WHERE request_id = ?", + requestId(original))); + } + + private static Map>> storageSnapshot(Context context) { + Map>> snapshot = new LinkedHashMap<>(); + for (String table : + List.of( + "accounts", + "account_gameplay_admission_lease_fences", + "account_gameplay_admission_lease_allocations", + "account_gameplay_admission_lease_operations", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_source_records", + "account_authority_outbox_streams", + "account_authority_outbox_events")) { + snapshot.put( + table, + context.dsl().fetch("SELECT * FROM " + table + " ORDER BY 1").stream() + .map(Record::intoMap) + .toList()); + } + return snapshot; + } + + private static UUID requestId(AccountGameplayAdmissionLeaseEvidence original) { + return UUID.fromString((String) original.carrier().get("requestId")); + } + + private static long expiresAt(AccountGameplayAdmissionLeaseEvidence original) { + return Long.parseLong((String) original.carrier().get("expiresAt")); + } + + private static long databaseNow(Context context) { + return Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint AS now_ms")) + .get("now_ms", Long.class); + } + + private static void waitPastDeadline( + Context context, AccountGameplayAdmissionLeaseEvidence original) { + context + .dsl() + .fetchOne( + "SELECT pg_sleep(GREATEST(0, (? - ceil(extract(epoch FROM clock_timestamp()) * 1000) + 50) / 1000.0))", + expiresAt(original)); + assertThat(databaseNow(context)).isGreaterThanOrEqualTo(expiresAt(original)); + } + + private static AccountGameplayAdmissionLeaseEvidence pending( + Context context, UUID account, long lifetimeMs) { + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + return tx( + context, + () -> { + var allocation = repository.allocate(account, UUID.randomUUID(), UUID.randomUUID()); + var carrier = new LinkedHashMap<>(evidence(allocation).carrier()); + carrier.put( + "expiresAt", + Long.toString(Long.parseLong((String) carrier.get("evaluatedAt")) + lifetimeMs)); + var evidence = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + repository.beginPending(evidence); + return evidence; + }); + } + private static T retrySerialization(Supplier action) { for (int attempt = 0; ; attempt++) { try { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java new file mode 100644 index 0000000000..ac65c7647a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java @@ -0,0 +1,328 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionCommitConfirmation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner and transaction doubles only; no PostgreSQL durability or live mTLS is established. */ +class AccountGameplayAdmissionCommitConfirmationOwnerTest { + private final AccountGameplayAdmissionCommitConfirmationRepository repository = + mock(AccountGameplayAdmissionCommitConfirmationRepository.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final TransactionStatus transactionStatus = mock(TransactionStatus.class); + private final AccountGameplayAdmissionCommitConfirmationOwner owner = + new AccountGameplayAdmissionCommitConfirmationOwner(repository, manager, "test"); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void confirmsOnlyAfterCreationCommitThenReadsExactReceiptInIndependentSerializableTransaction() + throws Exception { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var receipt = receipt(evidence, decision); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.confirmCommitted(evidence, decision)).thenReturn(receipt); + when(repository.readCommitConfirmation(evidence, decision)).thenReturn(receipt); + + var returned = peer().call(() -> owner.confirm(request(evidence, decision))); + var retry = peer().call(() -> owner.confirm(request(evidence, decision))); + + assertThat(returned).isSameAs(receipt); + assertThat(retry).isSameAs(receipt); + assertThat(returned.operation().evidence().canonicalJson()).isEqualTo(evidence.canonicalJson()); + assertThat(returned.operation().evidence().sha256()).isEqualTo(evidence.sha256()); + assertThat(returned.operation().state()).isEqualTo(State.COMMITTED); + assertThat(returned.operation().bindingDecisionId()).isEqualTo(decision); + assertThat(returned.committedBeforeMs()).isLessThan(returned.expiresAtMs()); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + var ordered = inOrder(manager, repository); + ordered.verify(manager).getTransaction(definition.capture()); + ordered.verify(repository).confirmCommitted(evidence, decision); + ordered.verify(manager).commit(transactionStatus); + ordered.verify(manager).getTransaction(definition.capture()); + ordered.verify(repository).readCommitConfirmation(evidence, decision); + ordered.verify(manager).commit(transactionStatus); + ordered.verify(manager).getTransaction(definition.capture()); + ordered.verify(repository).confirmCommitted(evidence, decision); + ordered.verify(manager).commit(transactionStatus); + ordered.verify(manager).getTransaction(definition.capture()); + ordered.verify(repository).readCommitConfirmation(evidence, decision); + ordered.verify(manager).commit(transactionStatus); + assertThat(definition.getAllValues()) + .allSatisfy( + value -> { + assertThat(value.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(value.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(value.isReadOnly()).isFalse(); + }); + } + + @Test + void failedCreationOrLostCreationCommitNeverStartsIndependentReadOrReturnsProof() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.confirmCommitted(evidence, decision)).thenReturn(receipt(evidence, decision)); + doThrow(new IllegalStateException("commit uncertain")).when(manager).commit(transactionStatus); + assertStatus( + Status.Code.UNAVAILABLE, + () -> peer().call(() -> owner.confirm(request(evidence, decision)))); + verify(repository, never()).readCommitConfirmation(any(), any()); + verify(manager).commit(transactionStatus); + + TransactionSynchronizationManager.clear(); + org.mockito.Mockito.reset(manager, repository); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.confirmCommitted(evidence, decision)) + .thenThrow(new IllegalStateException("creation unavailable")); + assertStatus( + Status.Code.UNAVAILABLE, + () -> peer().call(() -> owner.confirm(request(evidence, decision)))); + verify(repository, never()).readCommitConfirmation(any(), any()); + } + + @Test + void changedIndependentReadAndReadFailureNeverExposeCreationResult() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var created = receipt(evidence, decision); + var changed = receipt(evidence, UUID.randomUUID()); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.confirmCommitted(evidence, decision)).thenReturn(created); + when(repository.readCommitConfirmation(evidence, decision)).thenReturn(changed); + assertStatus( + Status.Code.UNAVAILABLE, + () -> peer().call(() -> owner.confirm(request(evidence, decision)))); + + org.mockito.Mockito.reset(manager, repository); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.confirmCommitted(evidence, decision)).thenReturn(created); + when(repository.readCommitConfirmation(evidence, decision)) + .thenThrow(new IllegalStateException("read unavailable")); + assertStatus( + Status.Code.UNAVAILABLE, + () -> peer().call(() -> owner.confirm(request(evidence, decision)))); + } + + @Test + void dependencyUnavailableDescriptionAndTrailersAreReplacedWithBoundedOwnerFailure() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + Metadata trailers = new Metadata(); + Metadata.Key privateKey = + Metadata.Key.of("private-detail", Metadata.ASCII_STRING_MARSHALLER); + trailers.put(privateKey, "private dependency trailer"); + var dependencyFailure = + Status.UNAVAILABLE + .withDescription("private dependency description") + .asRuntimeException(trailers); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.confirmCommitted(evidence, decision)).thenThrow(dependencyFailure); + + assertUnavailableIsRedacted( + () -> peer().call(() -> owner.confirm(request(evidence, decision)))); + + TransactionSynchronizationManager.clear(); + org.mockito.Mockito.reset(manager, repository); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.confirmCommitted(evidence, decision)).thenReturn(receipt(evidence, decision)); + when(repository.readCommitConfirmation(evidence, decision)).thenThrow(dependencyFailure); + assertUnavailableIsRedacted( + () -> peer().call(() -> owner.confirm(request(evidence, decision)))); + + TransactionSynchronizationManager.clear(); + org.mockito.Mockito.reset(manager, repository); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.readCommitConfirmation(evidence, decision)).thenThrow(dependencyFailure); + assertUnavailableIsRedacted(() -> peer().call(() -> owner.read(request(evidence, decision)))); + } + + @Test + void readReturnsHistoricalTemporalProofWithoutCreatingOrReevaluatingItsDeadline() + throws Exception { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var receipt = receipt(evidence, decision); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.readCommitConfirmation(evidence, decision)).thenReturn(receipt); + + var returned = peer().call(() -> owner.read(request(evidence, decision))); + + assertThat(returned).isSameAs(receipt); + assertThat(returned.expiresAtMs()).isEqualTo(1_015_000L); + assertThat(returned.committedBeforeMs()).isLessThan(returned.expiresAtMs()); + verify(repository).readCommitConfirmation(evidence, decision); + verify(repository, never()).confirmCommitted(any(), any()); + verify(manager).commit(transactionStatus); + } + + @Test + void rejectsMissingWrongPeerAndNamespaceBeforeRequestParsingOrTransaction() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + var malformed = FinalizeGameplayAdmissionLeaseRequest.getDefaultInstance(); + assertStatus(Status.Code.UNAUTHENTICATED, () -> owner.confirm(malformed)); + for (String uri : + List.of( + "spiffe://firemud/ns/test/sa/account-service", + "spiffe://firemud/ns/other/sa/game-session-service")) { + assertStatus( + Status.Code.PERMISSION_DENIED, () -> peer(uri).call(() -> owner.read(malformed))); + } + assertStatus( + Status.Code.UNAUTHENTICATED, () -> owner.read(request(evidence, UUID.randomUUID()))); + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsMalformedEnvelopeDecisionUnknownFieldsAndCallerBindingBeforeTransaction() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var reference = AccountGameplayAdmissionLeaseWireCodec.encodeReference(evidence); + for (var request : + List.of( + FinalizeGameplayAdmissionLeaseRequest.getDefaultInstance(), + request(evidence, decision).toBuilder().setUnknownFields(unknown).build(), + request(evidence, decision).toBuilder() + .setLease(reference.toBuilder().setUnknownFields(unknown)) + .build(), + request(evidence, decision).toBuilder() + .setLease( + reference.toBuilder().setEvidenceCanonicalJson(ByteString.copyFromUtf8("{}"))) + .build(), + request(evidence, UUID.randomUUID()).toBuilder() + .setBindingDecisionId("not-a-uuid") + .build(), + request(evidence, decision).toBuilder() + .setBindingDecisionId(decision.toString().toUpperCase()) + .build())) { + assertStatus(Status.Code.INVALID_ARGUMENT, () -> peer().call(() -> owner.confirm(request))); + } + var changedCarrier = new LinkedHashMap<>(evidence.carrier()); + changedCarrier.put("targetNamespace", "other"); + changedCarrier.put("callerWorkload", "spiffe://firemud/ns/other/sa/game-session-service"); + var otherCaller = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> peer().call(() -> owner.read(request(otherCaller, decision)))); + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsAmbientTransactionAndSynchronizationBeforeOwnedTransaction() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.confirm(request(evidence, decision)))); + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.initSynchronization(); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.read(request(evidence, decision)))); + verifyNoInteractions(repository, manager); + } + + private static AccountGameplayAdmissionCommitConfirmation receipt( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + var operation = + new AccountGameplayAdmissionLeaseOperation(evidence, State.COMMITTED, decision, null); + return new AccountGameplayAdmissionCommitConfirmation( + operation, + (short) 1, + UUID.fromString((String) evidence.carrier().get("requestId")), + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString((String) evidence.carrier().get("leaseId")), + 1L, + evidence.sha256(), + decision, + 1_015_000L, + "123456", + "1/20", + "1/21", + 1_014_999L, + "123457"); + } + + private static FinalizeGameplayAdmissionLeaseRequest request( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + return FinalizeGameplayAdmissionLeaseRequest.newBuilder() + .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(evidence)) + .setBindingDecisionId(decision.toString()) + .build(); + } + + private static Context peer() { + return peer("spiffe://firemud/ns/test/sa/game-session-service"); + } + + private static Context peer(String uri) { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + } + + private static void assertStatus( + Status.Code expected, org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static void assertUnavailableIsRedacted( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + var statusFailure = (StatusRuntimeException) failure; + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(Status.fromThrowable(failure).getDescription()) + .isEqualTo("Durable Account admission commit confirmation unavailable"); + assertThat(statusFailure.getTrailers()).isNull(); + assertThat(statusFailure.getCause()).isNull(); + }); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java new file mode 100644 index 0000000000..f9add38597 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java @@ -0,0 +1,254 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Repository and SQL function doubles only; no PostgreSQL durability is established here. */ +class AccountGameplayAdmissionCommitConfirmationRepositoryTest { + private static final String CONFIRM_SQL = + "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)"; + private static final String READ_SQL = + "SELECT * FROM account_gameplay_admission_read_commit_confirmation(?, ?, ?)"; + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void confirmAndReadCallOnlyTheirDatabaseFunctionWithOriginalRequestDigestAndDecision() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var operation = committed(evidence, decision); + var confirmDsl = dsl(evidence, operation, proofRow(evidence, decision)); + var confirmRepository = repository(confirmDsl); + + var created = confirmRepository.confirmCommitted(evidence, decision); + + assertThat(created.operation()).isEqualTo(operation); + assertThat(created.operation().evidence().canonicalJson()).isEqualTo(evidence.canonicalJson()); + assertThat(created.operation().evidence().sha256()).isEqualTo(evidence.sha256()); + assertThat(created.operation().state()).isEqualTo(State.COMMITTED); + assertThat(created.operation().bindingDecisionId()).isEqualTo(decision); + assertThat(created.requestId()) + .isEqualTo(UUID.fromString((String) evidence.carrier().get("requestId"))); + assertThat(created.accountId()) + .isEqualTo(UUID.fromString("11111111-1111-4111-8111-111111111111")); + assertThat(created.leaseId()) + .isEqualTo(UUID.fromString((String) evidence.carrier().get("leaseId"))); + assertThat(created.leaseFence()).isEqualTo(1L); + assertThat(created.evidenceSha256()).isEqualTo(evidence.sha256()); + assertThat(created.bindingDecisionId()).isEqualTo(decision); + assertThat(created.expiresAtMs()).isEqualTo(1_015_000L); + assertThat(created.finalizationXid()).isEqualTo("123456"); + assertThat(created.walInsertLsn()).isEqualTo("1/20"); + assertThat(created.walFlushLsn()).isEqualTo("1/21"); + assertThat(created.committedBeforeMs()).isEqualTo(1_014_999L); + assertThat(created.confirmationXid()).isEqualTo("123457"); + verify(confirmDsl) + .fetchOne( + CONFIRM_SQL, + UUID.fromString((String) evidence.carrier().get("requestId")), + evidence.sha256(), + decision); + + var readDsl = dsl(evidence, operation, proofRow(evidence, decision)); + var readRepository = repository(readDsl); + assertThat(readRepository.readCommitConfirmation(evidence, decision)).isEqualTo(created); + verify(readDsl) + .fetchOne( + READ_SQL, + UUID.fromString((String) evidence.carrier().get("requestId")), + evidence.sha256(), + decision); + verify(readDsl, never()).fetchOne(eq(CONFIRM_SQL), any(Object[].class)); + } + + @Test + void requiresWritableSerializableAccountTransactionBeforeAnyStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + var repository = + new AccountGameplayAdmissionCommitConfirmationRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + assertThatThrownBy(() -> repository.readCommitConfirmation(evidence, UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.readCommitConfirmation(evidence, UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.confirmCommitted(evidence, UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + @Test + void pendingAbortedMissingAndDecisionMismatchNeverReachConfirmationFunctions() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + for (var operation : + java.util.List.of( + new AccountGameplayAdmissionLeaseOperation(evidence, State.PENDING, null, null), + new AccountGameplayAdmissionLeaseOperation( + evidence, State.ABORTED, null, UUID.randomUUID()), + new AccountGameplayAdmissionLeaseOperation( + evidence, State.COMMITTED, UUID.randomUUID(), null))) { + DSLContext dsl = dsl(evidence, operation, proofRow(evidence, decision)); + assertThatThrownBy(() -> repository(dsl).confirmCommitted(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + verify(dsl, never()).fetchOne(eq(CONFIRM_SQL), any(Object[].class)); + verify(dsl, never()).fetchOne(eq(READ_SQL), any(Object[].class)); + } + + DSLContext missingDsl = dsl(evidence, null, proofRow(evidence, decision)); + assertThatThrownBy(() -> repository(missingDsl).readCommitConfirmation(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + verify(missingDsl, never()).fetchOne(eq(READ_SQL), any(Object[].class)); + } + + @Test + void missingOrContradictoryDatabaseProofFailsClosed() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var operation = committed(evidence, decision); + for (String field : + java.util.List.of( + "confirmation_version", + "request_id", + "account_uuid", + "lease_id", + "lease_fence", + "evidence_sha256", + "binding_decision_id", + "expires_at_ms", + "finalization_xid", + "wal_insert_lsn", + "wal_flush_lsn", + "committed_before_ms", + "confirmation_xid")) { + Record bad = proofRow(evidence, decision); + overrideBadField(bad, field); + DSLContext dsl = dsl(evidence, operation, bad); + assertThatThrownBy(() -> repository(dsl).readCommitConfirmation(evidence, decision)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Durable Account admission commit confirmation unavailable"); + } + + DSLContext missing = dsl(evidence, operation, null); + assertThatThrownBy(() -> repository(missing).readCommitConfirmation(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + } + + private static AccountGameplayAdmissionCommitConfirmationRepository repository(DSLContext dsl) { + serializableTransaction(); + return new AccountGameplayAdmissionCommitConfirmationRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); + } + + private static DSLContext dsl( + AccountGameplayAdmissionLeaseEvidence evidence, + AccountGameplayAdmissionLeaseOperation operation, + Record proof) { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + Record operationRow = operation == null ? null : operationRow(evidence, operation); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, operationRow, proof); + return dsl; + } + + private static Record operationRow( + AccountGameplayAdmissionLeaseEvidence evidence, + AccountGameplayAdmissionLeaseOperation operation) { + Record row = mock(Record.class); + when(row.get("evidence_json", String.class)).thenReturn(evidence.canonicalJson()); + when(row.get("evidence_sha256", String.class)).thenReturn(evidence.sha256()); + when(row.get("account_uuid", UUID.class)) + .thenReturn(UUID.fromString("11111111-1111-4111-8111-111111111111")); + when(row.get("request_id", UUID.class)) + .thenReturn(UUID.fromString((String) evidence.carrier().get("requestId"))); + when(row.get("lease_id", UUID.class)) + .thenReturn(UUID.fromString((String) evidence.carrier().get("leaseId"))); + when(row.get("lease_fence", Long.class)).thenReturn(1L); + when(row.get("caller_workload", String.class)) + .thenReturn("spiffe://firemud/ns/test/sa/game-session-service"); + when(row.get("evaluated_at_ms", Long.class)).thenReturn(1_000_000L); + when(row.get("expires_at_ms", Long.class)).thenReturn(1_015_000L); + when(row.get("status", String.class)).thenReturn(operation.state().name()); + when(row.get("binding_decision_id", UUID.class)).thenReturn(operation.bindingDecisionId()); + when(row.get("orphan_cleanup_id", UUID.class)).thenReturn(operation.orphanCleanupId()); + return row; + } + + private static Record proofRow(AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + Record row = mock(Record.class); + when(row.get("confirmation_version", Short.class)).thenReturn((short) 1); + when(row.get("request_id", UUID.class)) + .thenReturn(UUID.fromString((String) evidence.carrier().get("requestId"))); + when(row.get("account_uuid", UUID.class)) + .thenReturn(UUID.fromString("11111111-1111-4111-8111-111111111111")); + when(row.get("lease_id", UUID.class)) + .thenReturn(UUID.fromString((String) evidence.carrier().get("leaseId"))); + when(row.get("lease_fence", Long.class)).thenReturn(1L); + when(row.get("evidence_sha256", String.class)).thenReturn(evidence.sha256()); + when(row.get("binding_decision_id", UUID.class)).thenReturn(decision); + when(row.get("expires_at_ms", Long.class)).thenReturn(1_015_000L); + when(row.get("finalization_xid", String.class)).thenReturn("123456"); + when(row.get("wal_insert_lsn", String.class)).thenReturn("1/20"); + when(row.get("wal_flush_lsn", String.class)).thenReturn("1/21"); + when(row.get("committed_before_ms", Long.class)).thenReturn(1_014_999L); + when(row.get("confirmation_xid", String.class)).thenReturn("123457"); + return row; + } + + private static void overrideBadField(Record row, String field) { + switch (field) { + case "confirmation_version" -> when(row.get(field, Short.class)).thenReturn((short) 2); + case "request_id", "account_uuid", "lease_id", "binding_decision_id" -> + when(row.get(field, UUID.class)).thenReturn(UUID.randomUUID()); + case "lease_fence", "expires_at_ms" -> when(row.get(field, Long.class)).thenReturn(2L); + case "committed_before_ms" -> when(row.get(field, Long.class)).thenReturn(1_015_000L); + case "evidence_sha256" -> when(row.get(field, String.class)).thenReturn("0".repeat(64)); + case "finalization_xid", "confirmation_xid" -> + when(row.get(field, String.class)).thenReturn("01"); + case "wal_insert_lsn" -> when(row.get(field, String.class)).thenReturn("2/20"); + case "wal_flush_lsn" -> when(row.get(field, String.class)).thenReturn("1/20 "); + default -> throw new IllegalArgumentException("Unknown proof field"); + } + } + + private static AccountGameplayAdmissionLeaseOperation committed( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + return new AccountGameplayAdmissionLeaseOperation(evidence, State.COMMITTED, decision, null); + } + + private static void serializableTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } +} From 42a2083e0de3e416d3a8e8d80d5d908fc800f9cc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:09:47 +1300 Subject: [PATCH 13/16] Fence Account-wide pending intents and prove durable fixture configuration --- design/project-management/ai-observations.md | 6 + .../player-access-and-session.md | 4 + .../DraftAuthorizationFenceRepository.java | 24 + .../AccountLifecyclePendingDenialReader.java | 38 +- ...ccount_global_pending_admission_fences.sql | 89 +++ ...StateOperationPostgresIntegrationTest.java | 277 ++++++++ ...orizationFencePostgresIntegrationTest.java | 364 +++++++++- ...issionLeasePersistenceIntegrationTest.java | 10 +- ...ionIssuancePersistenceIntegrationTest.java | 636 +++++++++++++++++- .../AccountPostgresIntegrationFixture.java | 64 +- ...AccountPostgresIntegrationFixtureTest.java | 29 + ...anonicalFirstJoinEventIntegrationTest.java | 306 ++++++++- ...countLifecyclePendingDenialReaderTest.java | 61 +- ...nicalFirstJoinTerminalCoordinatorTest.java | 4 +- ...meplayPublicAdmissionSourceReaderTest.java | 4 +- 15 files changed, 1848 insertions(+), 68 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V91__account_global_pending_admission_fences.sql diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 6163b7f1ad..547c7422ce 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -71,3 +71,9 @@ Entry format: - Observation: an exact-head CI observer initially attributed a cancelled dev-tool job to a retry-validation error printed by a negative-test fixture. Parent inspection found both displayed unittest groups ended `OK`, and GitHub marked the job cancelled after a newer run superseded it. The completed Account job and uploaded PostgreSQL JUnit evidence remained valid, while aggregate validation was incomplete. - Expected pattern: inspect failing assertions, group summaries and exact job/step conclusions before treating an error-shaped log line as a defect. Preserve completed module proof separately from cancellation, skipped later steps and whole-workflow readiness. - Reconsideration trigger: apply this classification to the next failed or cancelled exact-head run; a later green run does not retroactively execute the cancelled steps. + +- `2026-10-08`: PostgreSQL test-container defaults are not durability proof + - Observation: Testcontainers PostgreSQL 2.0.5 starts with `fsync=off`; exact Account confirmation CI executed eighteen lease cases, but five correctly failed the production durable-primary guard. Successful storage tests against that default must not be reported as durable COMMIT proof. + - Expected pattern: opt durability-sensitive suites into durable PostgreSQL settings from startup, read back primary and WAL settings explicitly, and reject an unsuitable external database without changing it. Do not weaken a production guard or infer that re-enabling `fsync` repairs previously unsafe data. + - Current status: the scoped startup/readback repair is prepared; corrected physical confirmation execution remains required, including idle-database WAL coverage. Other test suites retain their existing fixture configuration. + - Reconsideration trigger: update proof after corrected exact-head PostgreSQL execution; distinguish local compilation/skips and ordinary row visibility from established durability. 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 6fac3cbbd6..c35fc4743f 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,10 @@ This is a non-normative implementation tracker for player access and session. Ca ### Account Admission-Lease Prerequisite +Latest physical evidence supersedes the local-only confirmation evidence below: exact `28a1ef9a53be8c8423f34738d05fe3509a61dc57` [CI run 37709000871](https://github.com/benhook1013/FireMUD/actions/runs/37709000871), on merge `da108e97de9d01688abe3ef4a24ea64b2cf7386c` with exact base `7985e8a6f6354587f5c01649ede3d0cecde9fde2`, executes 1,339 Account cases with seven skips and five failures. All eighteen lease PostgreSQL cases execute: thirteen pass, while five confirmation cases reject the fixture's non-durable primary configuration. The installed Testcontainers PostgreSQL 2.0.5 constructor defaults to `fsync=off`. The corrected lease suite opts into `fsync=on` and `synchronous_commit=on` from container startup and explicitly reads back those settings and primary status; an unsuitable external database is rejected without changing its configuration. This repair preserves the production durability guard and all eighteen existing lease cases, adding one live-settings test. Corrected confirmation success and idle-database WAL coverage remain unproved; passing unrelated storage cases does not establish them. + +The pending-denial extension also checks Account security-state `WAITING` operations and exact `ACCOUNT:` / `GLOBAL_ROLES:` source changes in `WAITING`, independently of the target tenant's lifecycle journal. V91 versions only the matching persisted Account tuple, preserving logical state, counters, events and retained pending evidence. Source-change producers lock sorted, deduplicated Accounts before source and operation locks. New PostgreSQL definitions cover stale snapshots, both READ_COMMITTED lock orders, cross-account and cross-tenant scope, unchanged source/JOIN state, terminal draft changes that cannot clear a separate security operation, and historical committed JOIN replay. Corrected local R53 passes full Account checks, jOOQ generation, formatting, static analysis, integration compilation, boot packaging and documentation validation. Its test reports retain 1,170 executed unit outcomes with three skips and zero failures/errors from R52's unchanged unit boundary; eight non-database integration cases execute and 171 PostgreSQL cases skip without Docker. Flyway sanity passes twelve sets and 169 versioned files. R51 exposed three integration-fixture compilation errors and R52 exposed seven nullable fixture readbacks; bounded corrections preserve the denial assertions and use explicit non-null checks, not suppressions. These additions are negative protection only, not authenticated restriction authorization or a positive admission result; their new physical execution remains required. + The separate unregistered durability-confirmation preparation adds V90's database-stamped top-level finalization transaction identity and immutable exact-bound receipt. An independent committed operation, primary database with `fsync` enabled, ordered WAL-insert/flush coverage and subsequently rounded-up database clock establish a bound strictly before the original expiry. Bounded polling against one fixed WAL fence creates no marker, forces no flush and renews no deadline. The protected same-namespace Game Session owner commits receipt creation, then independently commits exact durable readback before returning the temporal value. Retained unstamped commits, rollback, self/subtransaction visibility, late or uncovered proof, changed identity and ambiguous readback remain denied. A retained receipt can be recovered later without rewriting its original evidence; it proves no current authority, World release, Game Session installation or gameplay admission. Seven additive PostgreSQL definitions preserve all eleven existing lease cases and cover real Java-owner/SQL timely and lost-response receipt recovery, late physical COMMIT, same-transaction rejection, retained/rolled-back denial, forged proof and immutability, uncommitted receipt rejection and concurrent exact retention. Local full Account checks, generation, formatting, static analysis, integration-source compilation, boot packaging and documentation checks passed in 2m18s: 1,170 unit and seven non-database integration cases executed, with three unit skips and 158 PostgreSQL skips, zero failures/errors. All eight confirmation-owner and four repository unit cases passed; all eighteen lease PostgreSQL definitions compiled but skipped. Flyway sanity passed twelve sets and 168 versioned files. Physical V90 execution, deterministic uncovered asynchronous WAL, recovery/disabled-fsync and remote-failover durability remain unproved. The preceding exact `17e8f609dcbe4ef4dc096b8bfe82557a68bbe9ef` checkpoint has successful [CI run 37706751965](https://github.com/benhook1013/FireMUD/actions/runs/37706751965) on composed merge `cd66dcf2618404caddba413731d50a32748ed705` against base `7985e8a6f6354587f5c01649ede3d0cecde9fde2`: 1,320 Account cases executed, seven skipped and zero failures/errors. All eleven then-existing lease PostgreSQL cases, six first-JOIN PostgreSQL cases and five World-client mTLS cases executed; that older proof does not establish V90. Acquire/finalize/reconcile RPCs remain unimplemented, raw storage `COMMITTED` remains denied by the negative-state read adapter, and the complete current-restriction producer and Game Session installation/cleanup are still required. The isolated Account candidate adds an unregistered same-transaction source reader for fresh Game Design tenant provenance and the existing `NON_PAID_DEMO` entitlement class. It captures the actual issuer/Account/tenant/membership sources, persisted Account lifecycle, exact membership event and role snapshot, current entitlement and its separate billing receipt, and the exact SQL token-identity fence. The exact Account row identity and `ACTIVE` lifecycle, active player membership, entitlement admission flags, provenance, issuance fence and receipt/checkpoint consistency are checked through the existing owner repositories; missing, changed or unsupported evidence is denied. Unit fixtures use doubles of those repositories and do not establish PostgreSQL lock or race behavior. Four PostgreSQL source-capture definitions compose the existing first-JOIN, entitlement and issuance owners; their seeded evidence does not prove authenticated Game Design transport, gameplay admission or lease finalization. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index ba50e2416d..cd506f9e04 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -14,6 +14,7 @@ import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Owner; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.OwnerReadback; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -237,6 +238,7 @@ public FenceSnapshot claimCommitOrder(DraftAuthorizationFenceBinding binding) { */ public boolean requestSourceChange(SourceChange change) { requireTransaction(); + lockChangedAccounts(change.sources()); lockSources(change.sources()); Record prior = readChange(change.changeId()); if (prior != null) { @@ -501,6 +503,28 @@ private void lockSources(List sources) { } } + /** Account-wide negative intent uses Account-before-source/operation lock order. */ + private void lockChangedAccounts(List sources) { + for (UUID account : + sources.stream() + .filter(s -> s.kind() == SourceKind.ACCOUNT || s.kind() == SourceKind.GLOBAL_ROLES) + .map(s -> UUID.fromString(s.scopeId())) + .distinct() + .sorted(Comparator.comparing(UUID::toString)) + .toList()) { + Record row = + dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ?" + + " AND id > 0 AND account_uuid_source_numeric_id = id" + + " AND account_uuid_provenance IN ('ACCOUNT_V29_MIGRATION'," + + " 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT') FOR UPDATE", + account); + if (row == null) { + throw new IllegalStateException("Source change requires the exact persisted Account row"); + } + } + } + private boolean hasWaitingChange(List sources) { for (SourceEvidence source : sources) { if (!dsl.fetch( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java index 3eda357d8b..8d2443d595 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java @@ -11,9 +11,9 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; /** - * Reads the canonical Account lifecycle operation table as a fail-closed admission denial - * predicate. It proves no producer identity, World result, source finalization, current serving - * state, or admission permission. + * Reads exact target-tenant lifecycle operations and Account-wide pending source operations as a + * fail-closed admission denial predicate. It proves no producer identity, World result, source + * finalization, current serving state, or admission permission. */ @Repository public class AccountLifecyclePendingDenialReader { @@ -22,7 +22,12 @@ public class AccountLifecyclePendingDenialReader { private static final String PENDING_SQL = "SELECT EXISTS (SELECT 1 FROM account_lifecycle_serving_operations " + "WHERE account_uuid = ? AND tenant_uuid = ? " - + "AND status IN ('PENDING', 'WORLD_TERMINAL'))"; + + "AND status IN ('PENDING', 'WORLD_TERMINAL')) " + + "OR EXISTS (SELECT 1 FROM account_security_state_operations " + + "WHERE account_uuid = ? AND status = 'WAITING') " + + "OR EXISTS (SELECT 1 FROM account_draft_authorization_source_changes c " + + "JOIN account_draft_authorization_changed_scopes s ON s.change_id = c.change_id " + + "WHERE c.status = 'WAITING' AND s.source_key IN (?, ?))"; private static final UUID NIL_UUID = new UUID(0L, 0L); private final DSLContext dsl; @@ -36,14 +41,18 @@ public AccountLifecyclePendingDenialReader(DSLContext dsl) { } /** - * Requires no unresolved lifecycle operation for the exact Account/tenant pair. + * Requires no unresolved exact target-tenant lifecycle operation or Account-wide pending source + * operation. * *

The existing writable owner transaction must be READ_COMMITTED, REPEATABLE_READ, or * SERIALIZABLE. At READ_COMMITTED, the exact Account row lock makes this query observe a - * lifecycle insert committed before the lock is acquired; the journal's BEFORE INSERT row-version - * fence prevents an insert from crossing a later lock holder. When Spring uses the datasource's - * default isolation, the actual PostgreSQL transaction isolation is checked. Both a pending - * intent and a correlated World terminal receipt remain denial evidence. + * lifecycle insert committed before the lock is acquired; the lifecycle journal's and + * Account-wide pending-intent tables' row-version fences prevent an insert from crossing a later + * lock holder. When Spring uses the datasource's default isolation, the actual PostgreSQL + * transaction isolation is checked. A pending lifecycle intent, a correlated World terminal + * receipt, an Account security-state operation in WAITING, or an Account/GLOBAL_ROLES source + * change in WAITING remains denial evidence. Tenant membership and tenant source scopes are not + * promoted to Account-wide scope. */ public void requireNoPending(UUID accountUuid, UUID tenantUuid) { requireWritableOwnerTransaction(dsl); @@ -56,7 +65,14 @@ public void requireNoPending(UUID accountUuid, UUID tenantUuid) { throw new PendingStateUnavailableException( "Account lifecycle pending state could not be read"); } - Record pendingRecord = dsl.fetchOne(PENDING_SQL, accountUuid, tenantUuid); + Record pendingRecord = + dsl.fetchOne( + PENDING_SQL, + accountUuid, + tenantUuid, + accountUuid, + "ACCOUNT:" + accountUuid, + "GLOBAL_ROLES:" + accountUuid); Boolean pending = pendingRecord == null ? null : pendingRecord.get(0, Boolean.class); if (pending == null) { throw new PendingStateUnavailableException( @@ -64,7 +80,7 @@ public void requireNoPending(UUID accountUuid, UUID tenantUuid) { } if (pending) { throw new PendingOperationException( - "Account lifecycle invalidation is unresolved for this Account and tenant"); + "Account-wide or target-tenant invalidation is unresolved"); } } catch (PendingOperationException | PendingStateUnavailableException denied) { throw denied; diff --git a/services/account-service/src/main/resources/db/migration/V91__account_global_pending_admission_fences.sql b/services/account-service/src/main/resources/db/migration/V91__account_global_pending_admission_fences.sql new file mode 100644 index 0000000000..007bf4ea03 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V91__account_global_pending_admission_fences.sql @@ -0,0 +1,89 @@ +-- Account-wide negative pending-intent protection only. Unchanged tuple versions fence stale +-- REPEATABLE_READ/SERIALIZABLE snapshots; no logical source, restriction or authority is created. +-- Retained WAITING evidence is preserved, including unmatched or contradictory historical rows. +-- [jooq ignore start] +CREATE FUNCTION account_security_state_account_row_version_fence() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + touched_rows INTEGER; +BEGIN + IF NEW.status = 'WAITING' THEN + UPDATE accounts SET id = id + WHERE account_uuid = NEW.account_uuid + AND id = NEW.account_id + AND account_uuid_source_numeric_id = NEW.account_id + AND account_uuid_provenance = NEW.account_provenance; + GET DIAGNOSTICS touched_rows = ROW_COUNT; + IF touched_rows <> 1 THEN + RAISE EXCEPTION 'Security-state intent requires the exact persisted Account row' + USING ERRCODE = '23514', + CONSTRAINT = 'account_security_state_account_row_version_fence'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_security_state_account_row_version_fence + BEFORE INSERT ON account_security_state_operations + FOR EACH ROW EXECUTE FUNCTION account_security_state_account_row_version_fence(); + +CREATE FUNCTION account_draft_authorization_account_row_version_fence() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + account_key TEXT; + touched_rows INTEGER; +BEGIN + IF split_part(NEW.source_key, ':', 1) IN ('ACCOUNT', 'GLOBAL_ROLES') THEN + IF NEW.source_key !~ '^(ACCOUNT|GLOBAL_ROLES):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN + RAISE EXCEPTION 'Account source scope must use the exact canonical UUID key' + USING ERRCODE = '23514', + CONSTRAINT = 'account_draft_authorization_account_row_version_fence'; + END IF; + account_key := split_part(NEW.source_key, ':', 2); + UPDATE accounts SET id = id + WHERE account_uuid = account_key::UUID + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND id > 0 AND account_uuid_source_numeric_id = id + AND account_uuid_provenance IN ( + 'ACCOUNT_V29_MIGRATION', 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT'); + GET DIAGNOSTICS touched_rows = ROW_COUNT; + IF touched_rows <> 1 THEN + RAISE EXCEPTION 'Account source scope requires the exact persisted Account row' + USING ERRCODE = '23514', + CONSTRAINT = 'account_draft_authorization_account_row_version_fence'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +-- Alphabetically earlier than V76's scope_insert_phase: Account is touched before parent locking. +CREATE TRIGGER account_draft_authorization_account_row_version_fence + BEFORE INSERT ON account_draft_authorization_changed_scopes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_account_row_version_fence(); + +-- Protect snapshots predating installation without asserting retained intent provenance or +-- enrolling an Account. Exact UUID/key matching supplies negative protection only. +DO $$ +DECLARE + pending_account UUID; +BEGIN + FOR pending_account IN + SELECT a.account_uuid FROM accounts a + WHERE EXISTS ( + SELECT 1 FROM account_security_state_operations security + WHERE security.account_uuid = a.account_uuid AND security.status = 'WAITING') + OR EXISTS ( + SELECT 1 FROM account_draft_authorization_source_changes change + JOIN account_draft_authorization_changed_scopes changed USING (change_id) + WHERE change.status = 'WAITING' + AND changed.source_key IN ( + 'ACCOUNT:' || a.account_uuid::TEXT, 'GLOBAL_ROLES:' || a.account_uuid::TEXT)) + ORDER BY a.account_uuid::TEXT + LOOP + UPDATE accounts SET id = id WHERE account_uuid = pending_account; + END LOOP; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java index 732f1bc931..6a0e53e67c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java @@ -4,6 +4,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.Objects; @@ -748,6 +750,281 @@ void forwardMigrationRetainsOriginalAccountAuthorityAndRoleImagesWithoutBackfill assertThat(seed.account().getAccountUuid()).isNotNull(); } + @Test + void latestWaitingClaimVersionsOnlyItsAccountAndFencesOlderSnapshots() throws Exception { + for (int isolation : + List.of(Connection.TRANSACTION_REPEATABLE_READ, Connection.TRANSACTION_SERIALIZABLE)) { + Fixture fixture = fixture("91"); + Seed seed = latestSeed(fixture); + Seed other = latestSeed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + var accounts = fixture.dsl().fetch("SELECT * FROM accounts ORDER BY id"); + var authority = fixture.dsl().fetch("SELECT * FROM account_authority_generations"); + var fences = fixture.dsl().fetch("SELECT * FROM account_authority_issuance_fences"); + var sources = fixture.dsl().fetch("SELECT * FROM account_authority_source_records"); + var roles = fixture.dsl().fetch("SELECT * FROM account_global_role_sources"); + var restrictions = + fixture.dsl().fetch("SELECT * FROM account_platform_restriction_projections"); + var restrictionBirths = + fixture.dsl().fetch("SELECT * FROM account_platform_restriction_births"); + var events = fixture.dsl().fetch("SELECT * FROM account_authority_outbox_events"); + String accountVersion = accountVersion(fixture, seed.account().getAccountUuid()); + String otherVersion = accountVersion(fixture, other.account().getAccountUuid()); + try (Connection stale = fixture.dataSource().getConnection()) { + stale.setAutoCommit(false); + stale.setTransactionIsolation(isolation); + try (var statement = stale.createStatement()) { + statement.executeQuery("SELECT id FROM accounts").close(); + var absent = + statement.executeQuery("SELECT count(*) FROM account_security_state_operations"); + assertThat(absent.next()).isTrue(); + assertThat(absent.getInt(1)).isZero(); + absent.close(); + } + var claim = + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + assertThat(claim.claimed()).isTrue(); + assertThat(claim.operation().receipt()).isEmpty(); + String claimedVersion = accountVersion(fixture, seed.account().getAccountUuid()); + assertThat(claimedVersion).isNotEqualTo(accountVersion); + assertThat(accountVersion(fixture, other.account().getAccountUuid())) + .isEqualTo(otherVersion); + assertThat(fixture.dsl().fetch("SELECT * FROM accounts ORDER BY id")).isEqualTo(accounts); + assertThat(fixture.dsl().fetch("SELECT * FROM account_authority_generations")) + .isEqualTo(authority); + assertThat(fixture.dsl().fetch("SELECT * FROM account_authority_issuance_fences")) + .isEqualTo(fences); + assertThat(fixture.dsl().fetch("SELECT * FROM account_authority_source_records")) + .isEqualTo(sources); + assertThat(fixture.dsl().fetch("SELECT * FROM account_global_role_sources")) + .isEqualTo(roles); + assertThat(fixture.dsl().fetch("SELECT * FROM account_platform_restriction_projections")) + .isEqualTo(restrictions); + assertThat(fixture.dsl().fetch("SELECT * FROM account_platform_restriction_births")) + .isEqualTo(restrictionBirths); + assertThat(fixture.dsl().fetch("SELECT * FROM account_authority_outbox_events")) + .isEqualTo(events); + assertStaleAccountLock(stale, seed.account().getAccountUuid()); + stale.rollback(); + assertThat( + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())) + .claimed()) + .isFalse(); + assertThat(accountVersion(fixture, seed.account().getAccountUuid())) + .isEqualTo(claimedVersion); + } + } + } + + @Test + void forwardPendingFenceMigrationRetainsEvidenceAndProtectsPreInstallSnapshots() + throws Exception { + for (int isolation : + List.of(Connection.TRANSACTION_REPEATABLE_READ, Connection.TRANSACTION_SERIALIZABLE)) { + Fixture fixture = fixture("83"); + Seed security = seed(fixture); + Seed roles = seed(fixture); + Seed other = seed(fixture); + migrate(fixture.dataSource(), fixture.schema(), "90"); + String securityVersion = accountVersion(fixture, security.account().getAccountUuid()); + String rolesVersion = accountVersion(fixture, roles.account().getAccountUuid()); + String otherVersion = accountVersion(fixture, other.account().getAccountUuid()); + try (Connection staleSecurity = fixture.dataSource().getConnection(); + Connection staleRoles = fixture.dataSource().getConnection()) { + for (Connection stale : List.of(staleSecurity, staleRoles)) { + stale.setAutoCommit(false); + stale.setTransactionIsolation(isolation); + try (var statement = stale.createStatement()) { + statement.executeQuery("SELECT id FROM accounts").close(); + var absent = + statement.executeQuery( + "SELECT count(*) FROM account_draft_authorization_source_changes"); + assertThat(absent.next()).isTrue(); + assertThat(absent.getInt(1)).isZero(); + absent.close(); + } + } + Pending pending = pending(fixture, security, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + // Retained contradictory correlation is negative-only evidence, never source authority. + // Superuser fixture corruption isolates UUID-keyed security denial from Draft scopes. + String unrelated = "ISSUER:retained-security-correlation"; + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + unrelated); + fixture + .dsl() + .execute("ALTER TABLE account_draft_authorization_changed_scopes DISABLE TRIGGER USER"); + fixture + .dsl() + .execute( + "UPDATE account_draft_authorization_changed_scopes SET source_key = ? WHERE change_id = ?", + unrelated, + pending.capture().sourceChange().changeId()); + fixture + .dsl() + .execute("ALTER TABLE account_draft_authorization_changed_scopes ENABLE TRIGGER USER"); + fixture.dsl().execute("ALTER TABLE account_security_state_operations DISABLE TRIGGER ALL"); + fixture + .dsl() + .execute( + "UPDATE account_security_state_operations SET account_provenance = 'ACCOUNT_DATABASE_INSERT' WHERE request_id = ?", + pending.request().requestId()); + fixture.dsl().execute("ALTER TABLE account_security_state_operations ENABLE TRIGGER ALL"); + SourceChange roleChange = + new SourceChange( + UUID.randomUUID(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + roles.account().getAccountUuid().toString(), + null, + "1", + null, + null, + new byte[] {7})), + new byte[] {12}); + tx(fixture, () -> fixture.fences().requestSourceChange(roleChange)); + // Historical malformed/unmapped participation remains evidence, never inferred identity. + retainedScope(fixture, "ACCOUNT:" + UUID.randomUUID()); + retainedScope(fixture, "GLOBAL_ROLES:41"); + assertThat(accountVersion(fixture, security.account().getAccountUuid())) + .isEqualTo(securityVersion); + assertThat(accountVersion(fixture, roles.account().getAccountUuid())) + .isEqualTo(rolesVersion); + var accounts = fixture.dsl().fetch("SELECT * FROM accounts ORDER BY id"); + var changes = + fixture + .dsl() + .fetch( + "SELECT * FROM account_draft_authorization_source_changes ORDER BY change_id"); + var scopes = + fixture + .dsl() + .fetch( + "SELECT * FROM account_draft_authorization_changed_scopes ORDER BY change_id, source_key"); + var operations = + fixture + .dsl() + .fetch("SELECT * FROM account_security_state_operations ORDER BY request_id"); + var authority = fixture.dsl().fetch("SELECT * FROM account_authority_generations"); + var fences = fixture.dsl().fetch("SELECT * FROM account_authority_issuance_fences"); + var sources = fixture.dsl().fetch("SELECT * FROM account_authority_source_records"); + var roleSources = fixture.dsl().fetch("SELECT * FROM account_global_role_sources"); + var events = fixture.dsl().fetch("SELECT * FROM account_authority_outbox_events"); + migrate(fixture.dataSource(), fixture.schema(), "91"); + assertThat(accountVersion(fixture, security.account().getAccountUuid())) + .isNotEqualTo(securityVersion); + assertThat(accountVersion(fixture, roles.account().getAccountUuid())) + .isNotEqualTo(rolesVersion); + assertThat(accountVersion(fixture, other.account().getAccountUuid())) + .isEqualTo(otherVersion); + assertThat(fixture.dsl().fetch("SELECT * FROM accounts ORDER BY id")).isEqualTo(accounts); + assertThat( + fixture + .dsl() + .fetch( + "SELECT * FROM account_draft_authorization_source_changes ORDER BY change_id")) + .isEqualTo(changes); + assertThat( + fixture + .dsl() + .fetch( + "SELECT * FROM account_draft_authorization_changed_scopes ORDER BY change_id, source_key")) + .isEqualTo(scopes); + assertThat( + fixture + .dsl() + .fetch("SELECT * FROM account_security_state_operations ORDER BY request_id")) + .isEqualTo(operations); + assertThat(fixture.dsl().fetch("SELECT * FROM account_authority_generations")) + .isEqualTo(authority); + assertThat(fixture.dsl().fetch("SELECT * FROM account_authority_issuance_fences")) + .isEqualTo(fences); + assertThat(fixture.dsl().fetch("SELECT * FROM account_authority_source_records")) + .isEqualTo(sources); + assertThat(fixture.dsl().fetch("SELECT * FROM account_global_role_sources")) + .isEqualTo(roleSources); + assertThat(fixture.dsl().fetch("SELECT * FROM account_authority_outbox_events")) + .isEqualTo(events); + assertThat(fixture.dsl().fetchCount(DSL.table("account_platform_restriction_births"))) + .isZero(); + assertStaleAccountLock(staleSecurity, security.account().getAccountUuid()); + assertStaleAccountLock(staleRoles, roles.account().getAccountUuid()); + staleSecurity.rollback(); + staleRoles.rollback(); + } + } + } + + private void retainedScope(Fixture fixture, String key) { + tx( + fixture, + () -> { + UUID change = UUID.randomUUID(); + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_changes (change_id, binding, status) VALUES (?, ?, 'WAITING')", + change, + new byte[] {12}); + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + key); + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_changed_scopes (change_id, source_key) VALUES (?, ?)", + change, + key); + return null; + }); + } + + private Seed latestSeed(Fixture fixture) { + return tx( + fixture, + () -> { + String suffix = UUID.randomUUID().toString(); + Account account = new Account(); + account.setUsername("security-" + suffix); + account.setEmail(suffix + "@example.test"); + account.setPasswordHash("synthetic-verifier"); + account.setLoginAuthModes(AccountLoginAuthModes.DEFAULT_SERIALIZED); + new AccountAuthoritySourceEvidenceRepository( + fixture.dsl(), fixture.generations(), fixture.outbox()) + .initializeIssuerIfAbsent("firemud-account-service"); + Account saved = new AccountRepository(fixture.dsl()).save(account); + return new Seed( + saved, fixture.generations().read(AuthorityScope.account(saved.getAccountUuid()))); + }); + } + + private static String accountVersion(Fixture fixture, UUID account) { + return Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT xmin::TEXT AS version FROM accounts WHERE account_uuid = ?", account), + "Expected persisted Account tuple version") + .get("version", String.class); + } + + private static void assertStaleAccountLock(Connection stale, UUID account) throws SQLException { + try (var lock = + stale.prepareStatement("SELECT id FROM accounts WHERE account_uuid = ? FOR SHARE")) { + lock.setObject(1, account); + assertThatThrownBy(lock::executeQuery) + .isInstanceOf(SQLException.class) + .extracting("SQLState") + .isEqualTo("40001"); + } + } + private Event producerFixture(Fixture fixture, Pending pending, boolean lateFailure) { return producerFixture(fixture, pending, lateFailure, true); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java index 4a398c04dc..a46a2f624c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java @@ -4,12 +4,16 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.SQLException; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Outcome; @@ -22,6 +26,8 @@ import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChangeAbortReason; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; @@ -45,6 +51,9 @@ * Component fixtures stipulate authenticated current-source capture and authenticated definitive * owner readback. They do not implement or prove those absent producers, RPC or source-writer * gates. + * + *

Actual Account storage creation establishes fixture identity only. Supplied source counters + * and payloads remain stipulated capture, never current authorization evidence. */ @Testcontainers(disabledWithoutDocker = true) class DraftAuthorizationFencePostgresIntegrationTest { @@ -54,7 +63,7 @@ class DraftAuthorizationFencePostgresIntegrationTest { @Test void revokeBeforeCommitDeniesDelayedRequestsUntilBothDefinitiveAborts() { Context context = context(); - DraftAuthorizationFenceBinding binding = binding(); + DraftAuthorizationFenceBinding binding = binding(context); SourceChange change = change(binding); tx(context, () -> context.repository().reserve(binding)); assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); @@ -79,7 +88,7 @@ void revokeBeforeCommitDeniesDelayedRequestsUntilBothDefinitiveAborts() { @Test void abortedSourceChangeRetainsExactTerminalReasonAndCannotReopenOrBecomeMalformed() { Context context = context(); - DraftAuthorizationFenceBinding binding = binding(); + DraftAuthorizationFenceBinding binding = binding(context); SourceChange change = change(binding); tx(context, () -> context.repository().reserve(binding)); assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); @@ -149,7 +158,7 @@ void abortedSourceChangeRetainsExactTerminalReasonAndCannotReopenOrBecomeMalform @Test void worldCommittedAndGameDesignUnknownSurviveRestartAndBlockSourceUntilExactBothReadbacks() { Context context = context(); - DraftAuthorizationFenceBinding binding = binding(); + DraftAuthorizationFenceBinding binding = binding(context); tx(context, () -> context.repository().reserve(binding)); var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); SourceChange change = change(binding); @@ -158,6 +167,7 @@ void worldCommittedAndGameDesignUnknownSurviveRestartAndBlockSourceUntilExactBot Context restarted = new Context( context.dsl(), + context.dataSource(), new DraftAuthorizationFenceRepository(context.dsl()), context.transaction()); assertThat(tx(restarted, () -> restarted.repository().sourceMutationPermitted(change))) @@ -195,7 +205,7 @@ void worldCommittedAndGameDesignUnknownSurviveRestartAndBlockSourceUntilExactBot @Test void commitOrderWithBothDefinitiveAbortsReleasesOriginalWaitingIntentWithoutReopening() { Context context = context(); - DraftAuthorizationFenceBinding binding = binding(); + DraftAuthorizationFenceBinding binding = binding(context); tx(context, () -> context.repository().reserve(binding)); var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); SourceChange change = change(binding); @@ -240,7 +250,7 @@ void commitOrderWithBothDefinitiveAbortsReleasesOriginalWaitingIntentWithoutReop void bothMixedDirectionsFailNonpublicationAndReleaseOnlyAfterBothExactReadbacks() { for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { Context context = context(); - DraftAuthorizationFenceBinding binding = binding(); + DraftAuthorizationFenceBinding binding = binding(context); tx(context, () -> context.repository().reserve(binding)); var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); SourceChange change = change(binding); @@ -295,7 +305,7 @@ void bothMixedDirectionsFailNonpublicationAndReleaseOnlyAfterBothExactReadbacks( void revokeOrderWithEitherMixedDirectionCannotAuthorizeSourceMutation() { for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { Context context = context(); - DraftAuthorizationFenceBinding binding = binding(); + DraftAuthorizationFenceBinding binding = binding(context); tx(context, () -> context.repository().reserve(binding)); SourceChange change = change(binding); assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); @@ -328,7 +338,7 @@ void revokeOrderWithEitherMixedDirectionCannotAuthorizeSourceMutation() { @Test void changedCompleteBindingsConflictWithoutRewritingOriginal() { Context context = context(); - DraftAuthorizationFenceBinding original = binding(); + DraftAuthorizationFenceBinding original = binding(context); var stored = tx(context, () -> context.repository().reserve(original)); assertThat(tx(context, () -> context.repository().readSettlement(original))) .isEqualTo(Settlement.PENDING); @@ -345,7 +355,7 @@ void changedCompleteBindingsConflictWithoutRewritingOriginal() { @Test void inconsistentOrMalformedCompleteBindingsFailBeforeReservationStorage() { Context context = context(); - DraftAuthorizationFenceBinding b = binding(); + DraftAuthorizationFenceBinding b = binding(context); for (int field = 0; field < 9; field++) { int changedField = field; byte[] bytes = field == 6 ? new byte[] {11} : b.gameDesignBinding(); @@ -397,7 +407,7 @@ void inconsistentOrMalformedCompleteBindingsFailBeforeReservationStorage() { @Test void rollbackPreservesReservationAndIntentTogetherAndDisjointSourcesDoNotConflict() { Context context = context(); - DraftAuthorizationFenceBinding original = binding(); + DraftAuthorizationFenceBinding original = binding(context); assertThatThrownBy( () -> tx( @@ -412,7 +422,7 @@ void rollbackPreservesReservationAndIntentTogetherAndDisjointSourcesDoNotConflic .isInstanceOf(IllegalArgumentException.class); tx(context, () -> context.repository().reserve(original)); tx(context, () -> context.repository().requestSourceChange(change(original))); - DraftAuthorizationFenceBinding independent = binding(); + DraftAuthorizationFenceBinding independent = binding(context); tx(context, () -> context.repository().reserve(independent)); assertThat(tx(context, () -> context.repository().claimCommitOrder(independent)).ordering()) .isEqualTo(Ordering.COMMIT_ORDER); @@ -421,7 +431,7 @@ void rollbackPreservesReservationAndIntentTogetherAndDisjointSourcesDoNotConflic @Test void distinctPendingChangesCannotRetainTwoOldCapturesForTheSameSource() { Context context = context(); - DraftAuthorizationFenceBinding binding = binding(); + DraftAuthorizationFenceBinding binding = binding(context); SourceChange first = change(binding); SourceChange second = change(binding); tx(context, () -> context.repository().reserve(binding)); @@ -457,7 +467,7 @@ void distinctPendingChangesCannotRetainTwoOldCapturesForTheSameSource() { void concurrentDistinctSourceClaimsAdmitOnlyOnePendingCaptureWithoutBlockingDisjointSources() throws Exception { Context context = context(); - DraftAuthorizationFenceBinding binding = binding(); + DraftAuthorizationFenceBinding binding = binding(context); SourceChange first = change(binding); SourceChange second = change(binding); tx(context, () -> context.repository().reserve(binding)); @@ -492,7 +502,7 @@ void concurrentDistinctSourceClaimsAdmitOnlyOnePendingCaptureWithoutBlockingDisj assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) .isEqualTo(1); assertThat(tx(context, () -> context.repository().requestSourceChange(first))).isFalse(); - SourceChange disjoint = change(binding()); + SourceChange disjoint = change(binding(context)); assertThat(tx(context, () -> context.repository().requestSourceChange(disjoint))).isTrue(); assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) .isEqualTo(2); @@ -502,7 +512,7 @@ void concurrentDistinctSourceClaimsAdmitOnlyOnePendingCaptureWithoutBlockingDisj void concurrentCommitOrderAndRevocationChooseExactlyOneDurableOrdering() throws Exception { for (boolean commitWins : List.of(true, false)) { Context context = context(); - DraftAuthorizationFenceBinding binding = binding(); + DraftAuthorizationFenceBinding binding = binding(context); SourceChange change = change(binding); tx(context, () -> context.repository().reserve(binding)); CountDownLatch firstOrdered = new CountDownLatch(1); @@ -560,6 +570,315 @@ private void assertSourceGuardBlocked(Context context, SourceChange change) { .isInstanceOf(DataAccessException.class); } + @Test + void accountAndGlobalRolePendingScopesVersionOnlyTheirExistingAccountTuple() throws Exception { + for (SourceKind kind : List.of(SourceKind.ACCOUNT, SourceKind.GLOBAL_ROLES)) { + for (int isolation : + List.of(Connection.TRANSACTION_REPEATABLE_READ, Connection.TRANSACTION_SERIALIZABLE)) { + Context context = context(); + UUID account = binding(context).actorAccountId(); + UUID other = binding(context).actorAccountId(); + var before = context.dsl().fetch("SELECT * FROM accounts ORDER BY id"); + var authority = context.dsl().fetch("SELECT * FROM account_authority_generations"); + var fences = context.dsl().fetch("SELECT * FROM account_authority_issuance_fences"); + var sources = context.dsl().fetch("SELECT * FROM account_authority_source_records"); + var roles = context.dsl().fetch("SELECT * FROM account_global_role_sources"); + var events = context.dsl().fetch("SELECT * FROM account_authority_outbox_events"); + String originalVersion = accountVersion(context, account); + String otherVersion = accountVersion(context, other); + try (Connection stale = context.dataSource().getConnection()) { + stale.setAutoCommit(false); + stale.setTransactionIsolation(isolation); + try (var statement = stale.createStatement()) { + statement.executeQuery("SELECT id FROM accounts").close(); + var absent = + statement.executeQuery( + "SELECT count(*) FROM account_draft_authorization_source_changes"); + assertThat(absent.next()).isTrue(); + assertThat(absent.getInt(1)).isZero(); + absent.close(); + } + SourceChange change = + new SourceChange(UUID.randomUUID(), List.of(source(kind, account)), new byte[] {12}); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isTrue(); + assertThat(accountVersion(context, account)).isNotEqualTo(originalVersion); + assertThat(accountVersion(context, other)).isEqualTo(otherVersion); + assertThat(context.dsl().fetch("SELECT * FROM accounts ORDER BY id")).isEqualTo(before); + assertThat(context.dsl().fetch("SELECT * FROM account_authority_generations")) + .isEqualTo(authority); + assertThat(context.dsl().fetch("SELECT * FROM account_authority_issuance_fences")) + .isEqualTo(fences); + assertThat(context.dsl().fetch("SELECT * FROM account_authority_source_records")) + .isEqualTo(sources); + assertThat(context.dsl().fetch("SELECT * FROM account_global_role_sources")) + .isEqualTo(roles); + assertThat(context.dsl().fetch("SELECT * FROM account_authority_outbox_events")) + .isEqualTo(events); + try (var lock = + stale.prepareStatement("SELECT id FROM accounts WHERE account_uuid = ? FOR SHARE")) { + lock.setObject(1, account); + assertThatThrownBy(lock::executeQuery) + .isInstanceOf(SQLException.class) + .extracting("SQLState") + .isEqualTo("40001"); + } + stale.rollback(); + } + } + } + } + + @Test + void producerLocksDeduplicatedAccountsInUuidOrderBeforeAnySourceLocks() throws Exception { + Context context = context(); + List accounts = + List.of(binding(context).actorAccountId(), binding(context).actorAccountId()).stream() + .sorted(java.util.Comparator.comparing(UUID::toString)) + .toList(); + UUID first = accounts.getFirst(); + UUID last = accounts.getLast(); + SourceChange change = + new SourceChange( + UUID.randomUUID(), + List.of( + source(SourceKind.ACCOUNT, last), + source(SourceKind.GLOBAL_ROLES, first), + source(SourceKind.GLOBAL_ROLES, last)), + new byte[] {12}); + tx( + context, + () -> { + for (SourceEvidence source : change.sources()) { + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + source.key()); + } + return null; + }); + CountDownLatch started = new CountDownLatch(1); + AtomicInteger waitingPid = new AtomicInteger(); + try (var executor = Executors.newSingleThreadExecutor()) { + var claimed = + tx( + context, + () -> { + context + .dsl() + .fetchOne("SELECT id FROM accounts WHERE account_uuid = ? FOR UPDATE", first); + int blockerPid = + Objects.requireNonNull( + context.dsl().fetchOne("SELECT pg_backend_pid() AS pid"), + "Expected blocking PostgreSQL backend") + .get("pid", Integer.class); + var task = + executor.submit( + () -> + tx( + context, + () -> { + context.dsl().execute("SET LOCAL lock_timeout = '10s'"); + waitingPid.set( + Objects.requireNonNull( + context + .dsl() + .fetchOne("SELECT pg_backend_pid() AS pid"), + "Expected waiting PostgreSQL backend") + .get("pid", Integer.class)); + started.countDown(); + return context.repository().requestSourceChange(change); + })); + await(started); + awaitBlocked(context, waitingPid.get(), blockerPid); + context + .dsl() + .fetchOne( + "SELECT id FROM accounts WHERE account_uuid = ? FOR UPDATE NOWAIT", last); + for (SourceEvidence source : change.sources()) { + context + .dsl() + .fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE NOWAIT", + source.key()); + } + return task; + }); + assertThat(claimed.get(15, TimeUnit.SECONDS)).isTrue(); + } + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isTrue(); + } + + @Test + void scopeInsertVersionsAccountBeforeTheExistingParentLockingTrigger() throws Exception { + Context context = context(); + UUID account = binding(context).actorAccountId(); + UUID change = UUID.randomUUID(); + String key = "ACCOUNT:" + account; + tx( + context, + () -> { + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_changes (change_id, binding, status) VALUES (?, ?, 'WAITING')", + change, + new byte[] {12}); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + key); + return null; + }); + CountDownLatch started = new CountDownLatch(1); + AtomicInteger waitingPid = new AtomicInteger(); + try (var executor = Executors.newSingleThreadExecutor()) { + var inserted = + tx( + context, + () -> { + context + .dsl() + .fetchOne( + "SELECT change_id FROM account_draft_authorization_source_changes WHERE change_id = ? FOR UPDATE", + change); + int blockerPid = + Objects.requireNonNull( + context.dsl().fetchOne("SELECT pg_backend_pid() AS pid"), + "Expected blocking PostgreSQL backend") + .get("pid", Integer.class); + var task = + executor.submit( + () -> + tx( + context, + () -> { + context.dsl().execute("SET LOCAL lock_timeout = '10s'"); + waitingPid.set( + Objects.requireNonNull( + context + .dsl() + .fetchOne("SELECT pg_backend_pid() AS pid"), + "Expected waiting PostgreSQL backend") + .get("pid", Integer.class)); + started.countDown(); + return context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_changed_scopes (change_id, source_key) VALUES (?, ?)", + change, + key); + })); + await(started); + awaitBlocked(context, waitingPid.get(), blockerPid); + try (Connection observer = context.dataSource().getConnection(); + var lock = + observer.prepareStatement( + "SELECT id FROM accounts WHERE account_uuid = ? FOR UPDATE NOWAIT")) { + lock.setObject(1, account); + assertThatThrownBy(lock::executeQuery) + .isInstanceOf(SQLException.class) + .extracting("SQLState") + .isEqualTo("55P03"); + } catch (SQLException failure) { + throw new IllegalStateException(failure); + } + return task; + }); + assertThat(inserted.get(15, TimeUnit.SECONDS)).isEqualTo(1); + } + } + + @Test + void applicableMissingOrMalformedAccountScopesDenyWithoutCreatingAccountOrIntent() { + Context context = context(); + UUID absent = UUID.randomUUID(); + SourceChange missing = + new SourceChange( + UUID.randomUUID(), List.of(source(SourceKind.ACCOUNT, absent)), new byte[] {12}); + assertThatThrownBy(() -> tx(context, () -> context.repository().requestSourceChange(missing))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("persisted Account"); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_locks"))) + .isZero(); + for (String key : + List.of( + "ACCOUNT:" + absent, + "GLOBAL_ROLES:" + absent, + "ACCOUNT:42", + "GLOBAL_ROLES:00000000-0000-0000-0000-000000000000", + "ACCOUNT")) { + assertThatThrownBy(() -> insertScope(context, key)).isInstanceOf(DataAccessException.class); + } + assertThat(context.dsl().fetchCount(DSL.table("accounts"))).isZero(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isZero(); + insertScope(context, "TENANT:" + absent); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_changed_scopes"))) + .isEqualTo(1); + } + + private void insertScope(Context context, String key) { + tx( + context, + () -> { + UUID change = UUID.randomUUID(); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_changes (change_id, binding, status) VALUES (?, ?, 'WAITING')", + change, + new byte[] {12}); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + key); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_changed_scopes (change_id, source_key) VALUES (?, ?)", + change, + key); + return null; + }); + } + + private static SourceEvidence source(SourceKind kind, UUID account) { + // Stipulated capture is retained exactly; its counters/payload never establish authority. + return new SourceEvidence( + kind, account.toString(), "3", "5", "stream/" + account, "2", new byte[] {7}); + } + + private static String accountVersion(Context context, UUID account) { + return Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT xmin::TEXT AS version FROM accounts WHERE account_uuid = ?", account), + "Expected persisted Account tuple version") + .get("version", String.class); + } + + private static void awaitBlocked(Context context, int waitingPid, int blockerPid) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + if (Boolean.TRUE.equals( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT ? = ANY(pg_blocking_pids(?)) AS blocked", blockerPid, waitingPid), + "Expected PostgreSQL blocking-state readback") + .get("blocked", Boolean.class))) { + return; + } + Thread.onSpinWait(); + } + throw new IllegalStateException("Source producer did not block on the first Account lock"); + } + private Context context() { String schema = "draft_fence_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource source = new DriverManagerDataSource(); @@ -579,11 +898,21 @@ private Context context() { TransactionTemplate transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - return new Context(dsl, new DraftAuthorizationFenceRepository(dsl), transaction); + return new Context(dsl, source, new DraftAuthorizationFenceRepository(dsl), transaction); } - private DraftAuthorizationFenceBinding binding() { - UUID account = UUID.randomUUID(); + private DraftAuthorizationFenceBinding binding(Context context) { + UUID account = + tx( + context, + () -> { + Account row = new Account(); + String suffix = UUID.randomUUID().toString(); + row.setUsername("draft-" + suffix); + row.setEmail(suffix + "@example.test"); + row.setPasswordHash("synthetic-verifier"); + return new AccountRepository(context.dsl()).save(row).getAccountUuid(); + }); SourceEvidence source = new SourceEvidence( SourceKind.ACCOUNT, @@ -727,6 +1056,7 @@ private static void await(CountDownLatch latch) { private record Context( DSLContext dsl, + DriverManagerDataSource dataSource, DraftAuthorizationFenceRepository repository, TransactionTemplate transaction) {} } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index 9c4d66c218..6c328fc8c1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -46,7 +46,7 @@ */ class AccountGameplayAdmissionLeasePersistenceIntegrationTest { private static final AccountPostgresIntegrationFixture POSTGRES = - new AccountPostgresIntegrationFixture(); + new AccountPostgresIntegrationFixture(true); private static final String TENANT = "22222222-2222-4222-8222-222222222222"; private static final String OTHER = "33333333-3333-4333-8333-333333333333"; @@ -60,6 +60,14 @@ static void stop() { POSTGRES.stop(); } + @Test + void fixtureUsesDurablePrimarySettingsRequiredByCommitConfirmation() { + var settings = POSTGRES.verifyDurablePrimary(); + assertThat(settings.inRecovery()).isFalse(); + assertThat(settings.fsync()).isEqualTo("on"); + assertThat(settings.synchronousCommit()).isEqualTo("on"); + } + @Test void actualAbortOwnerRecoversLostResponseAndRetainsOriginalDecisionAndCleanup() throws Exception { var context = context(null); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java index 385f8db1a6..9c39fd7365 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -1173,7 +1173,7 @@ void pendingAndWorldTerminalLifecycleRowsDenyWithoutChangingOwnerState() throws fixture.tenantId(), fixture.identity()))) .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class) - .hasMessage("Account lifecycle invalidation is unresolved for this Account and tenant"); + .hasMessage("Account-wide or target-tenant invalidation is unresolved"); assertThat(accountSemanticSnapshot(fixture.harness().dsl(), fixture.harness().accountId())) .isEqualTo(accountBefore); @@ -1315,6 +1315,365 @@ void lifecycleOperationForAnotherTenantDoesNotDenyExactAdmissionScope() throws E assertThat(captured.membershipSource().membership().tenantId()).isEqualTo(fixture.tenantId()); } + @Test + void accountWidePendingSourcesDenyEveryTenantButRemainAccountScoped() throws Exception { + for (GlobalPendingKind pendingKind : GlobalPendingKind.values()) { + AdmissionSourceFixture fixture = newAdmissionSourceFixture(); + UUID accountId = fixture.harness().accountId(); + UUID otherTenant = UUID.randomUUID(); + Account otherAccount = createAccount(fixture.harness().context()); + String accountBefore = accountSemanticSnapshot(fixture.harness().dsl(), accountId); + String sourceBefore = accountAuthoritySourceSnapshot(fixture.harness().dsl(), accountId); + long eventsBefore = accountAuthorityEventCount(fixture.harness().dsl(), accountId); + String roleSourceBefore = accountGlobalRoleSourceSnapshot(fixture.harness().dsl(), accountId); + String generationBefore = + accountAuthorityGenerationSnapshot(fixture.harness().dsl(), accountId); + String issuanceFenceBefore = accountIssuanceFenceSnapshot(fixture.harness().dsl(), accountId); + + seedGlobalPending(fixture, pendingKind); + + assertThatThrownBy( + () -> + inRepeatableReadTransaction( + fixture.harness().context(), + () -> + fixture + .admissionReader() + .readCurrent(accountId, fixture.tenantId(), fixture.identity()))) + .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class) + .hasMessage("Account-wide or target-tenant invalidation is unresolved"); + assertThatThrownBy( + () -> + inRepeatableReadTransaction( + fixture.harness().context(), + () -> { + new AccountLifecyclePendingDenialReader(fixture.harness().dsl()) + .requireNoPending(accountId, otherTenant); + return null; + })) + .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class); + inRepeatableReadTransaction( + fixture.harness().context(), + () -> { + new AccountLifecyclePendingDenialReader(fixture.harness().dsl()) + .requireNoPending(otherAccount.getAccountUuid(), fixture.tenantId()); + return null; + }); + + assertThat(accountSemanticSnapshot(fixture.harness().dsl(), accountId)) + .isEqualTo(accountBefore); + assertThat(accountAuthoritySourceSnapshot(fixture.harness().dsl(), accountId)) + .isEqualTo(sourceBefore); + assertThat(accountAuthorityEventCount(fixture.harness().dsl(), accountId)) + .isEqualTo(eventsBefore); + assertThat(accountGlobalRoleSourceSnapshot(fixture.harness().dsl(), accountId)) + .isEqualTo(roleSourceBefore); + assertThat(accountAuthorityGenerationSnapshot(fixture.harness().dsl(), accountId)) + .isEqualTo(generationBefore); + assertThat(accountIssuanceFenceSnapshot(fixture.harness().dsl(), accountId)) + .isEqualTo(issuanceFenceBefore); + assertThat( + Objects.requireNonNull( + fixture + .harness() + .dsl() + .fetchOne( + "SELECT state FROM account_gameplay_token_identity_fences " + + "WHERE operation_id = ?", + fixture.identity().operationId())) + .get(0, String.class)) + .isEqualTo("ACTIVE"); + } + } + + @Test + void terminalDraftSourceChangesDoNotClearWaitingSecurityStateOperation() throws Exception { + for (String terminalStatus : List.of("SOURCE_COMMITTED", "SOURCE_ABORTED")) { + AdmissionSourceFixture fixture = newAdmissionSourceFixture(); + SecurityStatePendingFixture waiting = insertSecurityStateWaitingFixture(fixture); + inTransaction( + fixture.harness().context(), + () -> { + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(fixture.harness().dsl()); + if ("SOURCE_ABORTED".equals(terminalStatus)) { + fences.markSourceAborted( + waiting.sourceChange(), + DraftAuthorizationFenceRepository.SourceChangeAbortReason.DEFINITIVE_ABORT); + } else { + fences.markSourceCommitted(waiting.sourceChange()); + } + return null; + }); + + assertThat( + Objects.requireNonNull( + fixture + .harness() + .dsl() + .fetchOne( + "SELECT status FROM account_security_state_operations " + + "WHERE request_id = ?", + waiting.requestId())) + .get(0, String.class)) + .isEqualTo("WAITING"); + assertThatThrownBy( + () -> + inRepeatableReadTransaction( + fixture.harness().context(), + () -> + fixture + .admissionReader() + .readCurrent( + fixture.harness().accountId(), + fixture.tenantId(), + fixture.identity()))) + .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class); + } + } + + @Test + void membershipAndTenantSourceChangesAreNotPromotedToAccountWideDenials() throws Exception { + AdmissionSourceFixture fixture = newAdmissionSourceFixture(); + insertScopedSourceChangeFixture(fixture, SourceKind.MEMBERSHIP, fixture.tenantId()); + insertScopedSourceChangeFixture(fixture, SourceKind.TENANT, fixture.tenantId()); + + var captured = + inRepeatableReadTransaction( + fixture.harness().context(), + () -> + fixture + .admissionReader() + .readCurrent( + fixture.harness().accountId(), fixture.tenantId(), fixture.identity())); + + assertThat(captured.membershipSource().membership().tenantId()).isEqualTo(fixture.tenantId()); + } + + @Test + void accountWidePendingInsertInvalidatesStaleRepeatableReadAndSerializableSnapshots() + throws Exception { + for (GlobalPendingKind pendingKind : GlobalPendingKind.values()) { + for (int isolation : + List.of( + TransactionDefinition.ISOLATION_REPEATABLE_READ, + TransactionDefinition.ISOLATION_SERIALIZABLE)) { + AdmissionSourceFixture fixture = newAdmissionSourceFixture(); + DSLContext dsl = fixture.harness().dsl(); + UUID accountId = fixture.harness().accountId(); + String accountBefore = accountSemanticSnapshot(dsl, accountId); + String sourceBefore = accountAuthoritySourceSnapshot(dsl, accountId); + long eventsBefore = accountAuthorityEventCount(dsl, accountId); + CountDownLatch writerLockedAccount = new CountDownLatch(1); + CountDownLatch readerSnapshotEstablished = new CountDownLatch(1); + CountDownLatch readerIsChecking = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + TransactionTemplate writerTransaction = + new TransactionTemplate(fixture.harness().context().manager()); + writerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var writer = + executor.submit( + () -> + writerTransaction.execute( + transaction -> { + Record lockedAccount = + dsl.fetchOne( + "SELECT account_uuid FROM accounts " + + "WHERE account_uuid = ? FOR UPDATE", + accountId); + if (lockedAccount == null) { + throw new IllegalStateException( + "Account-wide pending writer could not lock the exact Account"); + } + writerLockedAccount.countDown(); + awaitLatch( + readerSnapshotEstablished, + "reader to establish its stale Account-wide snapshot"); + awaitLatch( + readerIsChecking, "reader to attempt its Account-wide predicate"); + seedGlobalPending(fixture, pendingKind); + return null; + })); + + var reader = + executor.submit( + () -> { + awaitLatch(writerLockedAccount, "writer to lock the Account"); + TransactionTemplate readerTransaction = + new TransactionTemplate(fixture.harness().context().manager()); + readerTransaction.setIsolationLevel(isolation); + try { + readerTransaction.execute( + transaction -> { + establishPendingSnapshot(dsl, accountId, pendingKind); + readerSnapshotEstablished.countDown(); + readerIsChecking.countDown(); + new AccountLifecyclePendingDenialReader(dsl) + .requireNoPending(accountId, fixture.tenantId()); + return null; + }); + return null; + } catch (RuntimeException failure) { + return failure; + } + }); + + RuntimeException readerFailure = reader.get(15, TimeUnit.SECONDS); + writer.get(15, TimeUnit.SECONDS); + assertThat(readerFailure) + .as("an old %s snapshot cannot miss %s", isolation, pendingKind) + .isInstanceOf( + AccountLifecyclePendingDenialReader.PendingStateUnavailableException.class); + assertThat(sqlState(readerFailure)).isEqualTo("40001"); + assertThat(accountSemanticSnapshot(dsl, accountId)).isEqualTo(accountBefore); + assertThat(accountAuthoritySourceSnapshot(dsl, accountId)).isEqualTo(sourceBefore); + assertThat(accountAuthorityEventCount(dsl, accountId)).isEqualTo(eventsBefore); + } finally { + readerSnapshotEstablished.countDown(); + readerIsChecking.countDown(); + executor.shutdownNow(); + } + } + } + } + + @Test + void readCommittedReaderAndAccountWidePendingPublicationSerializeInBothOrders() throws Exception { + for (GlobalPendingKind pendingKind : GlobalPendingKind.values()) { + assertReadCommittedReaderWaitsThenDenies(fixtureForGlobalPendingRace(), pendingKind); + assertAccountWidePublicationWaitsForReadCommittedReader( + fixtureForGlobalPendingRace(), pendingKind); + } + } + + private AdmissionSourceFixture fixtureForGlobalPendingRace() throws Exception { + return newAdmissionSourceFixture(); + } + + private void assertReadCommittedReaderWaitsThenDenies( + AdmissionSourceFixture fixture, GlobalPendingKind pendingKind) throws Exception { + DSLContext dsl = fixture.harness().dsl(); + UUID accountId = fixture.harness().accountId(); + CountDownLatch writerInserted = new CountDownLatch(1); + CountDownLatch readerAttempting = new CountDownLatch(1); + CountDownLatch releaseWriter = new CountDownLatch(1); + AtomicReference readerBackendPid = new AtomicReference<>(); + var executor = Executors.newFixedThreadPool(2); + try { + TransactionTemplate writerTransaction = + new TransactionTemplate(fixture.harness().context().manager()); + writerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var writer = + executor.submit( + () -> + writerTransaction.execute( + transaction -> { + lockAccountForPendingFixture(dsl, accountId); + seedGlobalPending(fixture, pendingKind); + writerInserted.countDown(); + awaitLatch(releaseWriter, "release Account-wide pending writer"); + return null; + })); + var reader = + executor.submit( + () -> { + awaitLatch(writerInserted, "writer to insert Account-wide pending evidence"); + TransactionTemplate readerTransaction = + new TransactionTemplate(fixture.harness().context().manager()); + readerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + try { + readerTransaction.execute( + transaction -> { + readerBackendPid.set(currentBackendPid(dsl)); + readerAttempting.countDown(); + new AccountLifecyclePendingDenialReader(dsl) + .requireNoPending(accountId, fixture.tenantId()); + return null; + }); + return null; + } catch (RuntimeException failure) { + return failure; + } + }); + + awaitLatch(readerAttempting, "READ_COMMITTED reader to attempt Account lock"); + awaitBackendLockWait(dsl, Objects.requireNonNull(readerBackendPid.get())); + assertThat(reader.isDone()).isFalse(); + releaseWriter.countDown(); + writer.get(15, TimeUnit.SECONDS); + RuntimeException readerFailure = reader.get(15, TimeUnit.SECONDS); + assertThat(readerFailure) + .as("READ_COMMITTED reader observes committed %s after waiting for Account", pendingKind) + .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class); + } finally { + releaseWriter.countDown(); + executor.shutdownNow(); + } + } + + private void assertAccountWidePublicationWaitsForReadCommittedReader( + AdmissionSourceFixture fixture, GlobalPendingKind pendingKind) throws Exception { + DSLContext dsl = fixture.harness().dsl(); + UUID accountId = fixture.harness().accountId(); + CountDownLatch readerOwnsAccount = new CountDownLatch(1); + CountDownLatch releaseReader = new CountDownLatch(1); + CountDownLatch writerAttempting = new CountDownLatch(1); + AtomicReference writerBackendPid = new AtomicReference<>(); + var executor = Executors.newFixedThreadPool(2); + try { + TransactionTemplate readerTransaction = + new TransactionTemplate(fixture.harness().context().manager()); + readerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var reader = + executor.submit( + () -> + readerTransaction.execute( + transaction -> { + new AccountLifecyclePendingDenialReader(dsl) + .requireNoPending(accountId, fixture.tenantId()); + readerOwnsAccount.countDown(); + awaitLatch(releaseReader, "release READ_COMMITTED denial reader"); + return null; + })); + awaitLatch(readerOwnsAccount, "READ_COMMITTED reader to hold the Account lock"); + + TransactionTemplate writerTransaction = + new TransactionTemplate(fixture.harness().context().manager()); + writerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var writer = + executor.submit( + () -> + writerTransaction.execute( + transaction -> { + writerBackendPid.set(currentBackendPid(dsl)); + writerAttempting.countDown(); + seedGlobalPending(fixture, pendingKind); + return null; + })); + + awaitLatch(writerAttempting, "Account-wide pending publisher to attempt its Account lock"); + awaitBackendLockWait(dsl, Objects.requireNonNull(writerBackendPid.get())); + assertThat(writer.isDone()).isFalse(); + releaseReader.countDown(); + reader.get(15, TimeUnit.SECONDS); + writer.get(15, TimeUnit.SECONDS); + assertThatThrownBy( + () -> + inRepeatableReadTransaction( + fixture.harness().context(), + () -> { + new AccountLifecyclePendingDenialReader(dsl) + .requireNoPending(accountId, fixture.tenantId()); + return null; + })) + .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class); + } finally { + releaseReader.countDown(); + executor.shutdownNow(); + } + } + @Test void membershipRoleSnapshotMustStillMatchItsCommittedCurrentEvent() throws Exception { AdmissionSourceFixture fixture = newAdmissionSourceFixture(); @@ -1656,6 +2015,244 @@ private AdmissionSourceFixture newAdmissionSourceFixture() throws Exception { identity); } + private void seedGlobalPending(AdmissionSourceFixture fixture, GlobalPendingKind pendingKind) { + switch (pendingKind) { + case SECURITY_STATE -> insertSecurityStateWaitingFixture(fixture); + case ACCOUNT_SOURCE -> + insertScopedSourceChangeFixture( + fixture, SourceKind.ACCOUNT, fixture.harness().accountId()); + case GLOBAL_ROLES_SOURCE -> + insertScopedSourceChangeFixture( + fixture, SourceKind.GLOBAL_ROLES, fixture.harness().accountId()); + } + } + + /** + * Stores valid Account-owned WAITING operation evidence for denial testing only. The fixture + * supplies no authenticated owner decision and performs no Account source mutation. + */ + private SecurityStatePendingFixture insertSecurityStateWaitingFixture( + AdmissionSourceFixture fixture) { + return inTransaction( + fixture.harness().context(), + () -> { + DSLContext dsl = fixture.harness().dsl(); + UUID accountUuid = fixture.harness().accountId(); + Account account = + new AccountRepository(dsl, fixture.harness().sources()) + .findByAccountUuid(accountUuid) + .orElseThrow(); + var source = + fixture + .harness() + .sources() + .readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountUuid) + .account(); + Record roleRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT global_roles, global_role_source_version " + + "FROM account_global_role_sources WHERE account_uuid = ? FOR SHARE", + accountUuid)); + long roleVersion = roleRow.get("global_role_source_version", Long.class); + AccountState before = + new AccountState( + account.isEmailVerified(), + AccountLoginAuthModes.read(account.getLoginAuthModes()).stream() + .map(Enum::name) + .sorted() + .toList(), + java.util.Arrays.stream(roleRow.get("global_roles", String[].class)) + .sorted() + .toList(), + account.getLifecycleState().name()); + AccountState after = + new AccountState( + true, before.loginAuthModes(), before.globalRoles(), before.lifecycleState()); + UUID requestId = UUID.randomUUID(); + AccountSecurityStateMutationRequest request = + new AccountSecurityStateMutationRequest( + requestId, + accountUuid, + securityStateCorrelation(accountUuid, requestId), + source.generation(), + source.sourceVersion(), + AccountSecurityStateOperationRepository.detectedKinds(before, after), + after); + long checkpointSequence = source.checkpoint().sequence(); + byte[] checkpointPayload = + checkpointSequence == 0L + ? new byte[0] + : new AccountAuthorityOutboxRepository(dsl) + .findEvent(accountStream(accountUuid), checkpointSequence) + .orElseThrow() + .payload(); + Capture draft = + new Capture( + account.getId(), + account.getAccountUuidProvenance(), + before, + new AccountAuthorityGenerationRepository.ScopeState( + source.scope(), + source.generation(), + source.sourceVersion(), + source.issuanceFence()), + checkpointSequence, + checkpointPayload, + roleVersion, + null); + byte[] captureBytes = + AccountSecurityStateOperationRepository.captureBytes(request, draft); + SourceEvidence accountSource = + new SourceEvidence( + SourceKind.ACCOUNT, + accountUuid.toString(), + Long.toString(source.generation()), + Long.toString(source.sourceVersion()), + accountStream(accountUuid), + Long.toString(checkpointSequence), + captureBytes); + SourceChange sourceChange = + new SourceChange(UUID.randomUUID(), List.of(accountSource), captureBytes); + Capture capture = + new Capture( + draft.accountId(), + draft.provenance(), + before, + draft.sourceState(), + checkpointSequence, + checkpointPayload, + roleVersion, + sourceChange); + DraftAuthorizationFenceRepository fences = new DraftAuthorizationFenceRepository(dsl); + if (!fences.requestSourceChange(sourceChange)) { + throw new IllegalStateException("Security-state fixture source change is unresolved"); + } + new AccountSecurityStateOperationRepository(dsl).claim(request, capture); + return new SecurityStatePendingFixture(requestId, sourceChange); + }); + } + + /** Creates an exact-scope source-change row for negative-predicate tests only. */ + private SourceChange insertScopedSourceChangeFixture( + AdmissionSourceFixture fixture, SourceKind kind, UUID scopeUuid) { + return inTransaction( + fixture.harness().context(), + () -> { + UUID accountUuid = fixture.harness().accountId(); + String scopeId; + String generation = null; + String sourceVersion = "1"; + String checkpointStream = null; + String checkpointSequence = null; + byte[] evidence = opaquePendingSourceEvidence(kind, accountUuid, scopeUuid); + if (kind == SourceKind.ACCOUNT) { + var source = + fixture + .harness() + .sources() + .readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountUuid) + .account(); + scopeId = accountUuid.toString(); + generation = Long.toString(source.generation()); + sourceVersion = Long.toString(source.sourceVersion()); + checkpointStream = accountStream(accountUuid); + checkpointSequence = Long.toString(source.checkpoint().sequence()); + } else if (kind == SourceKind.GLOBAL_ROLES) { + Record role = + Objects.requireNonNull( + fixture + .harness() + .dsl() + .fetchOne( + "SELECT global_role_source_version " + + "FROM account_global_role_sources WHERE account_uuid = ?", + accountUuid)); + scopeId = accountUuid.toString(); + sourceVersion = Long.toString(role.get("global_role_source_version", Long.class)); + } else if (kind == SourceKind.MEMBERSHIP) { + scopeId = accountUuid + "/" + scopeUuid; + } else if (kind == SourceKind.TENANT) { + scopeId = scopeUuid.toString(); + } else { + throw new IllegalArgumentException("Unsupported source-change fixture scope"); + } + SourceEvidence source = + new SourceEvidence( + kind, + scopeId, + generation, + sourceVersion, + checkpointStream, + checkpointSequence, + evidence); + byte[] mutation = opaquePendingSourceEvidence(kind, accountUuid, scopeUuid); + SourceChange change = new SourceChange(UUID.randomUUID(), List.of(source), mutation); + boolean settled = + new DraftAuthorizationFenceRepository(fixture.harness().dsl()) + .requestSourceChange(change); + if (!settled) { + throw new IllegalStateException("Pending-source fixture has unresolved owners"); + } + return change; + }); + } + + private static byte[] opaquePendingSourceEvidence( + SourceKind kind, UUID accountUuid, UUID scopeUuid) { + return ("synthetic-denial-only-source:" + kind + ":" + accountUuid + ":" + scopeUuid) + .getBytes(StandardCharsets.US_ASCII); + } + + private static void establishPendingSnapshot( + DSLContext dsl, UUID accountUuid, GlobalPendingKind pendingKind) { + if (pendingKind == GlobalPendingKind.SECURITY_STATE) { + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM account_security_state_operations WHERE account_uuid = ?", + accountUuid)); + return; + } + String sourceKey = + (pendingKind == GlobalPendingKind.ACCOUNT_SOURCE ? "ACCOUNT:" : "GLOBAL_ROLES:") + + accountUuid; + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM account_draft_authorization_source_changes c " + + "JOIN account_draft_authorization_changed_scopes s ON s.change_id = c.change_id " + + "WHERE c.status = 'WAITING' AND s.source_key = ?", + sourceKey)); + } + + private static void lockAccountForPendingFixture(DSLContext dsl, UUID accountUuid) { + if (dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", accountUuid) + == null) { + throw new IllegalStateException("Account-wide pending writer could not lock the Account"); + } + } + + private static int currentBackendPid(DSLContext dsl) { + return Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")).get(0, Integer.class); + } + + private static void awaitBackendLockWait(DSLContext dsl, int backendPid) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10L); + while (System.nanoTime() < deadline) { + Record activity = + dsl.fetchOne("SELECT wait_event_type FROM pg_stat_activity WHERE pid = ?", backendPid); + if (activity != null && "Lock".equals(activity.get(0, String.class))) return; + try { + Thread.sleep(10L); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for PostgreSQL lock evidence", interrupted); + } + } + throw new IllegalStateException("PostgreSQL did not expose the expected Account row lock wait"); + } + /** * Creates opaque shape-valid storage evidence only. This fixture does not represent an * authenticated caller, valid World request, or actual invalidation publisher. @@ -1778,6 +2375,35 @@ private static String accountAuthoritySourceSnapshot(DSLContext dsl, UUID accoun .get(0, String.class); } + private static String accountGlobalRoleSourceSnapshot(DSLContext dsl, UUID accountId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(role_row)::text FROM account_global_role_sources role_row " + + "WHERE account_uuid = ?", + accountId)) + .get(0, String.class); + } + + private static String accountAuthorityGenerationSnapshot(DSLContext dsl, UUID accountId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COALESCE(jsonb_agg(to_jsonb(generation_row) " + + "ORDER BY generation_row.scope_kind, generation_row.tenant_uuid)::text, '[]') " + + "FROM account_authority_generations generation_row " + + "WHERE account_uuid = ?", + accountId)) + .get(0, String.class); + } + + private static String accountIssuanceFenceSnapshot(DSLContext dsl, UUID accountId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(fence_row)::text FROM account_authority_issuance_fences fence_row " + + "WHERE account_uuid = ?", + accountId)) + .get(0, String.class); + } + private static String sqlState(Throwable failure) { for (Throwable cause = failure; cause != null; cause = cause.getCause()) { if (cause instanceof SQLException sqlException && sqlException.getSQLState() != null) { @@ -3208,6 +3834,14 @@ private enum CommitHook { CAPTURE_COMMIT_PROOF } + private enum GlobalPendingKind { + SECURITY_STATE, + ACCOUNT_SOURCE, + GLOBAL_ROLES_SOURCE + } + + private record SecurityStatePendingFixture(UUID requestId, SourceChange sourceChange) {} + private record CommitHarness( TestContext context, DSLContext 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 d65bd20204..7f6ceb2993 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java @@ -4,6 +4,7 @@ import java.net.URI; import java.util.Properties; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.PostgreSQLContainer; @@ -14,21 +15,32 @@ public final class AccountPostgresIntegrationFixture { private final PostgreSQLContainer container; private final String externalJdbcUrl; + private final boolean requireDurablePrimary; private boolean started; public AccountPostgresIntegrationFixture() { + this(false); + } + + public AccountPostgresIntegrationFixture(boolean requireDurablePrimary) { + this.requireDurablePrimary = requireDurablePrimary; String configuredUrl = System.getenv(JDBC_URL_ENV); if (configuredUrl != null && !configuredUrl.isBlank()) { externalJdbcUrl = validateLoopbackJdbcUrl(configuredUrl); container = null; } else { externalJdbcUrl = null; - container = new PostgreSQLContainer<>("postgres:16-alpine"); + container = + new PostgreSQLContainer<>("postgres:16-alpine") + .withCommand(postgresCommand(requireDurablePrimary)); } } public void start() { if (container == null) { + if (requireDurablePrimary) { + verifyDurablePrimary(); + } return; } assumeTrue( @@ -36,6 +48,14 @@ public void start() { "Docker is unavailable; set " + JDBC_URL_ENV + " to an isolated loopback PostgreSQL URL"); container.start(); started = true; + if (requireDurablePrimary) { + try { + verifyDurablePrimary(); + } catch (RuntimeException unsuitable) { + stop(); + throw unsuitable; + } + } } public void stop() { @@ -90,6 +110,48 @@ public DriverManagerDataSource dataSource(String schema) { return dataSource; } + /** Reads and validates the live PostgreSQL settings required by durable commit confirmation. */ + public DurablePrimarySettings verifyDurablePrimary() { + DurablePrimarySettings settings = + new JdbcTemplate(dataSource()) + .queryForObject( + "SELECT pg_is_in_recovery(), current_setting('fsync'), " + + "current_setting('synchronous_commit')", + (result, rowNumber) -> + new DurablePrimarySettings( + result.getBoolean(1), result.getString(2), result.getString(3))); + if (settings == null) { + throw new IllegalStateException("Durable PostgreSQL primary settings are unavailable"); + } + validateDurablePrimarySettings( + settings.inRecovery(), settings.fsync(), settings.synchronousCommit()); + return settings; + } + + static String[] postgresCommand(boolean requireDurablePrimary) { + if (requireDurablePrimary) { + return new String[] {"postgres", "-c", "fsync=on", "-c", "synchronous_commit=on"}; + } + return new String[] {"postgres", "-c", "fsync=off"}; + } + + static void validateDurablePrimarySettings( + boolean inRecovery, String fsync, String synchronousCommit) { + if (inRecovery || !"on".equals(fsync) || !"on".equals(synchronousCommit)) { + throw new IllegalStateException( + "Durable PostgreSQL primary required (pg_is_in_recovery=false, fsync=on, " + + "synchronous_commit=on); observed pg_is_in_recovery=" + + inRecovery + + ", fsync=" + + fsync + + ", synchronous_commit=" + + synchronousCommit); + } + } + + public record DurablePrimarySettings( + boolean inRecovery, String fsync, String synchronousCommit) {} + static String validateLoopbackJdbcUrl(String jdbcUrl) { final URI uri; try { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java index 4d39468d9a..380feebeb2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java @@ -3,10 +3,39 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; class AccountPostgresIntegrationFixtureTest { + @Test + void durablePrimaryConfigurationIsOptInAndRequiresFlushedLocalCommits() { + assertThat(Arrays.asList(AccountPostgresIntegrationFixture.postgresCommand(false))) + .containsExactly("postgres", "-c", "fsync=off"); + assertThat(Arrays.asList(AccountPostgresIntegrationFixture.postgresCommand(true))) + .containsExactly("postgres", "-c", "fsync=on", "-c", "synchronous_commit=on"); + + assertThatThrownBy( + () -> + AccountPostgresIntegrationFixture.validateDurablePrimarySettings( + false, "off", "on")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Durable PostgreSQL primary required"); + assertThatThrownBy( + () -> + AccountPostgresIntegrationFixture.validateDurablePrimarySettings(true, "on", "on")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Durable PostgreSQL primary required"); + assertThatThrownBy( + () -> + AccountPostgresIntegrationFixture.validateDurablePrimarySettings( + false, "on", "off")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Durable PostgreSQL primary required"); + + AccountPostgresIntegrationFixture.validateDurablePrimarySettings(false, "on", "on"); + } + @Test void acceptsIpv4AndBracketedIpv6LoopbackUrls() { for (String jdbcUrl : 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 d4e556e4b1..4ada1c1fee 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 @@ -7,15 +7,23 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.Arrays; import java.util.HexFormat; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; @@ -30,6 +38,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.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository.Capture; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; @@ -39,6 +49,7 @@ import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; @@ -207,6 +218,7 @@ void pairCasFailureRollsBackMembershipAndTheActualOutboxAppend() { void terminalCoordinatorCommitsAuditAndOperationWithTheFirstEventAndReplaysExactly() { Fixture fixture = newFixture(); var proof = fixture.commitFirstJoin(); + fixture.seedGlobalPending(GlobalPendingKind.SECURITY_STATE); var replay = fixture.commitFirstJoin(); String stream = fixture.membershipStream(); var operation = @@ -294,13 +306,48 @@ void unresolvedLifecycleJournalRowsDenyNewFirstJoinWithoutChangingJoinOwnerState assertLifecycleJournalDeniesFirstJoin("WORLD_TERMINAL"); } + @Test + void accountWidePendingSourcesDenyNewFirstJoinWithoutChangingJoinOwnerState() { + for (GlobalPendingKind pendingKind : GlobalPendingKind.values()) { + Fixture fixture = newFixture(); + Account otherAccount = fixture.createAccount(); + UUID otherTenant = UUID.randomUUID(); + fixture.seedGlobalPending(pendingKind); + JoinOwnerSnapshot before = fixture.joinOwnerSnapshot(); + + assertThatThrownBy(fixture::commitFirstJoin) + .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class) + .hasMessage("Account-wide or target-tenant invalidation is unresolved"); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> { + new AccountLifecyclePendingDenialReader(fixture.dsl) + .requireNoPending(fixture.account.getAccountUuid(), otherTenant); + return null; + })) + .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class); + fixture.inTransaction( + () -> { + new AccountLifecyclePendingDenialReader(fixture.dsl) + .requireNoPending(otherAccount.getAccountUuid(), fixture.tenantUuid); + return null; + }); + + assertThat(fixture.joinOwnerSnapshot()).isEqualTo(before); + if (pendingKind == GlobalPendingKind.SECURITY_STATE) { + assertThat(fixture.countAll("account_security_state_operations")).isEqualTo(1L); + } + } + } + private void assertLifecycleJournalDeniesFirstJoin(String status) { Fixture fixture = newFixture(); fixture.seedLifecycleOperation(status); assertThatThrownBy(fixture::commitFirstJoin) .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class) - .hasMessage("Account lifecycle invalidation is unresolved for this Account and tenant"); + .hasMessage("Account-wide or target-tenant invalidation is unresolved"); assertThat( Objects.requireNonNull( fixture.dsl.fetchOne( @@ -567,6 +614,215 @@ private void seedLifecycleOperation(String status) { } } + private void seedGlobalPending(GlobalPendingKind pendingKind) { + if (pendingKind == GlobalPendingKind.SECURITY_STATE) { + seedSecurityStateWaitingOperation(); + return; + } + SourceKind kind = + pendingKind == GlobalPendingKind.ACCOUNT_SOURCE + ? SourceKind.ACCOUNT + : SourceKind.GLOBAL_ROLES; + seedDraftSourceChange(kind, account.getAccountUuid()); + } + + /** A stored owner-operation shape only; no authenticated security decision is asserted. */ + private void seedSecurityStateWaitingOperation() { + inTransaction( + () -> { + Account current = accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); + var source = + sourceEvidence + .readCurrentIssuerAccountSources(ACCOUNT_ISSUER, account.getAccountUuid()) + .account(); + var roleRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT global_roles, global_role_source_version " + + "FROM account_global_role_sources WHERE account_uuid = ? FOR SHARE", + account.getAccountUuid())); + long roleVersion = roleRow.get("global_role_source_version", Long.class); + AccountState before = + new AccountState( + current.isEmailVerified(), + AccountLoginAuthModes.read(current.getLoginAuthModes()).stream() + .map(Enum::name) + .sorted() + .toList(), + Arrays.stream(roleRow.get("global_roles", String[].class)).sorted().toList(), + current.getLifecycleState().name()); + AccountState after = + new AccountState( + true, before.loginAuthModes(), before.globalRoles(), before.lifecycleState()); + UUID operationId = UUID.randomUUID(); + AccountSecurityStateMutationRequest request = + new AccountSecurityStateMutationRequest( + operationId, + account.getAccountUuid(), + securityStateCorrelation(account.getAccountUuid(), operationId), + source.generation(), + source.sourceVersion(), + AccountSecurityStateOperationRepository.detectedKinds(before, after), + after); + long checkpointSequence = source.checkpoint().sequence(); + byte[] checkpointPayload = + checkpointSequence == 0L + ? new byte[0] + : outbox + .findEvent(accountStream(account.getAccountUuid()), checkpointSequence) + .orElseThrow() + .payload(); + Capture draft = + new Capture( + current.getId(), + current.getAccountUuidProvenance(), + before, + new AccountAuthorityGenerationRepository.ScopeState( + source.scope(), + source.generation(), + source.sourceVersion(), + source.issuanceFence()), + checkpointSequence, + checkpointPayload, + roleVersion, + null); + byte[] capture = AccountSecurityStateOperationRepository.captureBytes(request, draft); + SourceEvidence accountSource = + new SourceEvidence( + SourceKind.ACCOUNT, + account.getAccountUuid().toString(), + Long.toString(source.generation()), + Long.toString(source.sourceVersion()), + accountStream(account.getAccountUuid()), + Long.toString(checkpointSequence), + capture); + SourceChange change = + new SourceChange(UUID.randomUUID(), List.of(accountSource), capture); + Capture complete = + new Capture( + draft.accountId(), + draft.provenance(), + before, + draft.sourceState(), + checkpointSequence, + checkpointPayload, + roleVersion, + change); + DraftAuthorizationFenceRepository fences = new DraftAuthorizationFenceRepository(dsl); + if (!fences.requestSourceChange(change)) { + throw new IllegalStateException("Security-state source fixture is unresolved"); + } + new AccountSecurityStateOperationRepository(dsl).claim(request, complete); + return null; + }); + } + + private SourceChange seedDraftSourceChange(SourceKind kind, UUID scopeUuid) { + return inTransaction( + () -> { + String scopeId; + String generation = null; + String sourceVersion = "1"; + String checkpointStream = null; + String checkpointSequence = null; + byte[] payload = opaqueBytes("pending-source-evidence"); + if (kind == SourceKind.ACCOUNT) { + var source = + sourceEvidence + .readCurrentIssuerAccountSources(ACCOUNT_ISSUER, account.getAccountUuid()) + .account(); + scopeId = account.getAccountUuid().toString(); + generation = Long.toString(source.generation()); + sourceVersion = Long.toString(source.sourceVersion()); + checkpointStream = accountStream(account.getAccountUuid()); + checkpointSequence = Long.toString(source.checkpoint().sequence()); + } else if (kind == SourceKind.GLOBAL_ROLES) { + var role = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT global_role_source_version FROM account_global_role_sources " + + "WHERE account_uuid = ?", + account.getAccountUuid())); + scopeId = account.getAccountUuid().toString(); + sourceVersion = Long.toString(role.get("global_role_source_version", Long.class)); + } else if (kind == SourceKind.MEMBERSHIP) { + scopeId = account.getAccountUuid() + "/" + scopeUuid; + } else if (kind == SourceKind.TENANT) { + scopeId = scopeUuid.toString(); + } else { + throw new IllegalArgumentException("Unsupported source-change fixture scope"); + } + SourceEvidence source = + new SourceEvidence( + kind, + scopeId, + generation, + sourceVersion, + checkpointStream, + checkpointSequence, + payload); + SourceChange change = + new SourceChange( + UUID.randomUUID(), List.of(source), opaqueBytes("pending-source-mutation")); + if (!new DraftAuthorizationFenceRepository(dsl).requestSourceChange(change)) { + throw new IllegalStateException("Pending source fixture has unresolved owners"); + } + return change; + }); + } + + private JoinOwnerSnapshot joinOwnerSnapshot() { + UUID accountUuid = account.getAccountUuid(); + String accountStream = accountStream(accountUuid); + UUID auditEventId = + UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); + return new JoinOwnerSnapshot( + rowSetJson(dsl, "accounts", "account_uuid = ?", accountUuid), + rowSetJson( + dsl, "account_authority_source_records", "outbox_stream_key = ?", accountStream), + rowSetJson(dsl, "account_authority_generations", "account_uuid = ?", accountUuid), + rowSetJson(dsl, "account_authority_issuance_fences", "account_uuid = ?", accountUuid), + rowSetJson(dsl, "account_global_role_sources", "account_uuid = ?", accountUuid), + rowSetJson( + dsl, + "account_tenant_membership", + "account_uuid = ? AND tenant_uuid = ?", + accountUuid, + tenantUuid), + rowSetJson( + dsl, + "account_membership_pair_authority", + "account_uuid = ? AND tenant_uuid = ?", + accountUuid, + tenantUuid), + rowSetJson( + dsl, + "account_tenant_membership_role_snapshots", + "membership_id IN (SELECT id FROM account_tenant_membership " + + "WHERE account_uuid = ? AND tenant_uuid = ?)", + accountUuid, + tenantUuid), + rowSetJson( + dsl, + "account_tenant_membership_role_snapshot_roles", + "membership_id IN (SELECT id FROM account_tenant_membership " + + "WHERE account_uuid = ? AND tenant_uuid = ?)", + accountUuid, + tenantUuid), + rowSetJson( + dsl, "account_authority_outbox_events", "outbox_stream_key = ?", accountStream), + rowSetJson( + dsl, + "account_authority_outbox_events", + "outbox_stream_key = ?", + "account:auth-authority:v1:membership/" + accountUuid + "/" + tenantUuid), + rowSetJson(dsl, "account_audit_outbox", "audit_event_id = ?", auditEventId), + rowSetJson(dsl, "account_join_operations", "request_id = ?", requestId), + rowSetJson( + dsl, "account_gameplay_token_identity_fences", "account_uuid = ?", accountUuid)); + } + private static byte[] opaqueBytes(String label) { return ("opaque-fixture:" + label + ":" + UUID.randomUUID()).getBytes(StandardCharsets.UTF_8); } @@ -702,4 +958,52 @@ private static long positiveRandomLong() { } private record TestContext(DSLContext dsl, TransactionTemplate transaction) {} + + private static String rowSetJson( + DSLContext dsl, String table, String predicate, Object... parameters) { + String query = + "SELECT COALESCE(jsonb_agg(to_jsonb(owner_row) " + + "ORDER BY to_jsonb(owner_row)::text)::text, '[]') FROM " + + table + + " owner_row WHERE " + + predicate; + return Objects.requireNonNull(dsl.fetchOne(query, parameters)).get(0, String.class); + } + + private static String accountStream(UUID accountUuid) { + return "account:auth-authority:v1:account/" + accountUuid; + } + + private static byte[] securityStateCorrelation(UUID accountUuid, UUID operationId) { + return ("{\"actorAccountUuid\":\"" + + accountUuid + + "\",\"ownerEvidenceDigest\":\"sha256:" + + "a".repeat(64) + + "\",\"ownerOperationId\":\"" + + operationId + + "\",\"schemaVersion\":\"account-security-state-caller-correlation/v1\"}") + .getBytes(StandardCharsets.UTF_8); + } + + private enum GlobalPendingKind { + SECURITY_STATE, + ACCOUNT_SOURCE, + GLOBAL_ROLES_SOURCE + } + + private record JoinOwnerSnapshot( + String account, + String accountSource, + String authorityGenerations, + String issuanceFences, + String globalRoles, + String membership, + String pairAuthority, + String roleSnapshot, + String roleSnapshotRoles, + String accountEvents, + String membershipEvents, + String audit, + String joinOperation, + String gameplayTokenFences) {} } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReaderTest.java index ece09e1ff7..f2af445e03 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReaderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReaderTest.java @@ -18,12 +18,22 @@ import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.mockito.InOrder; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountLifecyclePendingDenialReaderTest { private static final UUID ACCOUNT = UUID.randomUUID(); private static final UUID TENANT = UUID.randomUUID(); + private static final String DENIAL_SQL = + "SELECT EXISTS (SELECT 1 FROM account_lifecycle_serving_operations " + + "WHERE account_uuid = ? AND tenant_uuid = ? " + + "AND status IN ('PENDING', 'WORLD_TERMINAL')) " + + "OR EXISTS (SELECT 1 FROM account_security_state_operations " + + "WHERE account_uuid = ? AND status = 'WAITING') " + + "OR EXISTS (SELECT 1 FROM account_draft_authorization_source_changes c " + + "JOIN account_draft_authorization_changed_scopes s ON s.change_id = c.change_id " + + "WHERE c.status = 'WAITING' AND s.source_key IN (?, ?))"; @AfterEach void clearTransaction() { @@ -31,7 +41,7 @@ void clearTransaction() { } @Test - void pendingOperationDeniesAfterLockingExactAccount() { + void pendingAccountOrTargetTenantOperationDeniesAfterLockingExactAccount() { DSLContext dsl = mock(DSLContext.class); Record account = accountRow(); Record pending = mock(Record.class); @@ -42,20 +52,13 @@ void pendingOperationDeniesAfterLockingExactAccount() { assertThatThrownBy( () -> new AccountLifecyclePendingDenialReader(dsl).requireNoPending(ACCOUNT, TENANT)) .isInstanceOf(PendingOperationException.class) - .hasMessage("Account lifecycle invalidation is unresolved for this Account and tenant"); + .hasMessage("Account-wide or target-tenant invalidation is unresolved"); var ordered = inOrder(dsl); ordered .verify(dsl) .fetchOne("SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", ACCOUNT); - ordered - .verify(dsl) - .fetchOne( - "SELECT EXISTS (SELECT 1 FROM account_lifecycle_serving_operations " - + "WHERE account_uuid = ? AND tenant_uuid = ? " - + "AND status IN ('PENDING', 'WORLD_TERMINAL'))", - ACCOUNT, - TENANT); + verifyDenialQuery(ordered, dsl); } @Test @@ -69,13 +72,7 @@ void noPendingOperationDoesNotTripTheDenialPredicate() { new AccountLifecyclePendingDenialReader(dsl).requireNoPending(ACCOUNT, TENANT); - verify(dsl) - .fetchOne( - "SELECT EXISTS (SELECT 1 FROM account_lifecycle_serving_operations " - + "WHERE account_uuid = ? AND tenant_uuid = ? " - + "AND status IN ('PENDING', 'WORLD_TERMINAL'))", - ACCOUNT, - TENANT); + verifyDenialQuery(dsl); } @Test @@ -89,13 +86,7 @@ void readCommittedWritableOwnerTransactionIsAllowedForNegativePredicate() { new AccountLifecyclePendingDenialReader(dsl).requireNoPending(ACCOUNT, TENANT); - verify(dsl) - .fetchOne( - "SELECT EXISTS (SELECT 1 FROM account_lifecycle_serving_operations " - + "WHERE account_uuid = ? AND tenant_uuid = ? " - + "AND status IN ('PENDING', 'WORLD_TERMINAL'))", - ACCOUNT, - TENANT); + verifyDenialQuery(dsl); } @Test @@ -117,14 +108,7 @@ void datasourceDefaultReadCommittedIsolationIsAccepted() { ordered .verify(dsl) .fetchOne("SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", ACCOUNT); - ordered - .verify(dsl) - .fetchOne( - "SELECT EXISTS (SELECT 1 FROM account_lifecycle_serving_operations " - + "WHERE account_uuid = ? AND tenant_uuid = ? " - + "AND status IN ('PENDING', 'WORLD_TERMINAL'))", - ACCOUNT, - TENANT); + verifyDenialQuery(ordered, dsl); } @Test @@ -251,6 +235,19 @@ private static Record accountRow() { return account; } + private static void verifyDenialQuery(DSLContext dsl) { + verify(dsl) + .fetchOne( + DENIAL_SQL, ACCOUNT, TENANT, ACCOUNT, "ACCOUNT:" + ACCOUNT, "GLOBAL_ROLES:" + ACCOUNT); + } + + private static void verifyDenialQuery(InOrder ordered, DSLContext dsl) { + ordered + .verify(dsl) + .fetchOne( + DENIAL_SQL, ACCOUNT, TENANT, ACCOUNT, "ACCOUNT:" + ACCOUNT, "GLOBAL_ROLES:" + ACCOUNT); + } + private static void transaction(int isolation) { TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java index 71077e778b..2e48b7e4d5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java @@ -149,7 +149,7 @@ void pendingLifecycleOperationDeniesBeforeAnyJoinMutationOrPublication() { fixture.arrangePending(); doThrow( new AccountLifecyclePendingDenialReader.PendingOperationException( - "Account lifecycle invalidation is unresolved for this Account and tenant")) + "Account-wide or target-tenant invalidation is unresolved")) .when(fixture.pendingReader) .requireNoPending(ACCOUNT_ID, TENANT_ID); fixture.startWritableTransaction(); @@ -159,7 +159,7 @@ void pendingLifecycleOperationDeniesBeforeAnyJoinMutationOrPublication() { fixture.coordinator.commitCanonicalFirstJoin( fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class) - .hasMessage("Account lifecycle invalidation is unresolved for this Account and tenant"); + .hasMessage("Account-wide or target-tenant invalidation is unresolved"); InOrder ordered = inOrder(fixture.operations, fixture.pendingReader); ordered.verify(fixture.operations).lockAccount(17L); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java index 5f936f83bd..b18a1a5002 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java @@ -108,13 +108,13 @@ void pendingLifecycleDenialStopsBeforeEntitlementAndTokenReads() { Fixture fixture = new Fixture(); doThrow( new AccountLifecyclePendingDenialReader.PendingOperationException( - "Account lifecycle invalidation is unresolved for this Account and tenant")) + "Account-wide or target-tenant invalidation is unresolved")) .when(fixture.lifecyclePendingDenials) .requireNoPending(ACCOUNT, TENANT); assertThatThrownBy(fixture::read) .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class) - .hasMessage("Account lifecycle invalidation is unresolved for this Account and tenant"); + .hasMessage("Account-wide or target-tenant invalidation is unresolved"); var ordered = inOrder(fixture.memberships, fixture.lifecyclePendingDenials); ordered.verify(fixture.memberships).readCurrent(ACCOUNT, TENANT); From 2b19e46fa4adb4c3c0c8434f4867cca6d9f86b81 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:25:34 +1300 Subject: [PATCH 14/16] fix(account): observe durable admission proof before tuple-lock WAL --- .../account-service/api-contracts.md | 2 +- design/project-management/ai-observations.md | 6 + .../player-access-and-session.md | 2 + ...AdmissionCommitConfirmationRepository.java | 35 ++++- ..._admission_durable_commit_confirmation.sql | 108 ++++++++++----- ...issionLeasePersistenceIntegrationTest.java | 129 ++++++++++++++++++ ...ssionCommitConfirmationRepositoryTest.java | 46 ++++++- 7 files changed, 281 insertions(+), 47 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 2ba10c807e..e4f953bca6 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -285,7 +285,7 @@ The canonical membership, entitlement response shape, freshness, and sequence co The admission owner remains unregistered and non-admitting. Its cancellation and exact negative-state readback methods accept only the original same-namespace Game Session workload and complete unchanged lease evidence; `ReadGameplayAdmissionLease` currently requires `expected_lease` and returns only `PENDING` or `ABORTED`, not `not_observed` or raw storage `COMMITTED`. The positive acquire/finalize/read/reconcile surface is not enabled. The canonical expiry and confirmation requirement is owned by [Session Behavior](../../system-architecture-session-behavior.md#admission-lease-durable-confirmation). -The separate Account-local temporal confirmation preparation stamps the actual finalization transaction and derives immutable proof from independent committed operation readback, ordered PostgreSQL WAL insertion/flush coverage on one primary, and a subsequent conservatively rounded database-time bound before the original expiry. It requires durable storage settings; unavailable or uncovered WAL, same-transaction finalization and late observation remain denied. Receipt creation must commit before a new transaction independently proves and reads the durable receipt; caller-supplied bounds and bare LSNs carried across a reconnect cannot substitute. Original operation, lease, digest, decision and deadline remain unchanged. This is not an authenticated positive admission result, a current restriction-source producer, Game Session installation proof or completed cleanup. Implementation and executed versus unavailable proof belong to the [Account admission tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-admission-lease-prerequisite). +The separate Account-local temporal confirmation preparation stamps the actual finalization transaction and derives immutable proof from independent committed operation readback, ordered PostgreSQL WAL insertion/flush coverage on one primary, and a subsequent conservatively rounded database-time bound before the original expiry. Capture the fixed coverage fence after independent committed observation but before the confirmation transaction emits tuple-lock WAL; then lock Account first and revalidate the exact immutable operation before accepting covered WAL and the time bound. Independently durable receipt readback follows the same observation, capture and locked-revalidation ordering. It requires durable storage settings; unavailable or uncovered WAL, same-transaction finalization and late observation remain denied. Receipt creation must commit before a new transaction independently proves and reads the durable receipt; caller-supplied bounds and bare LSNs carried across a reconnect cannot substitute. Original operation, lease, digest, decision and deadline remain unchanged. This is not an authenticated positive admission result, a current restriction-source producer, Game Session installation proof or completed cleanup. Implementation and executed versus unavailable proof belong to the [Account admission tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-admission-lease-prerequisite). ## Subject-Binding Rules (Normative) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 547c7422ce..dc2071f006 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -77,3 +77,9 @@ Entry format: - Expected pattern: opt durability-sensitive suites into durable PostgreSQL settings from startup, read back primary and WAL settings explicitly, and reject an unsuitable external database without changing it. Do not weaken a production guard or infer that re-enabling `fsync` repairs previously unsafe data. - Current status: the scoped startup/readback repair is prepared; corrected physical confirmation execution remains required, including idle-database WAL coverage. Other test suites retain their existing fixture configuration. - Reconsideration trigger: update proof after corrected exact-head PostgreSQL execution; distinguish local compilation/skips and ordinary row visibility from established durability. + +- `2026-10-08`: A durability observer can accidentally wait for its own uncommitted lock WAL + - Observation: PostgreSQL tuple locks emit WAL. Capturing the insertion fence after those locks can include an uncommitted partial WAL page that an idle primary need not flush, causing conservative confirmation failure despite an already durable original COMMIT. This is an availability defect, not evidence of unsafe positive confirmation. + - Expected pattern: independently observe the committed operation or receipt, capture its fixed coverage fence before own tuple locks, then lock in canonical Account-first order and revalidate exact immutable evidence before checking flush coverage and the original database-time bound. Never force a marker or extend the deadline to make proof pass. + - Current status: the SQL and Java ordering correction and idle-primary/stale-snapshot definitions are prepared; physical execution remains required. Assertions must not depend on asynchronous background WAL flushing remaining idle. + - Reconsideration trigger: consume corrected exact-head PostgreSQL proof; unrelated concurrent WAL can still conservatively prevent coverage, and unavailable proof remains denied. 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 c35fc4743f..9a567b49da 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,6 +10,8 @@ This is a non-normative implementation tracker for player access and session. Ca Latest physical evidence supersedes the local-only confirmation evidence below: exact `28a1ef9a53be8c8423f34738d05fe3509a61dc57` [CI run 37709000871](https://github.com/benhook1013/FireMUD/actions/runs/37709000871), on merge `da108e97de9d01688abe3ef4a24ea64b2cf7386c` with exact base `7985e8a6f6354587f5c01649ede3d0cecde9fde2`, executes 1,339 Account cases with seven skips and five failures. All eighteen lease PostgreSQL cases execute: thirteen pass, while five confirmation cases reject the fixture's non-durable primary configuration. The installed Testcontainers PostgreSQL 2.0.5 constructor defaults to `fsync=off`. The corrected lease suite opts into `fsync=on` and `synchronous_commit=on` from container startup and explicitly reads back those settings and primary status; an unsuitable external database is rejected without changing its configuration. This repair preserves the production durability guard and all eighteen existing lease cases, adding one live-settings test. Corrected confirmation success and idle-database WAL coverage remain unproved; passing unrelated storage cases does not establish them. +The corrected durability observer captures its fixed insertion fence after independent committed observation and before its own tuple-lock WAL, then takes Account-first locks and revalidates the complete immutable operation or receipt. Otherwise an idle primary can conservatively fail coverage by waiting for the observer's own uncommitted partial WAL page. Java calls the SQL proof function before its exact locked carrier readback; both remain in the owned writable SERIALIZABLE transaction. New definitions preserve all nineteen prior lease cases and add pre-lock capture/independent idle readback and deterministic stale-snapshot `40001`; concurrent exact retained replay also runs after the original expiry without changing the receipt. Local R55 passes full Account checks, jOOQ generation, formatting, static analysis, integration compilation, boot packaging and documentation checks in 2m37s: 1,170 unit cases and eight non-database integration cases execute without failures/errors, three unit cases skip and all 173 PostgreSQL cases skip. The twenty-one lease PostgreSQL definitions compile but do not execute locally. The automatic [42a2083 CI run](https://github.com/benhook1013/FireMUD/actions/runs/37711528914) selected a module matrix without Account, so it supplies no corrected Account execution proof; a full exact-head manual run is required. Background writer timing is not asserted to remain idle, and unrelated uncovered WAL still denies rather than forcing a flush or extending expiry. Current authority, finalization, installation and activation remain separately gated. + The pending-denial extension also checks Account security-state `WAITING` operations and exact `ACCOUNT:` / `GLOBAL_ROLES:` source changes in `WAITING`, independently of the target tenant's lifecycle journal. V91 versions only the matching persisted Account tuple, preserving logical state, counters, events and retained pending evidence. Source-change producers lock sorted, deduplicated Accounts before source and operation locks. New PostgreSQL definitions cover stale snapshots, both READ_COMMITTED lock orders, cross-account and cross-tenant scope, unchanged source/JOIN state, terminal draft changes that cannot clear a separate security operation, and historical committed JOIN replay. Corrected local R53 passes full Account checks, jOOQ generation, formatting, static analysis, integration compilation, boot packaging and documentation validation. Its test reports retain 1,170 executed unit outcomes with three skips and zero failures/errors from R52's unchanged unit boundary; eight non-database integration cases execute and 171 PostgreSQL cases skip without Docker. Flyway sanity passes twelve sets and 169 versioned files. R51 exposed three integration-fixture compilation errors and R52 exposed seven nullable fixture readbacks; bounded corrections preserve the denial assertions and use explicit non-null checks, not suppressions. These additions are negative protection only, not authenticated restriction authorization or a positive admission result; their new physical execution remains required. The separate unregistered durability-confirmation preparation adds V90's database-stamped top-level finalization transaction identity and immutable exact-bound receipt. An independent committed operation, primary database with `fsync` enabled, ordered WAL-insert/flush coverage and subsequently rounded-up database clock establish a bound strictly before the original expiry. Bounded polling against one fixed WAL fence creates no marker, forces no flush and renews no deadline. The protected same-namespace Game Session owner commits receipt creation, then independently commits exact durable readback before returning the temporal value. Retained unstamped commits, rollback, self/subtransaction visibility, late or uncovered proof, changed identity and ambiguous readback remain denied. A retained receipt can be recovered later without rewriting its original evidence; it proves no current authority, World release, Game Session installation or gameplay admission. Seven additive PostgreSQL definitions preserve all eleven existing lease cases and cover real Java-owner/SQL timely and lost-response receipt recovery, late physical COMMIT, same-transaction rejection, retained/rolled-back denial, forged proof and immutability, uncommitted receipt rejection and concurrent exact retention. Local full Account checks, generation, formatting, static analysis, integration-source compilation, boot packaging and documentation checks passed in 2m18s: 1,170 unit and seven non-database integration cases executed, with three unit skips and 158 PostgreSQL skips, zero failures/errors. All eight confirmation-owner and four repository unit cases passed; all eighteen lease PostgreSQL definitions compiled but skipped. Flyway sanity passed twelve sets and 168 versioned files. Physical V90 execution, deterministic uncovered asynchronous WAL, recovery/disabled-fsync and remote-failover durability remain unproved. The preceding exact `17e8f609dcbe4ef4dc096b8bfe82557a68bbe9ef` checkpoint has successful [CI run 37706751965](https://github.com/benhook1013/FireMUD/actions/runs/37706751965) on composed merge `cd66dcf2618404caddba413731d50a32748ed705` against base `7985e8a6f6354587f5c01649ede3d0cecde9fde2`: 1,320 Account cases executed, seven skipped and zero failures/errors. All eleven then-existing lease PostgreSQL cases, six first-JOIN PostgreSQL cases and five World-client mTLS cases executed; that older proof does not establish V90. Acquire/finalize/reconcile RPCs remain unimplemented, raw storage `COMMITTED` remains denied by the negative-state read adapter, and the complete current-restriction producer and Game Session installation/cleanup are still required. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java index 04d1a1ecfd..4887402f54 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionCommitConfirmation; @@ -9,6 +10,7 @@ import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import org.jooq.DSLContext; import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Unregistered, non-admitting storage confirmation for an already retained COMMITTED lease. @@ -32,33 +34,45 @@ public AccountGameplayAdmissionCommitConfirmationRepository( /** Creates or exactly replays a database-stamped receipt for the original proven COMMIT. */ AccountGameplayAdmissionCommitConfirmation confirmCommitted( AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { - AccountGameplayAdmissionLeaseOperation operation = exactCommitted(evidence, bindingDecisionId); + UUID requestId = validateRequest(evidence, bindingDecisionId); Record row = dsl.fetchOne( "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", - requestId(evidence), + requestId, evidence.sha256(), bindingDecisionId); + if (row == null) throw unavailable(); + AccountGameplayAdmissionLeaseOperation operation = exactCommitted(evidence, bindingDecisionId); return confirmation(row, operation); } /** Reads only a committed, independently durable receipt; this path never creates one. */ AccountGameplayAdmissionCommitConfirmation readCommitConfirmation( AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { - AccountGameplayAdmissionLeaseOperation operation = exactCommitted(evidence, bindingDecisionId); + UUID requestId = validateRequest(evidence, bindingDecisionId); Record row = dsl.fetchOne( "SELECT * FROM account_gameplay_admission_read_commit_confirmation(?, ?, ?)", - requestId(evidence), + requestId, evidence.sha256(), bindingDecisionId); + if (row == null) throw unavailable(); + AccountGameplayAdmissionLeaseOperation operation = exactCommitted(evidence, bindingDecisionId); return confirmation(row, operation); } - private AccountGameplayAdmissionLeaseOperation exactCommitted( + private static UUID validateRequest( AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { + requireWritableSerializableTransaction(); Objects.requireNonNull(evidence); + UUID requestId = requestId(evidence); + requireUuidV4(requestId); requireUuidV4(bindingDecisionId); + return requestId; + } + + private AccountGameplayAdmissionLeaseOperation exactCommitted( + AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { AccountGameplayAdmissionLeaseOperation operation = leaseRepository .readExact(evidence) @@ -102,9 +116,18 @@ private static UUID requestId(AccountGameplayAdmissionLeaseEvidence evidence) { return UUID.fromString((String) evidence.carrier().get("requestId")); } + private static void requireWritableSerializableTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_SERIALIZABLE) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException("Writable SERIALIZABLE Account transaction required"); + } + } + private static void requireUuidV4(UUID value) { if (value == null || value.version() != 4 || value.variant() != 2) - throw new IllegalArgumentException("Canonical non-nil UUIDv4 decision identity required"); + throw new IllegalArgumentException("Canonical non-nil UUIDv4 identity required"); } private static IllegalStateException unavailable() { diff --git a/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql b/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql index e8c4c0d72a..ebd0d45bf5 100644 --- a/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql +++ b/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql @@ -105,6 +105,7 @@ $$; CREATE FUNCTION account_gameplay_admission_confirmation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE operation account_gameplay_admission_lease_operations%ROWTYPE; + locked_operation account_gameplay_admission_lease_operations%ROWTYPE; finalization_status TEXT; insert_fence pg_lsn; flush_fence pg_lsn; @@ -128,13 +129,7 @@ BEGIN RAISE EXCEPTION 'Account admission confirmation operation missing' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_operation_required'; END IF; - PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; - IF NOT FOUND THEN - RAISE EXCEPTION 'Account admission confirmation owner missing' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_owner_required'; - END IF; - SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = NEW.request_id; - IF NOT FOUND OR operation.status <> 'COMMITTED' OR operation.finalization_xid IS NULL + IF operation.status <> 'COMMITTED' OR operation.finalization_xid IS NULL OR NEW.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 OR NEW.binding_decision_id IS DISTINCT FROM operation.binding_decision_id THEN RAISE EXCEPTION 'Account admission confirmation exact committed binding required' @@ -154,15 +149,28 @@ BEGIN RAISE EXCEPTION 'Account admission confirmation durable primary required' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_durable_primary'; END IF; - -- Independent committed visibility precedes this insert fence; its original COMMIT WAL is - -- therefore no later than the fence. Never carry an unconfirmed fence across connections. + -- Independent committed visibility precedes this fixed insert fence; the original COMMIT + -- WAL is therefore covered. Capture BEFORE this proof transaction's tuple locks emit WAL: + -- an idle primary need not flush an uncommitted partial page containing those lock records. insert_fence := pg_current_wal_insert_lsn(); IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; END IF; - -- A fixed fence permits read-only polling while lock WAL is flushed naturally. The bounded - -- observation budget is not a new lease deadline, and no flush or new marker is forced. + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_owner_required'; + END IF; + SELECT * INTO locked_operation FROM account_gameplay_admission_lease_operations + WHERE request_id = NEW.request_id FOR UPDATE; + IF NOT FOUND OR locked_operation IS DISTINCT FROM operation THEN + RAISE EXCEPTION 'Account admission confirmation exact committed binding required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; + END IF; + -- Account-first locking serializes first receipt creation, and exact locked revalidation + -- preserves the independently observed immutable operation. Only the pre-lock fence needs + -- coverage; this bounded polling creates no marker, forces no flush and renews no deadline. FOR observation IN 1..50 LOOP flush_fence := pg_current_wal_flush_lsn(); -- A separate statement AFTER each flush observation is essential: SQL expression order @@ -211,36 +219,52 @@ BEGIN RAISE EXCEPTION 'Account admission confirmation operation missing' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_operation_required'; END IF; + IF operation.status <> 'COMMITTED' OR operation.finalization_xid IS NULL + OR expected_sha IS DISTINCT FROM operation.evidence_sha256 + OR expected_decision IS DISTINCT FROM operation.binding_decision_id THEN + RAISE EXCEPTION 'Account admission confirmation exact committed binding required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; + END IF; + SELECT * INTO receipt FROM account_gameplay_admission_commit_confirmations WHERE request_id = requested_request_id; + IF NOT FOUND THEN + -- The INSERT guard owns initial proof observation and capture before any tuple lock. + -- A concurrent stale SERIALIZABLE insertion reports 40001 through ON CONFLICT rather + -- than leaking a raw uniqueness failure. No caller proof or renewed deadline is accepted. + INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) + VALUES (requested_request_id, expected_sha, expected_decision) + ON CONFLICT (request_id) DO NOTHING RETURNING * INTO receipt; + IF FOUND THEN + RETURN NEXT receipt; + RETURN; + END IF; + END IF; + -- Exact retained replay may occur after expiry. It locks Account first and revalidates the + -- immutable original decision, but neither re-proves nor replaces the receipt's timing bound. PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; IF NOT FOUND THEN RAISE EXCEPTION 'Account admission confirmation owner missing' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_owner_required'; END IF; - SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = requested_request_id; + SELECT * INTO operation FROM account_gameplay_admission_lease_operations + WHERE request_id = requested_request_id FOR UPDATE; IF NOT FOUND OR operation.status <> 'COMMITTED' OR operation.finalization_xid IS NULL OR expected_sha IS DISTINCT FROM operation.evidence_sha256 OR expected_decision IS DISTINCT FROM operation.binding_decision_id THEN RAISE EXCEPTION 'Account admission confirmation exact committed binding required' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; END IF; - SELECT * INTO receipt FROM account_gameplay_admission_commit_confirmations WHERE request_id = requested_request_id; - IF FOUND THEN - IF receipt.account_uuid IS DISTINCT FROM operation.account_uuid - OR receipt.lease_id IS DISTINCT FROM operation.lease_id - OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence - OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 - OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id - OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms - OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid THEN - RAISE EXCEPTION 'Account admission confirmation immutable binding conflict' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_conflict'; - END IF; - RETURN NEXT receipt; - RETURN; + SELECT * INTO receipt FROM account_gameplay_admission_commit_confirmations + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR receipt.account_uuid IS DISTINCT FROM operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid THEN + RAISE EXCEPTION 'Account admission confirmation immutable binding conflict' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_conflict'; END IF; - -- No supplied timestamps, transaction IDs, WAL positions or renewed deadline are accepted. - INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) - VALUES (requested_request_id, expected_sha, expected_decision) RETURNING * INTO receipt; RETURN NEXT receipt; END; $$; @@ -251,6 +275,8 @@ RETURNS SETOF account_gameplay_admission_commit_confirmations LANGUAGE plpgsql A DECLARE operation account_gameplay_admission_lease_operations%ROWTYPE; receipt account_gameplay_admission_commit_confirmations%ROWTYPE; + locked_operation account_gameplay_admission_lease_operations%ROWTYPE; + locked_receipt account_gameplay_admission_commit_confirmations%ROWTYPE; insert_fence pg_lsn; flush_fence pg_lsn; observation INTEGER; @@ -260,12 +286,6 @@ BEGIN RAISE EXCEPTION 'Account admission confirmation operation missing' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_operation_required'; END IF; - PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; - IF NOT FOUND THEN - RAISE EXCEPTION 'Account admission confirmation owner missing' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_owner_required'; - END IF; - SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = requested_request_id; SELECT * INTO receipt FROM account_gameplay_admission_commit_confirmations WHERE request_id = requested_request_id; IF NOT FOUND OR operation.status IS DISTINCT FROM 'COMMITTED' OR expected_sha IS DISTINCT FROM operation.evidence_sha256 @@ -291,11 +311,29 @@ BEGIN RAISE EXCEPTION 'Account admission confirmation durable primary required' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_durable_primary'; END IF; + -- Capture after independent receipt visibility, before Account/operation/receipt lock WAL. insert_fence := pg_current_wal_insert_lsn(); IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; END IF; + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_owner_required'; + END IF; + SELECT * INTO locked_operation FROM account_gameplay_admission_lease_operations + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR locked_operation IS DISTINCT FROM operation THEN + RAISE EXCEPTION 'Account admission confirmation exact durable receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_receipt_required'; + END IF; + SELECT * INTO locked_receipt FROM account_gameplay_admission_commit_confirmations + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR locked_receipt IS DISTINCT FROM receipt THEN + RAISE EXCEPTION 'Account admission confirmation exact durable receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_receipt_required'; + END IF; FOR observation IN 1..50 LOOP flush_fence := pg_current_wal_flush_lsn(); EXIT WHEN flush_fence IS NOT NULL AND flush_fence >= insert_fence; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index 6c328fc8c1..c72bd24077 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -774,6 +774,126 @@ void durableConfirmationStoresOriginalCommitProofAndRecoversLostResponseAfterExp assertFailedExactRead(readOwner, original); } + @Test + void idlePrimaryConfirmationCapturesBeforeLocksAndIndependentlyReadsExactReceipt() { + var context = context(null); + var original = pending(context, account(context)); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID decision = UUID.randomUUID(); + tx(context, () -> repository.recordCommitted(original, decision)); + var unchanged = storageSnapshot(context); + + // This fixture is idle: no marker, forced flush or unrelated writer is used to make proof + // succeed. The original finalizer's synchronous COMMIT already covers the pre-lock fence. + var receipt = + tx( + context, + () -> { + String beforeLocks = + Objects.requireNonNull( + context.dsl().fetchOne("SELECT pg_current_wal_insert_lsn()::text AS lsn")) + .get("lsn", String.class); + var created = confirm(context, original, decision); + assertThat(created.get("wal_insert_lsn", String.class)).isEqualTo(beforeLocks); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT pg_current_wal_insert_lsn() > ?::pg_lsn AS advanced", + beforeLocks)) + .get("advanced", Boolean.class)) + .isTrue(); + return created; + }); + + tx( + context, + () -> { + String beforeLocks = + Objects.requireNonNull( + context.dsl().fetchOne("SELECT pg_current_wal_insert_lsn()::text AS lsn")) + .get("lsn", String.class); + assertThat(readConfirmation(context, original, decision)).isEqualTo(receipt); + // Independent exact readback succeeds with its pre-call fence covered and advances WAL + // through its tuple locks. Background flush progress does not affect this assertion. + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT pg_current_wal_insert_lsn() > ?::pg_lsn " + + "AND pg_current_wal_flush_lsn() >= ?::pg_lsn AS pre_call_fence_covered", + beforeLocks, + beforeLocks)) + .get("pre_call_fence_covered", Boolean.class)) + .isTrue(); + return null; + }); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + } + + @Test + void staleSerializableConfirmationInsertRetriesInsteadOfLeakingUniqueViolation() + throws Exception { + var context = context(null); + var original = pending(context, account(context)); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID decision = UUID.randomUUID(); + tx(context, () -> repository.recordCommitted(original, decision)); + var unchanged = storageSnapshot(context); + var snapshotReady = new CountDownLatch(1); + var winnerCommitted = new CountDownLatch(1); + try (var executor = Executors.newSingleThreadExecutor()) { + var stale = + executor.submit( + () -> + tx( + context, + () -> { + assertThat( + context + .dsl() + .fetchCount( + DSL.table( + "account_gameplay_admission_commit_confirmations"))) + .isZero(); + snapshotReady.countDown(); + try { + if (!winnerCommitted.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("winner commit timeout"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return confirm(context, original, decision); + })); + Record retained; + try { + assertThat(snapshotReady.await(10, TimeUnit.SECONDS)).isTrue(); + retained = tx(context, () -> confirm(context, original, decision)); + } finally { + winnerCommitted.countDown(); + } + assertThatThrownBy(() -> stale.get(30, TimeUnit.SECONDS)) + .satisfies( + failure -> { + Throwable cause = failure; + while (cause != null && !(cause instanceof java.sql.SQLException)) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(java.sql.SQLException.class); + assertThat(((java.sql.SQLException) cause).getSQLState()).isEqualTo("40001"); + }); + assertThat(tx(context, () -> confirm(context, original, decision))).isEqualTo(retained); + assertThat(tx(context, () -> readConfirmation(context, original, decision))) + .isEqualTo(retained); + } + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isEqualTo(1); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + } + @Test void updateBeforeExpiryButPhysicalCommitAfterExpiryCannotCreateConfirmation() { var context = context(null); @@ -1038,6 +1158,15 @@ void concurrentConfirmationsRetainOneOriginalReceiptWithoutAdvancingSources() th context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) .isEqualTo(1); var retained = tx(context, () -> confirm(context, original, decision)); + waitPastDeadline(context, original); + // Both duplicates now replay an expired retained receipt. They must never enter the fresh + // INSERT guard, restamp its temporal bound or allocate replacement evidence. + try (var executor = Executors.newFixedThreadPool(2)) { + var left = executor.submit(duplicate); + var right = executor.submit(duplicate); + assertThat(left.get(30, TimeUnit.SECONDS)).isEqualTo(retained); + assertThat(right.get(30, TimeUnit.SECONDS)).isEqualTo(retained); + } assertThat(tx(context, () -> readConfirmation(context, original, decision))) .isEqualTo(retained); assertThat(storageSnapshot(context)).isEqualTo(unchanged); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java index f9add38597..20b32aca03 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java @@ -3,8 +3,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -28,6 +28,11 @@ class AccountGameplayAdmissionCommitConfirmationRepositoryTest { "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)"; private static final String READ_SQL = "SELECT * FROM account_gameplay_admission_read_commit_confirmation(?, ?, ?)"; + private static final String ACCOUNT_LOCK_SQL = + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE"; + private static final String OPERATION_SELECT_SQL = + "SELECT * FROM account_gameplay_admission_lease_operations WHERE request_id = ? FOR UPDATE"; + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); @AfterEach void clearTransaction() { @@ -70,6 +75,19 @@ void confirmAndReadCallOnlyTheirDatabaseFunctionWithOriginalRequestDigestAndDeci UUID.fromString((String) evidence.carrier().get("requestId")), evidence.sha256(), decision); + var confirmOrder = inOrder(confirmDsl); + confirmOrder + .verify(confirmDsl) + .fetchOne( + CONFIRM_SQL, + UUID.fromString((String) evidence.carrier().get("requestId")), + evidence.sha256(), + decision); + confirmOrder.verify(confirmDsl).fetchOne(ACCOUNT_LOCK_SQL, ACCOUNT_ID); + confirmOrder + .verify(confirmDsl) + .fetchOne( + OPERATION_SELECT_SQL, UUID.fromString((String) evidence.carrier().get("requestId"))); var readDsl = dsl(evidence, operation, proofRow(evidence, decision)); var readRepository = repository(readDsl); @@ -80,6 +98,19 @@ void confirmAndReadCallOnlyTheirDatabaseFunctionWithOriginalRequestDigestAndDeci UUID.fromString((String) evidence.carrier().get("requestId")), evidence.sha256(), decision); + var readOrder = inOrder(readDsl); + readOrder + .verify(readDsl) + .fetchOne( + READ_SQL, + UUID.fromString((String) evidence.carrier().get("requestId")), + evidence.sha256(), + decision); + readOrder.verify(readDsl).fetchOne(ACCOUNT_LOCK_SQL, ACCOUNT_ID); + readOrder + .verify(readDsl) + .fetchOne( + OPERATION_SELECT_SQL, UUID.fromString((String) evidence.carrier().get("requestId"))); verify(readDsl, never()).fetchOne(eq(CONFIRM_SQL), any(Object[].class)); } @@ -107,7 +138,7 @@ void requiresWritableSerializableAccountTransactionBeforeAnyStorageAccess() { } @Test - void pendingAbortedMissingAndDecisionMismatchNeverReachConfirmationFunctions() { + void pendingAbortedMissingAndDecisionMismatchFailClosedAfterProofLookup() { var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); UUID decision = UUID.randomUUID(); for (var operation : @@ -120,14 +151,14 @@ void pendingAbortedMissingAndDecisionMismatchNeverReachConfirmationFunctions() { DSLContext dsl = dsl(evidence, operation, proofRow(evidence, decision)); assertThatThrownBy(() -> repository(dsl).confirmCommitted(evidence, decision)) .isInstanceOf(IllegalStateException.class); - verify(dsl, never()).fetchOne(eq(CONFIRM_SQL), any(Object[].class)); + verify(dsl).fetchOne(eq(CONFIRM_SQL), any(Object[].class)); verify(dsl, never()).fetchOne(eq(READ_SQL), any(Object[].class)); } DSLContext missingDsl = dsl(evidence, null, proofRow(evidence, decision)); assertThatThrownBy(() -> repository(missingDsl).readCommitConfirmation(evidence, decision)) .isInstanceOf(IllegalStateException.class); - verify(missingDsl, never()).fetchOne(eq(READ_SQL), any(Object[].class)); + verify(missingDsl).fetchOne(eq(READ_SQL), any(Object[].class)); } @Test @@ -161,6 +192,8 @@ void missingOrContradictoryDatabaseProofFailsClosed() { DSLContext missing = dsl(evidence, operation, null); assertThatThrownBy(() -> repository(missing).readCommitConfirmation(evidence, decision)) .isInstanceOf(IllegalStateException.class); + verify(missing).fetchOne(eq(READ_SQL), any(Object[].class)); + verify(missing, never()).fetchOne(eq(ACCOUNT_LOCK_SQL), any(Object[].class)); } private static AccountGameplayAdmissionCommitConfirmationRepository repository(DSLContext dsl) { @@ -176,7 +209,10 @@ private static DSLContext dsl( DSLContext dsl = mock(DSLContext.class); Record account = mock(Record.class); Record operationRow = operation == null ? null : operationRow(evidence, operation); - when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, operationRow, proof); + when(dsl.fetchOne(eq(CONFIRM_SQL), any(Object[].class))).thenReturn(proof); + when(dsl.fetchOne(eq(READ_SQL), any(Object[].class))).thenReturn(proof); + when(dsl.fetchOne(eq(ACCOUNT_LOCK_SQL), any(Object[].class))).thenReturn(account); + when(dsl.fetchOne(eq(OPERATION_SELECT_SQL), any(Object[].class))).thenReturn(operationRow); return dsl; } From 1baaaaa355fe54e7bcd4bbd6ee6d954de776acf1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:59:07 +1300 Subject: [PATCH 15/16] Capture Account durable confirmation from fixed snapshot before heap reads --- ...uthority-and-gameplay-session-ownership.md | 4 +- ...30-risk-based-active-session-revocation.md | 42 ++---- .../account-service/api-contracts.md | 2 +- .../architecture/system-architecture-redis.md | 8 +- .../system-architecture-session-behavior.md | 30 ++-- design/project-management/ai-observations.md | 6 + .../player-access-and-session.md | 6 +- ..._admission_durable_commit_confirmation.sql | 126 ++++++++++------ ...issionLeasePersistenceIntegrationTest.java | 136 +++++++++++++----- ...anonicalFirstJoinEventIntegrationTest.java | 1 - 10 files changed, 230 insertions(+), 131 deletions(-) diff --git a/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md b/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md index 25897359ed..974d753cc3 100644 --- a/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md +++ b/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md @@ -52,13 +52,13 @@ Later clarification: [ADR 0132](./adr-0132-namespace-scoped-single-character-con Game Session consumes authoritative Account membership, entitlement, and revocation state. It stores only the token identity and freshness metadata needed to validate a binding, such as token hash, issued-at time, and `membershipVersion`; it must not make a persisted raw backend JWT the durable session authority. -For issuer-generation consumption only, Game Session may maintain one derived consumer-local projection under its own namespace: `session:game:auth:issuer-generation:v1:`. Its schema is `game-session-auth-issuer-projection/v1` with `{schemaVersion, issuerId, issuerAuthGeneration, lastAppliedSourceOutboxSequence, sourceOutboxStreamKey, sourceEventId, sourceEventDigest, appliedAt}` plus bounded per-sequence applied-source evidence, or an explicit immutable Account source-checkpoint lookup. Account's issuer `outboxStreamKey` is immutable for the life of that issuer authority and must not be regenerated by deployment, failover, Redis reset, or projection repair. If authoritative recovery ever changes the stream key or resets its sequence/epoch, Account must first install and expose an authoritative checkpoint for the new exact stream identity/epoch; consumers quarantine the scope and accept no changed- or reset-stream event until that checkpoint is validated. The checkpoint, not an inferred event baseline, is the only value that may establish the new local watermark or permit sequence advancement. The canonical issuer projection watermark is `lastAppliedSourceOutboxSequence`. For each exact `sourceOutboxStreamKey`, an incoming event is applicable only when its source sequence is exactly `lastAppliedSourceOutboxSequence + 1`; a higher sequence is a gap that must be quarantined and reconciled from Account before either the watermark or generation advances. An event at or below the watermark is an idempotent no-op only when retained evidence or an exact Account checkpoint lookup proves the complete required authority evidence: the same `authorityTuple`, positive `issuanceFence`, complete `outboxCheckpoints` set, event ID, sequence, recomputed event digest, exact stream key, and `issuerAuthGeneration`. A sequence/event/digest/stream/generation match without the complete tuple, fence, and checkpoint set is not duplicate proof. Missing, partial, generation-only, stale, regressed, conflicting, or ambiguous evidence, including an older event outside the bounded local evidence window that cannot be resolved by the exact Account lookup, quarantines the scope and is reconciled rather than treated as a no-op. A next-sequence event must pass the same complete evidence comparison before the watermark or generation advances; a lower `issuerAuthGeneration` is contradictory Account evidence, while an equal generation is idempotent and a higher generation uses set-if-greater semantics. This local projection is a revocation-consumer cache, not an authority source, and Game Session must never write or mutate any canonical `session:auth:generation:*` key. Account's durable issuer generation and its canonical projection remain the only authority; Game Session owns only this derived consumer-local projection. +For issuer-generation consumption only, Game Session may maintain one derived consumer-local projection under its own namespace: `session:game:auth:issuer-generation:v1:`. Its local projection schema remains `game-session-auth-issuer-projection/v1` with `{schemaVersion, issuerId, issuerAuthGeneration, lastAppliedSourceOutboxSequence, sourceOutboxStreamKey, sourceEventId, sourceEventDigest, appliedAt}` plus bounded per-sequence applied-source evidence, or an explicit immutable Account source-checkpoint lookup. Issuer events and source snapshots use the closed issuer-specific schema owned by [ADR 0030](./adr-0030-risk-based-active-session-revocation.md): they bind the exact issuer scope, committed `issuerAuthGeneration` and source version, and exact stream checkpoint, with event identity and digest for positive sequences. They contain no recipient `authorityTuple`, `issuanceFence`, or full `outboxCheckpoints` set. Every reconciliation snapshot, including sequence zero, binds its source transaction or immutable source version to the exact reconciliation operation identity as specified by ADR 0030. Account's issuer `outboxStreamKey` is immutable for the life of that issuer authority and must not be regenerated by deployment, failover, Redis reset, or projection repair. If authoritative recovery ever changes the stream key or resets its sequence/epoch, Account must first install and expose an authoritative checkpoint for the new exact stream identity/epoch; consumers quarantine the scope and accept no changed- or reset-stream event until that checkpoint is validated. The checkpoint, not an inferred event baseline, is the only value that may establish the new local watermark or permit sequence advancement. The canonical issuer projection watermark is `lastAppliedSourceOutboxSequence`. For each exact `sourceOutboxStreamKey`, an incoming event is applicable only when its source sequence is exactly `lastAppliedSourceOutboxSequence + 1`; a higher sequence is a gap that must be quarantined and reconciled from Account before either the watermark or generation advances. An event at or below the watermark is an idempotent no-op only when retained evidence or an exact Account source-checkpoint lookup proves the complete issuer event schema and source evidence, including exact scope, committed generation/source version, stream checkpoint, and positive-sequence event identity/digest. A generation-only match or an event ID/digest/stream/generation match without the complete issuer source evidence is not duplicate proof. Missing, partial, stale, regressed, conflicting, or ambiguous evidence, including an older event outside the bounded local evidence window that cannot be resolved by the exact Account lookup, quarantines the scope and is reconciled rather than treated as a no-op. A next-sequence event must pass the same complete issuer-evidence comparison before the watermark or generation advances; a lower `issuerAuthGeneration` is contradictory Account evidence, while an equal generation is idempotent and a higher generation uses set-if-greater semantics. This local projection is a revocation-consumer cache, not an authority source, and Game Session must never write or mutate any canonical `session:auth:generation:*` key. Account's durable issuer generation and its canonical projection remain the only authority; Game Session owns only this derived consumer-local projection. ### Canonical Checkpoint And Source-Evidence Binding [ADR 0030](./adr-0030-risk-based-active-session-revocation.md) owns the unchanged `outboxCheckpoints` entry schema: exactly `{outboxStreamKey, outboxSequence}`, with one entry for every applicable authority stream. `compareOutboxCheckpointEntries(a, b)` compares the unsigned UTF-8 bytes of `outboxStreamKey` lexicographically and places the shorter key first when one is a prefix. Duplicate stream keys, locale collation, Unicode normalization, case folding, alternate escaping, or another ordering are invalid. -Event identity and digest remain separate same-snapshot source evidence rather than members of `outboxCheckpoints`. For each checkpoint, retained applied-source evidence or an exact Account lookup binds `{outboxStreamKey, outboxSequence, eventId, eventDigest, authorityTuple, issuanceFence, outboxCheckpoints}` from one Account linearization point. Delivery, refresh, rebind, binding CAS, acknowledgement, retries, and duplicate detection carry or resolve that complete binding without adding fields to the checkpoint carrier. A latest entry, aggregate maximum, projection-only value, partial source-evidence match, or evidence assembled from separate snapshots is invalid and quarantines the affected scope. +Event identity and digest remain separate source evidence rather than members of `outboxCheckpoints`. For issuer projection events, retained evidence or an exact Account source lookup binds the complete closed issuer schema and source version to its exact issuer stream checkpoint; it does not add recipient tuple, fence, or checkpoint-set fields. Recipient admission, refresh, rebind, binding CAS, and their acknowledgements/retries still carry or resolve the applicable full same-snapshot `authorityTuple`, actual `issuanceFence`, and complete `outboxCheckpoints` set. For event consumption, Account authenticates those recipient carriers as separate same-snapshot source evidence bound to the exact consumed event ID/digest and `membershipBaseline` where applicable; they do not extend the closed event schema or its digest input. In either contract, a checkpoint entry remains exactly `{outboxStreamKey, outboxSequence}`. A latest entry, aggregate maximum, projection-only value, partial source-evidence match, or evidence assembled from separate snapshots is invalid and quarantines the affected scope. [ADR 0030](./adr-0030-risk-based-active-session-revocation.md) owns the closed issuer source schema and recipient evidence contract. ### Operation Partition diff --git a/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md b/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md index 22ed63b094..7ffdfa5a49 100644 --- a/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md +++ b/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md @@ -28,7 +28,7 @@ The previous target distinguished soft and hard billing states and required even ### Canonical Authority Tuple Boundary -[ADR 0035](./adr-0035-single-record-issued-token-registry.md) owns the single normative `authorityTuple` schema and exact field names. This ADR does not redefine that schema. It applies the tuple unchanged to revocation events, Account leases, gameplay bindings, and active-session cutoff decisions; `issuanceFence` remains the Account composite authority fence copied alongside the tuple, never a substitute for a tuple member. Account carries the same fence through applicable canonical outbox and logout/revocation evidence so consumers cannot accept authority evidence assembled across different Account linearization points. +[ADR 0035](./adr-0035-single-record-issued-token-registry.md) owns the single normative `authorityTuple` schema and exact field names. This ADR does not redefine that schema. It applies the tuple unchanged to recipient admission, Account leases, gameplay bindings, and active-session cutoff decisions; `issuanceFence` remains the Account composite authority fence copied alongside the tuple, never a substitute for a tuple member. For recipient event consumption, Account authenticates the applicable same-snapshot tuple and fence as separate source evidence bound to the exact consumed event identity and digest; these carriers do not extend the closed event schema or its digest input. Consumers cannot accept authority evidence assembled across different Account linearization points. Revocation-local admission decisions, exact-binding leases, and gameplay bindings also carry the complete canonical `outboxCheckpoints` set: one exact `{outboxStreamKey, outboxSequence}` entry for every applicable scoped outbox stream. This set is admission freshness evidence, not a member of `authorityTuple` or a general JWT/registry claim, and any stream coordinates embedded in cutoff evidence must equal their corresponding set entries. @@ -64,36 +64,20 @@ For every admission or replacement operation, `membershipBaseline` is one immuta ### Delivery And Bounded Enforcement -- Account is the sole authority writer. One Account database transaction, or one composite Account CAS/fence that atomically covers every applicable member of `authorityTuple`, commits the authority change, applicable account-security or tenant-billing cutoff evidence, applicable private-realm grant version, the applicable `issuanceFence`, and the outbox row. Independent row updates are not an acceptable substitute. Redis and other downstream projections are derived outputs. A cutoff workflow does not report enforcement complete until the required projection and consumer convergence succeeds. [ADR 0036](./adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md) supersedes timestamp watermark ordering for bulk token-revocation decisions. +- Account is the sole authority writer. One Account database transaction, or one composite Account CAS/fence, commits each authority mutation and its applicable closed source event/checkpoint. Recipient `authorityTuple`, actual `issuanceFence`, and full `outboxCheckpoints` evidence is captured from that same Account state in a separate Account-authenticated source-evidence carrier bound to the exact consumed event identity and digest; it is not added to the closed event schema or digest input. Independent row updates are not an acceptable substitute. Issuer-generation source events use the separate closed issuer schema below and do not carry recipient tuple, fence, or checkpoint-set evidence. Redis and other downstream projections are derived outputs. A cutoff workflow does not report enforcement complete until the required projection and consumer convergence succeeds. [ADR 0036](./adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md) supersedes timestamp watermark ordering for bulk token-revocation decisions. - The durable revocation outbox stream key is exactly `account:auth-authority:v1:`. The exact `scopeId` is `issuer/`, `account/`, `tenant/`, `membership//`, or the lifecycle-bound private/playtest grant scope produced by the [canonical grant authority-stream scope codec](../system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). Account allocates `outboxSequence` contiguously starting at `1` independently for each exact stream key, in the same transaction/CAS as the authority mutation. `tenantBillingSequence` remains the separate Account billing sequence for the exact tenant and is copied into `tenantBillingCutoff` when applicable. -- `tenantBillingSequence` has one canonical billing-cutoff stream mapping: for tenant ``, every billing cutoff advances the Account-owned sequence and is emitted on `account:auth-authority:v1:tenant/`. The `tenantBillingCutoff[tenantId]` evidence carries that exact `tenantBillingSequence`, `outboxStreamKey`, and `outboxSequence`; no second billing stream or tenant-local sequence source exists. Billing consumption maintains two independent ledgers: a source-delivery ledger keyed by each exact `outboxStreamKey`, with its own `lastAppliedOutboxSequence` and bounded retained duplicate evidence `{outboxStreamKey, outboxSequence, eventId, eventDigest, authorityTuple, issuanceFence, membershipBaseline, outboxCheckpoints}` when membership applies, and a separate `lastAppliedTenantBillingSequence` for each tenant. The source ledger advances for every event on that stream, including non-billing events; the tenant billing ledger advances only for billing-cutoff events. `tenantBillingSequence` is never used as the source watermark or duplicate identity, and an outbox watermark is never used as billing-sequence evidence. Each delivered event must be contiguous at `lastAppliedOutboxSequence + 1` for its exact stream; a billing-cutoff event must additionally satisfy the exact tenant/stream mapping and `tenantBillingSequence == lastAppliedTenantBillingSequence + 1`, while a non-billing event must not advance or regress the billing sequence. Matching duplicates are no-ops only when the complete retained same-snapshot evidence matches the canonical schema or an exact Account lookup proves that evidence; a same-key gap, conflicting duplicate, missing evidence, billing-sequence regression, or mismatch stops the affected scope, reconciles from Account, and advances either independent ledger only after the corresponding Account checkpoint proves coverage. A first event never initializes either ledger from delivered data: it first installs the exact Account snapshot, source watermark/evidence, and separate billing watermark under the bootstrap rule below, and only the next source sequence (`installed watermark + 1`) can be accepted. +- `tenantBillingSequence` has one canonical billing-cutoff stream mapping: for tenant ``, every billing cutoff advances the Account-owned sequence and is emitted on `account:auth-authority:v1:tenant/`. The `tenantBillingCutoff[tenantId]` evidence carries that exact `tenantBillingSequence`, `outboxStreamKey`, and `outboxSequence`; no second billing stream or tenant-local sequence source exists. Billing consumption maintains two independent ledgers: a source-delivery ledger keyed by each exact `outboxStreamKey`, with its own `lastAppliedOutboxSequence` and bounded retained duplicate evidence for the complete event-type schema and source proof, and a separate `lastAppliedTenantBillingSequence` for each tenant. Recipient events are compared with their separate Account-authenticated same-snapshot source evidence; issuer streams use only the closed issuer schema and source-version evidence below. The source ledger advances for every event on that stream, including non-billing events; the tenant billing ledger advances only for billing-cutoff events. `tenantBillingSequence` is never used as the source watermark or duplicate identity, and an outbox watermark is never used as billing-sequence evidence. Each delivered event must be contiguous at `lastAppliedOutboxSequence + 1` for its exact stream; a billing-cutoff event must additionally satisfy the exact tenant/stream mapping and `tenantBillingSequence == lastAppliedTenantBillingSequence + 1`, while a non-billing event must not advance or regress the billing sequence. Matching duplicates are no-ops only when the complete retained same-snapshot evidence matches the event-type schema or an exact source lookup proves that evidence; a same-key gap, conflicting duplicate, missing evidence, billing-sequence regression, or mismatch stops the affected scope, reconciles from Account, and advances either independent ledger only after the corresponding source checkpoint proves coverage. A first event never initializes either ledger from delivered data: it first installs the exact source snapshot, watermark/evidence, and separate billing watermark under the bootstrap rule below, and only the next source sequence (`installed watermark + 1`) can be accepted. - Every authority change that can affect a new gameplay binding advances its applicable tuple member and the scoped outbox sequence in the same Account transaction/CAS. The Account-owned admission decision exposes the exact tuple and the complete `outboxCheckpoints` set it covers. Game Session may create a binding only after every checkpoint entry has its exact stream watermark at or beyond `outboxSequence` and every corresponding authority/index projection confirms coverage of that entry. A missing, stale, gapped, ambiguous, or otherwise unconfirmed checkpoint or projection fails closed before binding creation. -- An issuer-generation cutoff is also an active-session revocation authority, not only a token-validation rule. Account advances the issuer generation and emits the committed outbox event with the issuer scope, new generation, `issuanceFence`, and cutoff checkpoint. Game Session owns only the derived consumer-local projection `session:game:auth:issuer-generation:v1:` and applies that event with set-if-greater semantics; it never writes or mutates Account's canonical `session:auth:generation:*` projection. Duplicate or older events are no-ops only when the exact source evidence rule below is satisfied; a generation-only match is insufficient. A gap or unavailable, stale, regressed, or ambiguous projection triggers authoritative reconciliation and fail-closed admission. Every active gameplay binding persists the issuer generation captured at admission, and the issuer cutoff is applied to all affected bindings across tenants. +- An issuer-generation cutoff is also an active-session revocation authority, not only a token-validation rule. Account commits the issuer generation, exact issuer-scope checkpoint, and closed versioned issuer event from the same source transaction or immutable issuer source version. That event binds the exact `issuer/` scope, committed `issuerAuthGeneration`, source version, `outboxStreamKey`, and `outboxSequence`; a positive sequence has its exact `eventId` and `eventDigest` computed over the complete issuer event schema under the canonical digest rule below, while sequence zero is only a source checkpoint and has no event identity or digest. The issuer event and source snapshot contain no recipient `authorityTuple`, `issuanceFence`, or full `outboxCheckpoints` set. Every reconciliation snapshot, including a sequence-zero snapshot, binds its source transaction or immutable source version to the exact reconciliation operation identity. Account-issued recipient admission and rebind still require their own complete same-snapshot `authorityTuple`, actual `issuanceFence`, and full `outboxCheckpoints` set; they are not inferred from issuer projection evidence. Game Session owns only the derived consumer-local projection `session:game:auth:issuer-generation:v1:` and applies the issuer generation with set-if-greater semantics; it never writes or mutates Account's canonical `session:auth:generation:*` projection. Duplicate or older events are no-ops only when the exact issuer event/source evidence rule below is satisfied; a generation-only match is insufficient. A gap or unavailable, stale, regressed, or ambiguous projection triggers authoritative reconciliation and fail-closed admission. Every active gameplay binding persists the issuer generation captured at admission, and the issuer cutoff is applied to all affected bindings across tenants. - Every new gameplay binding and every reconnect/resume admission must also use an Account-owned exact-binding admission lease. The lease contains the target `{accountId, tenantId}` binding identity, exact `authorityTuple`, unchanged `membershipBaseline`, `issuanceFence`, complete `outboxCheckpoints` set, a monotonic `leaseFence`, and a short expiry; grace resume uses the existing `resumeActivationLease` as this contract's exact-resume specialization. Game Session's binding CAS must include the expected old binding generation, exact lease identity, `leaseFence`, `issuanceFence`, and the same tuple, unchanged baseline, and checkpoint set and may publish only a non-admissible provisional record until Account durably finalizes the same lease as `COMMITTED`. Account authority advancement, membership-baseline changes, and lease finalization serialize through the same composite Account CAS across every applicable tuple and baseline member: if any issuer, account, tenant, membership, grant, billing, security, lifecycle, membership-version, or membership-generation value advances before finalization, the fence changes, finalization fails, and any provisional local binding is removed or remains blocked. A stale, missing, expired, ambiguous, or unfenced lease never becomes an admissible binding. This lease/fence predicate is the conditional authority checked by the Game Session binding CAS; it is an ordered idempotent protocol across stores, not a claimed cross-store transaction. - Game Session remains the owner of gameplay binding records, the binding CAS, all bounded active-binding indexes, and socket/admission termination. Account finalization commits only the Account-owned lease, decision, authority snapshot, complete `outboxCheckpoints` set, and idempotency evidence; it does not create, delete, or mutate a Game Session binding or index. If Account reconciliation finds a committed or abandoned lease with no matching admissible Game Session binding, Account emits durable orphan evidence and a fenced cleanup request keyed to the exact request, lease, binding, and fence. Gateway performs any matching edge-token deny/clear cleanup, and Game Session validates the cleanup fence before removing or quarantining the binding and its indexes. Account may reconcile the decision evidence and record cleanup acknowledgements, but local Account cleanup is not physical gameplay cleanup or proof of completion. -- Game Session consumes revocation events durably and idempotently. The canonical Account outbox payload is: - - ```text - { - schemaVersion, - eventId, - eventType, - outboxStreamKey, - outboxSequence, - sourceScope, - authorityTuple, - issuanceFence, - outboxCheckpoints, - eventDigest, - occurredAt - } - ``` - - `sourceScope` must decode to the scope encoded by `outboxStreamKey`; a mismatch is malformed evidence. `outboxCheckpoints` must be the complete canonical stream-key-ordered set, with exactly one `{outboxStreamKey, outboxSequence}` entry for every applicable authority stream, and the entry for `outboxStreamKey` must equal the event's `outboxSequence`; missing, extra, reordered-with-different-content, stale, regressed, or cross-scope entries are invalid. `eventDigest` is `sha256:` followed by 64 lowercase hexadecimal characters for SHA-256 over the UTF-8 bytes of the RFC 8785 JSON Canonicalization Scheme serialization of the complete canonical event object, excluding only the `eventDigest` field itself. The input includes every field in the payload above and every field declared by the exact `eventType` schema; it excludes transport headers, delivery metadata, and any undeclared or duplicate field. Account computes it from the authoritative snapshot before publishing, and the consumer recomputes it from the received object and compares the exact digest before applying or acknowledging the event. Canonical optional objects are omitted only when inapplicable; required maps/lists use their declared empty `{}`/`[]` forms, and `null`, empty-string, sentinel, alternate numeric, and alternate serialization forms are invalid. For a membership-scoped event, the event-type `membershipVersion` field is the complete exact one-tenant map defined above and must equal the map from the same Account snapshot. - - A consumer stores one `lastAppliedSourceOutboxSequence` and a bounded per-sequence retained duplicate-evidence window using `{outboxStreamKey, outboxSequence, eventId, eventDigest, authorityTuple, issuanceFence, membershipBaseline, outboxCheckpoints}` when membership applies, never one global watermark. If `outboxSequence <= lastAppliedSourceOutboxSequence`, an older or duplicate event is a no-op only when retained evidence contains exact equality for the complete canonical schema, or an authoritative Account checkpoint returns that exact committed event evidence including the same digest; an evicted local entry, a generation-only match, or an event ID/digest pair alone is not proof. The same sequence with different evidence or digest is a reachable stream conflict, so the scope is quarantined and reconciled fail-closed. If the retained evidence has been evicted and the Account checkpoint is unavailable or timed out, the affected scope remains quarantined and the operation returns retryable `AUTH_UNAVAILABLE`. If `outboxSequence == lastAppliedSourceOutboxSequence + 1`, the consumer validates the recomputed `eventDigest`, full `authorityTuple`, `issuanceFence`, unchanged `membershipBaseline` where applicable, and complete `outboxCheckpoints` set against matching Account evidence, including that no applicable stream is missing or extra. An equal authority value is an idempotent accepted checkpoint and a higher value applies through set-if-greater before the watermark advances; a lower value is contradictory evidence that quarantines the scope and requires Account reconciliation before either value advances. If `outboxSequence > lastAppliedSourceOutboxSequence + 1`, it is a gap only for that same `outboxStreamKey`: the consumer stops admitting or reconnecting affected bindings, reconciles the exact scope from Account, and advances the watermark only after the Account checkpoint proves the missing range is covered. - - An uninitialized stream must bootstrap before processing any delivered event. The consumer obtains one Account snapshot at a single Account linearization point containing the exact `outboxStreamKey`, the Account-owned `lastCommittedOutboxSequence` for that stream (including the sequence-0 baseline), the complete applicable `authorityTuple`, `issuanceFence`, and `outboxCheckpoints`. Only a stream with an explicit unique tenant identity, including `tenant/`, `membership//`, or the codec-derived lifecycle-bound non-public grant scope for an ordinary-private or playtest grant, also carries the applicable Account-owned `lastCommittedTenantBillingSequence` for that tenant, including its sequence-0 baseline; issuer and account streams do not carry or infer a tenant billing watermark. For each positive source or applicable billing watermark, that same snapshot carries its exact source/event evidence: the source stream key and sequence, committed event ID, and `eventDigest`; for a positive tenant billing watermark it additionally carries the exact committed billing event's `tenantBillingSequence`. Sequence-zero watermarks omit their source-event fields rather than serializing `null`, an empty string, or a sentinel. For a membership-scoped stream, that same snapshot must additionally carry the unchanged `membershipBaseline`, complete same-snapshot membership state (`membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, and applicable `roles`), and both independent membership projection high-waters: the `membershipAuthorityGeneration` projection high-water and the `membershipVersion` projection high-water, each with its exact stream checkpoint and source evidence. Neither projection high-water may be inferred from the other or from the aggregate outbox watermark. The consumer installs the exact per-stream source watermark and bounded retained duplicate evidence separately from any applicable committed tenant billing watermark, along with the authority, issuance fence, checkpoint set, baseline, both membership projection high-waters, and same-snapshot membership state atomically before inspecting the delivered event. A new delivered event is then accepted only when its `outboxSequence` is exactly the installed source watermark for that same `outboxStreamKey` plus one; a billing-cutoff event is accepted only on the exact canonical stream `account:auth-authority:v1:tenant/` and its `tenantBillingSequence` must also be exactly the installed `lastCommittedTenantBillingSequence + 1`, while a non-billing event must not advance or regress that billing watermark. Membership and grant snapshots may carry the applicable billing watermark as same-snapshot evidence, but their streams never emit, advance, or validate a billing-cutoff sequence. A lower or equal source sequence requires the bounded retained duplicate-evidence rule or an exact Account event lookup, and a higher sequence is a gap. The consumer must never initialize either ledger, authority, membership state, or evidence from an arbitrary delivered event. An event for an unrelated scope uses another stream key and another watermark and must not create a gap in this scope. Event delivery, projection application, and consumer convergence are part of the cutoff proof. +- Game Session consumes revocation events durably and idempotently. Every `eventType` has a closed versioned schema: issuer-generation, account, tenant, membership, and grant events carry only their declared scope-specific fields. Consumers validate only the complete applicable closed event schema; recipient authority evidence is a separate Account-authenticated same-snapshot source-evidence carrier bound to the exact consumed `eventId` and `eventDigest`, never an extension to the event payload. An event alone is insufficient for recipient admission or rebind. Issuer-generation events use the separate closed issuer schema described above. + + `sourceScope` must decode to the scope encoded by `outboxStreamKey`; a mismatch is malformed evidence. `eventDigest` is `sha256:` followed by 64 lowercase hexadecimal characters for SHA-256 over the UTF-8 bytes of the RFC 8785 JSON Canonicalization Scheme serialization of the complete canonical event object declared by that exact `eventType`, excluding only the `eventDigest` field itself. The digest input includes every required field of that closed event schema and excludes transport headers, delivery metadata, undeclared or duplicate fields, and separate recipient source evidence. Canonical optional objects are omitted only when inapplicable; required maps/lists use their declared empty `{}`/`[]` forms, and `null`, empty-string, sentinel, alternate numeric, and alternate serialization forms are invalid. Account computes the digest from the authoritative snapshot before publishing, and the consumer recomputes it from the received event object and compares the exact digest before applying or acknowledging the event. For a membership-scoped event, the event-type `membershipVersion` field is the complete exact one-tenant map defined above and must equal the map from the same Account snapshot. Recipient evidence separately supplies the applicable full `authorityTuple`, actual `issuanceFence`, unchanged `membershipBaseline` where applicable, and complete canonical stream-key-ordered `outboxCheckpoints` set from that same Account snapshot, bound to the exact event identity and digest. The set has exactly one entry for each applicable authority stream, and the entry matching the consumed event's `outboxStreamKey` must have `outboxSequence` equal to that event's `outboxSequence`; a missing, extra, stale, regressed, cross-scope, mismatched, or separately assembled recipient carrier is invalid. Canonical presence and ordering rules remain those owned by the applicable schemas. + + A consumer stores one `lastAppliedSourceOutboxSequence` per exact `outboxStreamKey` and a bounded per-sequence window of complete event-type duplicate evidence, never one global watermark. Recipient events are compared with their separate Account-authenticated same-snapshot source evidence, including the applicable `authorityTuple`, actual `issuanceFence`, unchanged `membershipBaseline` where applicable, and complete `outboxCheckpoints` set bound to the exact event identity and digest. Issuer evidence instead compares the complete closed issuer event schema, exact issuer scope, committed `issuerAuthGeneration` and immutable source version, and exact stream checkpoint; positive sequences also require the exact `eventId` and `eventDigest`. If `outboxSequence <= lastAppliedSourceOutboxSequence`, an older or duplicate event is a no-op only when retained event and source evidence exactly match, or an authoritative lookup for the exact source stream and sequence proves the same committed event and bound source evidence including its digest; an evicted local entry, generation-only match, or event ID/digest pair alone is not proof. The same sequence with different evidence or digest is a reachable stream conflict, so the scope is quarantined and reconciled fail-closed. If retained evidence has been evicted and the exact Account source lookup is unavailable or timed out, the affected scope remains quarantined and the operation returns retryable `AUTH_UNAVAILABLE`. If `outboxSequence == lastAppliedSourceOutboxSequence + 1`, the consumer validates the recomputed `eventDigest` over the closed event schema and the corresponding source evidence against the matching Account snapshot: issuer events use the issuer schema and source-version proof, while recipient events also require the full `authorityTuple`, actual `issuanceFence`, unchanged `membershipBaseline` where applicable, and complete `outboxCheckpoints` set, including that no applicable stream is missing or extra. An equal authority value is an idempotent accepted checkpoint and a higher value applies through set-if-greater before the watermark advances; a lower value is contradictory evidence that quarantines the scope and requires source reconciliation before either value advances. If `outboxSequence > lastAppliedSourceOutboxSequence + 1`, it is a gap only for that same `outboxStreamKey`: the consumer stops admitting or reconnecting affected bindings, reconciles the exact scope from Account, and advances the watermark only after the exact source checkpoint proves the missing range is covered. + + An uninitialized stream must bootstrap before processing any delivered event. An issuer-generation projection obtains one Account issuer-source snapshot at one source linearization point containing the exact `issuer/` scope, `outboxStreamKey`, Account-owned `lastCommittedOutboxSequence` for that stream (including its sequence-0 baseline), committed `issuerAuthGeneration`, and immutable source version. Every reconciliation snapshot, including sequence zero, binds the source transaction or immutable source version to the exact reconciliation operation identity. For a positive sequence, the snapshot carries the exact committed event ID and digest; sequence zero has no event identity or digest. This issuer snapshot contains no recipient `authorityTuple`, `issuanceFence`, or full `outboxCheckpoints` set. Recipient authority state separately obtains Account-authenticated same-snapshot source evidence containing the applicable full `authorityTuple`, actual `issuanceFence`, and complete `outboxCheckpoints` set, bound to the exact committed event identity and digest where a source event exists; the event alone is insufficient for recipient admission or rebind, and none of these recipient carriers is inferred from the issuer projection. The consumer installs that recipient evidence with the exact source watermark and event evidence before inspecting a delivered event. Only a stream with an explicit unique tenant identity, including `tenant/`, `membership//`, or the codec-derived lifecycle-bound non-public grant scope for an ordinary-private or playtest grant, also carries the applicable Account-owned `lastCommittedTenantBillingSequence` for that tenant, including its sequence-0 baseline; issuer and account streams do not carry or infer a tenant billing watermark. For each positive source or applicable billing watermark, the corresponding same-snapshot source evidence includes the exact stream key and sequence, committed event ID, and digest; issuer evidence also binds the committed generation/source version, and a positive tenant billing watermark additionally carries the exact committed billing event's `tenantBillingSequence`. Sequence-zero watermarks omit their source-event fields rather than serializing `null`, an empty string, or a sentinel. For a membership-scoped stream, its Account snapshot must additionally carry the unchanged `membershipBaseline`, complete same-snapshot membership state (`membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, and applicable `roles`), and both independent membership projection high-waters: the `membershipAuthorityGeneration` projection high-water and the `membershipVersion` projection high-water, each with its exact stream checkpoint and source evidence. Neither projection high-water may be inferred from the other or from the aggregate outbox watermark. The issuer projection atomically installs only the exact issuer source watermark, bounded issuer duplicate evidence, and mapped issuer generation; recipient authority state atomically installs the full tuple, actual fence, complete checkpoint set, baseline, applicable billing watermark, both membership projection high-waters, and same-snapshot membership state before inspecting a delivered event. A new delivered event is then accepted only when its `outboxSequence` is exactly the installed source watermark for that same `outboxStreamKey` plus one; a billing-cutoff event is accepted only on the exact canonical stream `account:auth-authority:v1:tenant/` and its `tenantBillingSequence` must also be exactly the installed `lastCommittedTenantBillingSequence + 1`, while a non-billing event must not advance or regress that billing watermark. Membership and grant snapshots may carry the applicable billing watermark as same-snapshot evidence, but their streams never emit, advance, or validate a billing-cutoff sequence. A lower or equal source sequence requires the bounded retained duplicate-evidence rule or an exact source event lookup, and a higher sequence is a gap. The consumer must never initialize either ledger, authority, membership state, or evidence from an arbitrary delivered event. An event for an unrelated scope uses another stream key and another watermark and must not create a gap in this scope. Event delivery, projection application, and consumer convergence are part of the cutoff proof. - An unavailable or timed-out Account reconciliation, outbox store, projection, lease or lease-commit operation, fence, binding or binding index, token-identity fence, non-entitlement authority evidence, or token issuance dependency returns retryable `AUTH_UNAVAILABLE` while the affected operation remains denied; an entitlement-only dependency failure outside the bounded ADR 0028 continuity exception returns `ENTITLEMENT_UNAVAILABLE`. Reachable missing, malformed, stale, regressed, or conflicting evidence is invalid/revoked evidence. No cached tuple or empty index is accepted. - Game Session maintains six physical active-binding index families: the tenant-scoped character uniqueness index, plus five cutoff/revocation families for issuer, account, tenant, caller-bound membership `{accountId, tenantId}`, and private-realm grant scope. The canonical family `session:game:index:account-tenant:{tenantGameplayTag}:` maps to active session IDs for the exact `{accountId, tenantId}` caller-bound membership index used by active revocation; the tenant tag and binding member must be validated against the exact tenant, so this is not the untagged `session:game:index:account:` account-wide family. The canonical issuer family is `session:game:index:issuer:{issuerIndexLayoutTag}::`, a bounded Redis hash whose `` field maps to `{schemaVersion: 1, issuerId, accountId, tenantId, gameInstanceId, sessionId, bindingGeneration, issuerAuthGeneration, issuerIndexLayoutVersion}`. `` is the versioned length-prefixed encoding of the complete `{tenantId, gameInstanceId, sessionId}` binding identity, avoiding delimiter or textual-normalization ambiguity. `partitionId` is the deterministic hash of that exact encoded identity modulo the positive partition count recorded by the immutable normative `issuerIndexLayoutVersion`; `{issuerIndexLayoutTag}` is derived opaquely from `(issuerIndexLayoutVersion, issuerId, partitionId)`. Reads, writes, removals, repair obligations, and acknowledgements must use the same pinned layout version, partition count, capacity, and tag. A membership cutoff sweeps exactly `session:game:index:account-tenant:{tenantGameplayTag}:` for the affected `{accountId, tenantId}` rather than scanning every binding for the tenant. Issuer and other scope cutoffs perform the corresponding bounded index sweep, partitioned as needed within the existing revocation budget, and terminate every binding whose captured authority generation or grant version is below the committed cutoff. Revocation must not rely on Redis wildcard scans. - Issuer-index writes and removals are single-key compare-and-sets against the complete expected binding reference, binding generation, issuer generation, and active `issuerIndexLayoutVersion` contract, including its partition count, capacity, and derived layout tag. An identical value is an idempotent success; a stale or conflicting value creates a repair conflict. A tenant-local binding CAS records `issuerIndexState=REPAIR_REQUIRED` and keeps the binding non-admissible until the deterministic issuer repair obligation is durably acknowledged and a follow-up CAS records `issuerIndexState=ACKNOWLEDGED`. Cutoff and recovery read exactly the finite partition range selected by the pinned active layout pointer version and validate every returned entry against that same version; they must not reread the pointer and mix layouts. If the pointer changes before acknowledgement, the operation fails closed or enters the explicit layout-transition workflow. Missing, unreadable, conflicting, stale-layout, or unresolved-repair partitions are unavailable or ambiguous coverage, never empty coverage. Recovery rebuilds partitions from the durable active-binding inventory with the same expected-value compare-and-set and clears the obligation only after all required partition acknowledgements are proven. @@ -140,12 +124,12 @@ Checking Account or Redis before every command gives a tighter revocation observ ## Implementation and Proof Obligations -- Implement monotonic `authorityTuple` issuer/account/tenant/membership fields, `privateRealmGrantVersions`, applicable `accountSecurityCutoff` and `tenantBillingCutoff`, and `issuanceFence` with transactional durable advances, durable outbox and logout/revocation evidence carrying the exact fence, and idempotent consumers. +- Implement monotonic Account authority changes, including the recipient `authorityTuple` issuer/account/tenant/membership fields, `privateRealmGrantVersions`, applicable `accountSecurityCutoff` and `tenantBillingCutoff`, and `issuanceFence` with transactional durable advances. Durable outbox event types use their closed schemas: issuer source events follow the issuer-specific schema above, while recipient authority changes commit separate Account-authenticated same-snapshot tuple, actual fence, and complete checkpoint evidence bound to the exact source event identity/digest. Logout/revocation evidence and consumers preserve their applicable exact schema and remain idempotent. - Define, validate, observe, and prove the event-delivery, gap-detection, scheduler-jitter, retry, datastore-timeout, clock-skew, and `B_termination` sub-budgets using the single canonical equation above; include partial-outage and deadline-exhaustion behavior without adding `B_termination_setup` or the capacity term a second time. - Expose the applicable Account-owned authority tuple and complete committed `outboxCheckpoints` set through the admission decision, track every corresponding projection's application of its checkpoint, and fail closed before creating any new gameplay binding while any checkpoint is stale, gapped, ambiguous, or unconfirmed. - Implement the Account-owned exact-binding admission lease and monotonic `leaseFence` for new binding and reconnect/resume admission, bind the applicable complete `authorityTuple`, unchanged `membershipBaseline`, `issuanceFence`, and complete `outboxCheckpoints` set into that lease, include the lease/fence, unchanged baseline, and checkpoint set in the atomic Game Session binding CAS, and keep the local record provisional until Account `COMMITTED` finalization. Prove cutoff-before-finalization rejects admission, finalization-before-cutoff admits only the then-current authority and is later revoked through the bounded event path, and any stale, ambiguous, expired, or uncertain lease state fails closed without leaving an admissible binding. - Implement Account-owned issuer, account, tenant, and membership authority-generation plus realm-grant-version projections with retry, set-if-greater, and cutoff-completion semantics. -- Prove canonical `eventDigest` recomputation over the complete event object, exact per-sequence duplicate-evidence retention and comparison keyed by `outboxStreamKey`, duplicate verification after local evidence eviction, first-event Account-snapshot bootstrap that atomically installs the per-stream `lastCommittedOutboxSequence` and bounded source evidence separately from any applicable Account-owned `lastCommittedTenantBillingSequence`, contiguous next-sequence enforcement for the source stream and independent billing sequence, and fail-closed reconciliation when retained or authoritative evidence is unavailable. For membership-scoped bootstrap, prove that the atomic install carries the unchanged `membershipBaseline`, same-snapshot membership state, and both independent membership projection high-waters with their matching checkpoint/source evidence; missing, divergent, or separately assembled values remain quarantined. +- Prove canonical `eventDigest` recomputation over each complete closed event-type schema, exact per-sequence duplicate-evidence retention and comparison keyed by `outboxStreamKey`, duplicate verification after local evidence eviction, and fail-closed reconciliation when retained or authoritative evidence is unavailable. Issuer projection bootstrap atomically installs the exact issuer source sequence and generation evidence, including positive-sequence event identity/digest and source-version evidence bound to the reconciliation operation; recipient Account snapshots separately install the applicable tuple, actual `issuanceFence`, and complete `outboxCheckpoints` set. Both keep the per-stream `lastCommittedOutboxSequence` and bounded source evidence separate from any applicable Account-owned `lastCommittedTenantBillingSequence`, enforce contiguous next sequence for the source stream and independent billing sequence, and fail closed when evidence is unavailable. For membership-scoped bootstrap, prove that the atomic recipient install carries the unchanged `membershipBaseline`, same-snapshot membership state, and both independent membership projection high-waters with their matching checkpoint/source evidence; missing, divergent, or separately assembled values remain quarantined. - Persist the authority versions required by active gameplay bindings and implement bounded issuer, account, tenant, caller-bound membership `{accountId, tenantId}`, and private-realm indexes for targeted termination, including bounded issuer and membership sweeps and the active-binding termination path. - Prove issuer- and membership-generation cutoff delivery, event projection, duplicate and gap handling, bounded issuer- and membership-index coverage, and termination of every affected active binding within the same fail-closed deadline as other authority cutoffs. - Add batched reconciliation, the 60-second freshness lease, event-gap repair, the index-unavailable fail-closed fallback, and bounded telemetry for event lag, projection failures, reconciliation age, and termination outcome. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index e4f953bca6..90ae339b60 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -285,7 +285,7 @@ The canonical membership, entitlement response shape, freshness, and sequence co The admission owner remains unregistered and non-admitting. Its cancellation and exact negative-state readback methods accept only the original same-namespace Game Session workload and complete unchanged lease evidence; `ReadGameplayAdmissionLease` currently requires `expected_lease` and returns only `PENDING` or `ABORTED`, not `not_observed` or raw storage `COMMITTED`. The positive acquire/finalize/read/reconcile surface is not enabled. The canonical expiry and confirmation requirement is owned by [Session Behavior](../../system-architecture-session-behavior.md#admission-lease-durable-confirmation). -The separate Account-local temporal confirmation preparation stamps the actual finalization transaction and derives immutable proof from independent committed operation readback, ordered PostgreSQL WAL insertion/flush coverage on one primary, and a subsequent conservatively rounded database-time bound before the original expiry. Capture the fixed coverage fence after independent committed observation but before the confirmation transaction emits tuple-lock WAL; then lock Account first and revalidate the exact immutable operation before accepting covered WAL and the time bound. Independently durable receipt readback follows the same observation, capture and locked-revalidation ordering. It requires durable storage settings; unavailable or uncovered WAL, same-transaction finalization and late observation remain denied. Receipt creation must commit before a new transaction independently proves and reads the durable receipt; caller-supplied bounds and bare LSNs carried across a reconnect cannot substitute. Original operation, lease, digest, decision and deadline remain unchanged. This is not an authenticated positive admission result, a current restriction-source producer, Game Session installation proof or completed cleanup. Implementation and executed versus unavailable proof belong to the [Account admission tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-admission-lease-prerequisite). +The separate Account-local temporal confirmation preparation stamps the actual finalization transaction and derives immutable proof from independent committed operation readback, ordered PostgreSQL WAL insertion/flush coverage on one primary, and a subsequent conservatively rounded database-time bound before the original expiry. Enforce a writable SERIALIZABLE transaction, establish its fixed snapshot and capture the database-owned WAL coverage fence before heap reads or tuple locks can emit observer WAL. A subsequently visible independently committed operation in that same snapshot committed before the snapshot and therefore before the captured fence. Exclude the observer's own top-level transaction, including its subtransactions; then lock Account first and revalidate the exact immutable operation before accepting covered WAL and the time bound. Independently durable receipt readback follows the same snapshot, capture and locked-revalidation ordering. It requires durable storage settings; unavailable or uncovered WAL, same-transaction finalization and late observation remain denied. Receipt creation must commit before a new transaction independently proves and reads the durable receipt; caller-supplied bounds and bare LSNs carried across a reconnect cannot substitute. Exact retained replay returns the original receipt without restamping its proof or expiry. Original operation, lease, digest, decision and deadline remain unchanged. This is not an authenticated positive admission result, a current restriction-source producer, Game Session installation proof or completed cleanup. Implementation and executed versus unavailable proof belong to the [Account admission tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-admission-lease-prerequisite). ## Subject-Binding Rules (Normative) diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 7e8799f5db..183dd12b2a 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -96,8 +96,8 @@ Redis coordination keys form a long-running, measured-exposure **coordination bu - Target-state invariant, not a current runtime guarantee: `session:auth:token:` is a narrow security exception whose exact-token registry record is authoritative for runtime protected admission and per-token revocation. A cryptographically valid JWT is denied and requires fresh authentication when its exact active, permitted registry record is reachable but absent, deleted, expired, or revoked; an unavailable registry is retryable `AUTH_UNAVAILABLE` and never permits reconstruction from the JWT or another local representation. This token family is distinct from Account's durable issuer, account, tenant, and membership generation family; those generations remain Account-owned. Redis and non-Account consumers cannot advance or recreate either family. Account may physically delete a record before its natural expiry only after the durable Account `PENDING_LOGOUT`/revocation fence or equivalent tombstone intent has committed; deletion is cleanup and never the revocation proof. For a destructive wipe, Account must durably invalidate old token authority before the wipe; cleanup may delete only old or stale projections, and replacement registry records are registered afterward and remain after registration. During reset recovery, Account alone may rebuild or re-project only its Account-owned `session:auth:token:` values from durable token authority under the documented scope, cutover, and verification gates. - Target-state invariant, not a current runtime guarantee: Account-owned exact-input `session:connect-token:v1:*` issuance-result projections are a separate reset-sensitive projection family from the unversioned legacy `session:connect-token:*` result map. Region- and tenant-scoped resets preserve both families. A planned cluster reset that can drop target records requires Account's durable operation/authority cutover and immutable pre-wipe handoff evidence before the wipe, then exact Account repair and readback before protected admission or the corresponding handshake reopens. An unexpected cold start or observed Redis loss has no pre-wipe gate to satisfy retroactively: protected admission and the handshake remain fail-closed while the affected projection is treated as untrusted and Account performs the owner-defined post-loss repair and exact readback under fenced recovery. Account alone may rebuild target records from the durable issuance-result operation; consumers must not reconstruct one from a JWT, request fields, or Redis key presence. A missing, stale, changed, or ambiguous target projection fails closed. Target values require `schemaVersion: "connect-token-issuance-result-v1"`; target readers never fall back to the legacy family. Because the legacy writer has no issuance fence, target enablement requires full Account-cohort quiescence, in-flight drain, and the configured legacy TTL/retry horizon before legacy writer absence is verified. Legacy records are then owner-cleaned from exact inventory/readback, not migrated or promoted. This family is intentionally not a gameplay/session aggregate and is not covered by `--preserve-sessions` beyond its required preservation under narrower resets. - Target-state invariant, not a current runtime guarantee: Account issuer, account, tenant, and membership generation projections are an approved global/account exception to ordinary Coordination Redis reset handling. Account durable authority remains the sole writer and source of truth; Redis is only a required projection. Region- and tenant-scoped resets preserve these projections and re-project/verify exact generations, while a cluster reset may discard them only after the Account repair/reset cutover, then must rebuild and verify them before protected admission reopens. The implementation limitations near the top of this document remain controlling until the projection and reset workflows are implemented and proved end to end. -- Every issuer-generation projection, including the canonical `session:auth:generation:issuer:` projection and the Game Session `session:game:auth:issuer-generation:v1:` consumer projection, atomically stores `lastAppliedSourceOutboxSequence` (the accepted source `outboxSequence`) and `lastAppliedIssuerGeneration` for its exact canonical `outboxStreamKey`, plus `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` as derived source-checkpoint evidence for every nonzero sequence. These `lastAppliedSource*` fields are projection evidence associated with the canonical `outboxStreamKey`/`outboxSequence` and the applicable `outboxCheckpoints`; they are not authority-tuple fields or JWT claims. For sequence `0`, the two source-event fields are omitted from the projection, not serialized as JSON `null`, an empty string, a zero digest, or another sentinel; the Account-owned zero-sequence checkpoint is the only evidence. For every positive sequence, both source-event fields are required non-null values in their canonical formats. Ordinary delivered events may apply only the next contiguous sequence. A higher delivered sequence is a gap and must quarantine the affected projection and reconcile from Account before advancing the watermark or generation. The sole exception is one Account-owned authoritative snapshot/reconciliation installation, which may atomically install the exact Account checkpoint and generation at its latest sequence without consuming skipped events; that installation must carry the exact snapshot/checkpoint evidence and operation identity, and the next delivered event must be exactly one greater than the installed sequence. For each stream, the projection also retains bounded duplicate evidence for the most recent accepted sequences, at minimum `{outboxStreamKey, outboxSequence, eventId, eventDigest}`; each evidence entry has a required non-null `eventDigest`, and no entry represents the zero-sequence baseline. An equal or lower sequence is a no-op only when that bounded evidence matches or an authoritative Account lookup for the exact `(outboxStreamKey, outboxSequence)` proves the same event identity and digest; a high-water mark alone is never duplicate proof. If the evidence has aged out, the lookup is unavailable, or same-sequence evidence conflicts, the projection is quarantined. A valid next event advances the complete persisted checkpoint even when set-if-greater generation semantics leave the generation unchanged. The gameplay binding's separate `{outboxStreamKey, outboxSequence}` freshness set does not replace this projection-local replay evidence. Projection recovery fails closed while the checkpoint is missing, stale, regressed, ambiguous, or quarantined, including any invalid omitted/null/sentinel representation. -- An empty Game Session issuer projection is an uninstalled and quarantined state, not an implicit zero-authority state and not permission to consume live events. Game Session, not Account, must install `session:game:auth:issuer-generation:v1:` from one Account-owned authoritative snapshot/reconciliation transaction for the exact `issuer/` scope and read back that installed derived projection. That transaction returns the exact checkpoint: `outboxStreamKey = account:auth-authority:v1:issuer/`, `lastAppliedSourceOutboxSequence` equal to the Account checkpoint's exact latest `outboxSequence`, and source `issuerAuthGeneration` from the same snapshot. For a nonzero sequence it also returns the exact source `eventId` and `eventDigest`; for sequence `0`, permitted only when the stream has no committed event, `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` are absent, and the Account-owned zero-sequence checkpoint itself is the evidence. The result also carries the source transaction or immutable bundle version, the exact checkpoint evidence, and the reconciliation operation identity; Game Session must not invent bootstrap event IDs, digests, sequences, or authority values locally. Before consuming events, Game Session atomically persists that complete checkpoint with the exact `issuerAuthGeneration` mapped to canonical persisted `lastAppliedIssuerGeneration`, stores matching `{outboxStreamKey, outboxSequence, eventId, eventDigest}` duplicate evidence only for a nonzero checkpoint, and reads back the installed projection. For a zero-sequence baseline, duplicate evidence is empty and the first consumable event must be sequence `1`; for a nonzero baseline, the next consumable event must be exactly `lastAppliedSourceOutboxSequence + 1`. Until the atomic installation and exact readback succeed, or if any applicable snapshot, source-checkpoint, event-identity/digest, or authority value is missing, stale, regressed, contradictory, or ambiguous, the projection remains quarantined and issuer-gated admission, reconnect, and revocation consumption fail closed. +- Every issuer-generation projection, including the canonical `session:auth:generation:issuer:` projection and the Game Session `session:game:auth:issuer-generation:v1:` consumer projection, atomically stores `lastAppliedSourceOutboxSequence` (the accepted source `outboxSequence`) and `lastAppliedIssuerGeneration` for its exact canonical `outboxStreamKey`, plus `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` as derived source-checkpoint evidence for every nonzero sequence. These `lastAppliedSource*` fields are evidence for the complete closed issuer event schema associated with the canonical `outboxStreamKey`/`outboxSequence`; they are not authority-tuple fields, `outboxCheckpoints` members, or JWT claims. Recipient Account-authenticated tuple, actual fence, and checkpoint evidence is separate and is not installed in this issuer projection. For sequence `0`, the two source-event fields are omitted from the projection, not serialized as JSON `null`, an empty string, a zero digest, or another sentinel; the Account-owned zero-sequence checkpoint is the only evidence. For every positive sequence, both source-event fields are required non-null values in their canonical formats. Ordinary delivered events may apply only the next contiguous sequence. A higher delivered sequence is a gap and must quarantine the affected projection and reconcile from Account before advancing the watermark or generation. The sole exception is one Account-owned authoritative snapshot/reconciliation installation, which may atomically install the exact Account checkpoint and generation at its latest sequence without consuming skipped events; that installation must carry the exact snapshot/checkpoint evidence and operation identity, and the next delivered event must be exactly one greater than the installed sequence. For each stream, the projection also retains bounded duplicate evidence for the most recent accepted sequences, at minimum `{outboxStreamKey, outboxSequence, eventId, eventDigest}`; each evidence entry has a required non-null `eventDigest`, and no entry represents the zero-sequence baseline. An equal or lower sequence is a no-op only when that bounded evidence matches or an authoritative Account lookup for the exact `(outboxStreamKey, outboxSequence)` proves the same event identity and digest; a high-water mark alone is never duplicate proof. If the evidence has aged out, the lookup is unavailable, or same-sequence evidence conflicts, the projection is quarantined. A valid next event advances the complete persisted checkpoint even when set-if-greater generation semantics leave the generation unchanged. The gameplay binding's separate `{outboxStreamKey, outboxSequence}` freshness set does not replace this projection-local replay evidence. Projection recovery fails closed while the checkpoint is missing, stale, regressed, ambiguous, or quarantined, including any invalid omitted/null/sentinel representation. +- An empty Game Session issuer projection is an uninstalled and quarantined state, not an implicit zero-authority state and not permission to consume live events. Game Session, not Account, must install `session:game:auth:issuer-generation:v1:` from one Account-owned issuer-source snapshot/reconciliation operation for the exact `issuer/` scope and read back that installed derived projection, as defined by [ADR 0030](./decisions/adr-0030-risk-based-active-session-revocation.md). That operation returns the exact checkpoint: `outboxStreamKey = account:auth-authority:v1:issuer/`, `lastAppliedSourceOutboxSequence` equal to the Account checkpoint's exact latest `outboxSequence`, committed `issuerAuthGeneration` and its immutable source version from the same source snapshot. For a nonzero sequence it also returns the exact source `eventId` and `eventDigest`; for sequence `0`, permitted only when the stream has no committed event, `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` are absent, and the Account-owned zero-sequence checkpoint itself is the evidence. The result binds the source transaction or immutable source version to the exact reconciliation operation identity; it carries no recipient `authorityTuple`, `issuanceFence`, or full `outboxCheckpoints` set. Game Session must not invent bootstrap event IDs, digests, sequences, or authority values locally. Before consuming events, Game Session atomically persists that issuer checkpoint with the exact `issuerAuthGeneration` mapped to canonical persisted `lastAppliedIssuerGeneration`, stores matching `{outboxStreamKey, outboxSequence, eventId, eventDigest}` duplicate evidence only for a nonzero checkpoint, and reads back the installed projection. For a zero-sequence baseline, duplicate evidence is empty and the first consumable event must be sequence `1`; for a nonzero baseline, the next consumable event must be exactly `lastAppliedSourceOutboxSequence + 1`. Until the atomic installation and exact readback succeed, or if any applicable issuer snapshot, source-checkpoint, event-identity/digest, source-version, or authority value is missing, stale, regressed, contradictory, or ambiguous, the projection remains quarantined and issuer-gated admission, reconnect, and revocation consumption fail closed. - Canonical issuer snapshot mapping is exact across bootstrap, persistence, readback, replay, and recovery: Account's authoritative snapshot field `issuerAuthGeneration` maps one-to-one to the projection field `lastAppliedIssuerGeneration`. The latter is the only persisted projection field used for comparison and replay advancement; `issuerAuthGeneration` is the source snapshot/authority name and is not a second persisted alias or a local fallback. Every bootstrap install, event replay, exact readback, set-if-greater repair decision, and recovery acknowledgement must compare the mapped value together with the exact `outboxStreamKey`, `lastAppliedSourceOutboxSequence`, source event evidence, and operation/checkpoint evidence. - Spring Cloud Gateway has one narrow Coordination Redis authority: one-use connect-token replay consumption under `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, browser-revocation deny markers under `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, the shared replay-readiness record under `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and a separate Gateway-generated disposable recovery-probe marker under `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`. The readiness value carries the shared `replayAdmissionFence`. Any marker-loss or reset event that can break replay continuity keeps shared readiness quarantined under an advanced `replayAdmissionFence` until the canonical [ADR 0029 readiness proof](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md) permits reopening; during that quarantine, an absent `jti` marker alone never proves first use. The probe marker is not a player `jti` or deny marker: its typed probe runs only in `QUARANTINED`, does not accept player credentials or write shared readiness, and returns evidence to the recovery coordinator. Normal player consume remains `OPEN`-only; only the coordinator may reopen after every release gate passes. The Gateway fails closed when that replay authority is unavailable, owns marker TTLs and reset contract, and must not expand this exception into ownership of gameplay sessions, Account auth state, or general coordination policy. These probe and release contracts are target-only and currently unimplemented. @@ -368,7 +368,7 @@ Every binding writer and removal, issuer cutoff reader, capacity reservation CAS Changing `issuerIndexPartitionCount` is a layout migration, not a configuration refresh. Game Session creates a durable layout-transition operation under one `operationId` and `operationFence`, captures the expected active pointer as the pinned old layout `{issuerIndexLayoutVersion, issuerIndexPartitionCount, issuerIndexPartitionCapacity}`, and records the complete new layout as a separate pinned target. New binding/reconnect/resume admission and issuer cutoffs are fenced for the affected issuer, the complete durable inventory and unresolved obligations are snapshotted, and every new partition is rebuilt from that snapshot. The transition record covers both old and new layout descriptors, but migration is the only workflow allowed to read the old layout as a source and the new layout as a target; player, cutoff, and recovery readers never combine partitions from both layouts. It records and applies terminal transitions under the migration fence, proves per-partition capacity and exact readback for the new layout, and publishes durable per-layout coverage acknowledgements. Only a compare-and-set that still matches the pinned old pointer and `operationFence` may advance the active pointer to the pinned new version/count/capacity. Before that CAS, all ordinary readers and writers use only the old pointer; after it, they use only the new pointer. A crash leaves the old pointer active and resumes or abandons the recorded transition; an absent, changed, ambiguous, or mixed pointer fails closed. The old layout is retained read-only until the post-cutover drain/reconciliation window proves zero in-flight old-layout operations, then is removed by a separate fenced cleanup. A modulo change without this versioned build, pointer cutover, and old-layout drain is unsupported. -Before enumeration, Game Session establishes one issuer-wide admission `coverageFence` and immutable `inventorySnapshotRevision` under the durable `operationId`/`operationFence`, and pins the active layout pointer as `{issuerIndexLayoutVersion, issuerIndexPartitionCount, issuerIndexPartitionCapacity}` for that operation. The snapshot contains the exact `issuer/` cutoff checkpoint, issuer generation, `issuanceFence`, complete applicable `outboxCheckpoints`, and the pinned layout identity. `coverageFence` is the immutable admission/creation fence for that inventory snapshot and is distinct from the maintenance `operationFence`; `coverageGeneration` is a later generation used to account for every post-fence transition. New binding, reconnect, and resume admission is blocked against that fence while coverage is open; a post-fence binding can become admissible only when it and its exact durable evidence carrier bind both the `operationFence` and `coverageFence` plus a later `coverageGeneration` to the same operation and `inventorySnapshotRevision`. Carrying only one fence or only the coverage generation is invalid. Any race that produces a non-admissible candidate, reservation, or repair obligation must be accounted for before acknowledgement. A standalone issuer-wide operation persists `parentRecoveryOperationId=NOT_APPLICABLE`, `parentLifecycle=NOT_APPLICABLE`, `parentOperationFence=NOT_APPLICABLE`, and `parentCoverageFence=NOT_APPLICABLE`, and self-binds `issuerCoverageOperationId=operationId`, `issuerCoverageLifecycle=lifecycle`, and `issuerCoverageOperationFence=operationFence`; a linked child instead associates the exact parent tuple only through its independent parent edge, while the child itself owns only its operation and coverage fences and never nests under the parent maintenance lock. Every linked child request, digest, transition, readback, acknowledgement, and retry carries only the child-owned tuple; the independent edge and parent's consumption record carry the exact parent tuple and validate the child result. Standalone records carry the four exact `NOT_APPLICABLE` parent markers. Game Session durably acknowledges each partition only with the parent-independent child issuer-partition acknowledgement tuple defined above: issuer operation identity/lifecycle/fence, `issuerId`, applicable child fences, snapshot revision, later coverage generation, pinned layout version/count/capacity, `partitionId`, exact cutoff, reservation lifecycle identities, and local plus aggregate capacity evidence. A missing HASH key is an empty partition only when the read succeeded and the matching acknowledgement proves coverage for that exact issuer-wide snapshot, operation attempt, layout, cutoff, and fences. A missing, stale, or mismatched acknowledgement, cross-snapshot or cross-attempt evidence, an unavailable read, malformed value, conflicting duplicate, unresolved reservation, or unresolved repair obligation is ambiguous coverage; the cutoff fails closed and requires reconciliation/rebuild rather than inferring empty coverage from key absence or an aggregate proof. The coverage generation is index-maintenance evidence, not a second authority generation. +Before enumeration, Game Session establishes one issuer-wide admission `coverageFence` and immutable `inventorySnapshotRevision` under the durable `operationId`/`operationFence`, and pins the active layout pointer as `{issuerIndexLayoutVersion, issuerIndexPartitionCount, issuerIndexPartitionCapacity}` for that operation. The snapshot contains the exact issuer source checkpoint `{outboxStreamKey, outboxSequence}`, committed `issuerAuthGeneration` and immutable source-version evidence from the same Account issuer snapshot, plus the pinned layout identity. It contains no recipient `authorityTuple`, `issuanceFence`, or full `outboxCheckpoints` set; those remain separate evidence for Account-issued recipient admission/rebind. `coverageFence` is the immutable admission/creation fence for that inventory snapshot and is distinct from the maintenance `operationFence`; `coverageGeneration` is a later generation used to account for every post-fence transition. New binding, reconnect, and resume admission is blocked against that fence while coverage is open; a post-fence binding can become admissible only when it and its exact durable evidence carrier bind both the `operationFence` and `coverageFence` plus a later `coverageGeneration` to the same operation and `inventorySnapshotRevision`. Carrying only one fence or only the coverage generation is invalid. Any race that produces a non-admissible candidate, reservation, or repair obligation must be accounted for before acknowledgement. A standalone issuer-wide operation persists `parentRecoveryOperationId=NOT_APPLICABLE`, `parentLifecycle=NOT_APPLICABLE`, `parentOperationFence=NOT_APPLICABLE`, and `parentCoverageFence=NOT_APPLICABLE`, and self-binds `issuerCoverageOperationId=operationId`, `issuerCoverageLifecycle=lifecycle`, and `issuerCoverageOperationFence=operationFence`; a linked child instead associates the exact parent tuple only through its independent parent edge, while the child itself owns only its operation and coverage fences and never nests under the parent maintenance lock. Every linked child request, digest, transition, readback, acknowledgement, and retry carries only the child-owned tuple; the independent edge and parent's consumption record carry the exact parent tuple and validate the child result. Standalone records carry the four exact `NOT_APPLICABLE` parent markers. Game Session durably acknowledges each partition only with the parent-independent child issuer-partition acknowledgement tuple defined above: issuer operation identity/lifecycle/fence, `issuerId`, applicable child fences, snapshot revision, later coverage generation, pinned layout version/count/capacity, `partitionId`, exact issuer source checkpoint, reservation lifecycle identities, and local plus aggregate capacity evidence. A missing HASH key is an empty partition only when the read succeeded and the matching acknowledgement proves coverage for that exact issuer-wide snapshot, operation attempt, layout, cutoff, and fences. A missing, stale, or mismatched acknowledgement, cross-snapshot or cross-attempt evidence, an unavailable read, malformed value, conflicting duplicate, unresolved reservation, or unresolved repair obligation is ambiguous coverage; the cutoff fails closed and requires reconciliation/rebuild rather than inferring empty coverage from key absence or an aggregate proof. The coverage generation is index-maintenance evidence, not a second authority generation. For every partition `p`, `N_issuer_partition(p)` counts distinct non-terminal durable reservation entries, with each binding transition counted once even when its reservation is attached to an active, provisional, or unresolved binding. Each `IssuerPartitionReservation` is Game Session-owned durable evidence with `reservationId`, `owner` (the complete `bindingRef` and owning session identity), exact `transitionId`, `issuerId`, `partitionId`, `issuerIndexLayoutVersion`, lifecycle (`RESERVED`, `BOUND`, `RELEASE_PENDING`, or terminal `RELEASED`), `reservationFence`, and the exact coverage tuple `{issuerCoverageOperationId, operationFence, coverageFence, inventorySnapshotRevision}`. `inventorySnapshotRevision` is the complete immutable issuer-inventory revision; it is not a caller-selected or generic local revision. Before any tenant-local binding CAS publishes a binding, Game Session commits the reservation and any repair obligation in the same durable transaction, then atomically reserves one unit in the target issuer partition through a single-key capacity compare-and-set keyed by the exact reservation and transition. That CAS exact-compares the owner, transition, partition/layout, lifecycle, reservation fence, `issuerCoverageOperationId`, `operationFence`, `coverageFence`, and `inventorySnapshotRevision`, and is idempotent only for the same complete reservation tuple. It rejects or backpressures when the reservation would exceed `issuerIndexPartitionCapacity`. A binding cannot become admissible or a repair obligation be considered covered without the matching reservation. The reservation remains counted through `RESERVED`, `BOUND`, and `RELEASE_PENDING`; failed or ambiguous cleanup leaves it counted. Terminal cleanup first records `RELEASE_PENDING`, exact-compares the same coverage tuple while removing the binding field through the fenced CAS, removes/releases the capacity entry, reads back both absences and the exact terminal state with that tuple, and only then records `RELEASED`; terminal evidence remains available for idempotent reconciliation. Every CAS, readback, acknowledgement, and cleanup must exact-compare all four coverage-tuple fields; a binding-only, reservation-only, operation-only, or current-snapshot match cannot substitute. This reservation-before-binding protocol serializes concurrent admissions at the partition and prevents over-capacity races. At recovery, Game Session must enumerate the complete binding and reservation inventory, establish the same finite per-partition invariant for every `p`, and publish no coverage acknowledgement when any non-terminal reservation exceeds capacity. The aggregate proof is additionally required: `N_issuer = sum_p N_issuer_partition(p) <= issuerIndexPartitionCount * issuerIndexPartitionCapacity`. Aggregate capacity alone is insufficient. @@ -384,7 +384,7 @@ For preserved-session region- or tenant-scoped recovery, the scoped recovery ope An issuer-partition acknowledgement is either a standalone issuer-operation artifact or a linked-child artifact, never a region/tenant parent artifact. A standalone publication transaction validates `parentRecoveryOperationId=NOT_APPLICABLE`, `parentLifecycle=NOT_APPLICABLE`, `parentOperationFence=NOT_APPLICABLE`, `parentCoverageFence=NOT_APPLICABLE`, and the self-bound `issuerCoverageOperationId=operationId`, `issuerCoverageLifecycle=lifecycle`, `issuerCoverageOperationFence=operationFence`, and distinct `coverageFence`. A linked-child publication transaction validates the child identity and current lifecycle, the child `issuerCoverageOperationFence`, and the child `coverageFence` before recording the pinned issuer snapshot/layout/cutoff, later `coverageGeneration`, reservation identities, and partition-local plus issuer-wide capacity tuple; every reservation identity includes and exact-compares `issuerCoverageOperationId`, `operationFence`, `coverageFence`, and `inventorySnapshotRevision`. The independent parent edge and parent's consumption CAS validate the parent identity/lifecycle/fences, linked child identity, and `linkRevision`. The same child-owned tuple is required in the linked request/digest, partition and reservation CAS/readback, acknowledgement, exact retry, and cleanup; the edge and parent-consumption CAS additionally carry the exact parent tuple and must revalidate the full snapshot/layout/cutoff/reservation/capacity tuple rather than trusting a previously complete readback. A stale, terminal, or mismatched parent, child, reservation, operation, snapshot, or fence fails closed even when the partition readback is complete; a parent may consume only the complete finite set of acknowledgements from its linked child, with every expected partition, and only after the child reaches its coverage-proven lifecycle. A standalone operation completes and validates its own finite acknowledgement set and has no parent-consumption path. -An issuer-generation replay at sequence `0` is a no-op only when the exact canonical `outboxStreamKey` matches, the received sequence is exactly zero, and an Account-owned zero-sequence checkpoint proves that the stream has no committed event. The source event fields `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` must be omitted in that baseline, never represented by null or sentinels; a sequence-0 value from another stream or a caller-supplied baseline is not a no-op. Positive sequences require the exact stream key, contiguous sequence proof, source event identity, event digest, and complete Account snapshot/checkpoint proof. +An issuer-generation replay at sequence `0` is a no-op only when the exact canonical `outboxStreamKey` matches, the received sequence is exactly zero, and an Account-owned issuer zero-sequence checkpoint proves that the stream has no committed event. The source event fields `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` must be omitted in that baseline, never represented by null or sentinels; a sequence-0 value from another stream or a caller-supplied baseline is not a no-op. Positive sequences require the exact issuer stream key, contiguous sequence proof, source event identity and digest, committed issuer generation/source-version evidence, and the exact issuer source snapshot/checkpoint proof defined by ADR 0030. Recipient admission or rebind separately requires the Account-authenticated complete same-snapshot `authorityTuple`, actual `issuanceFence`, and full `outboxCheckpoints` set; those are not issuer-projection replay fields. The issuer binding/index CAS must persist and exact-compare the complete binding fields together with reservation identity, owner, transition, partition and layout, lifecycle, fence, and revision in one atomic durable result, or use separate atomic binding and reservation CAS results joined in one durable acknowledgement. The acknowledgement must preserve and exact-compare all of those fields, and recovery must read back and reconcile the same complete joined result before clearing an obligation or publishing coverage; a binding-only or reservation-only success cannot authorize recovery. diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index 5a961173ad..1fc1102a37 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -4,7 +4,7 @@ This document defines gameplay takeover, reconnect, token refresh, membership-ve ## Canonical Authority Tuple -The canonical `authorityTuple` schema, exact nested field names, profile requirements, and registry mapping are defined in [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple). This document does not duplicate that schema. Session behavior copies the canonical tuple unchanged into applicable events, leases, bindings, refresh requests, rebind proofs, registry records/claims, and installation acknowledgements; missing applicable evidence, extra scope, malformed values, or mismatches fail closed. +The canonical `authorityTuple` schema, exact nested field names, profile requirements, and registry mapping are defined in [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple). This document does not duplicate that schema. For recipient event consumption, Account authenticates the applicable tuple as separate same-snapshot source evidence bound to the exact event identity/digest; the closed recipient event does not carry the tuple. Session behavior otherwise carries the canonical tuple unchanged through applicable leases, bindings, refresh requests, rebind proofs, registry records/claims, and installation acknowledgements; missing applicable evidence, extra scope, malformed values, or mismatches fail closed. Issuer-generation source events and projection bootstrap use the separate closed issuer schema in [ADR 0030](./decisions/adr-0030-risk-based-active-session-revocation.md); they contain no recipient tuple, `issuanceFence`, or full checkpoint set. Session behavior uses one immutable `membershipBaseline` carrier for each admission or replacement operation: @@ -16,13 +16,13 @@ Session behavior uses one immutable `membershipBaseline` carrier for each admiss } ``` -The object is captured from one Account snapshot and is carried unchanged, as one object rather than three independently sourced fields, through the admission lease, lease identity and request digest, Game Session binding CAS, Account finalization and `COMMITTED` comparison, and every exact retry/replay. Each boundary compares the complete object, including lifecycle state, the sole tenant key/value, and the exact membership authority generation; missing, extra, scalarized, null, stale, or differently keyed evidence fails closed. A new refresh or rebind operation may establish a new baseline only from its own Account snapshot; it must not mutate the baseline inside the operation being retried or finalized. The `billing_safe_tenant` exception omits the target-tenant generation only from route comparison, never from this required carrier or the canonical tuple shape. Account owns all canonical authority-generation projections; Game Session may maintain only the distinct derived issuer projection and schema defined by [ADR 0022](./decisions/adr-0022-account-authority-and-gameplay-session-ownership.md). +The object is captured from one Account snapshot and is carried unchanged, as one object rather than three independently sourced fields, through the admission lease, lease identity and request digest, Game Session binding CAS, Account finalization and `COMMITTED` comparison, and every exact retry/replay. Each boundary compares the complete object, including lifecycle state, the sole tenant key/value, and the exact membership authority generation; missing, extra, scalarized, null, stale, or differently keyed evidence fails closed. A new refresh or rebind operation may establish a new baseline only from its own Account snapshot; it must not mutate the baseline inside the operation being retried or finalized. The `billing_safe_tenant` exception omits the target-tenant generation only from route comparison, never from this required carrier or the canonical tuple shape. Account owns all canonical authority-generation projections; Game Session may maintain only the distinct derived issuer projection described in [Redis Architecture](./system-architecture-redis.md#redis-coordination-invariants), using the issuer source and bootstrap contract owned by [ADR 0030](./decisions/adr-0030-risk-based-active-session-revocation.md). Target admission behavior carries the same unchanged `membershipBaseline` through admission lease state, lease identity/digest, the Game Session binding CAS, Account finalization and `COMMITTED` evidence, and all retries/replays. The separate `membershipVersion` map remains available wherever the canonical JWT or authority contract requires it, but it is never used as a substitute for the baseline object or for `membershipAuthorityGeneration`. -The canonical `outboxCheckpoints` entry schema remains the ADR 0030 `{outboxStreamKey, outboxSequence}` carrier; [ADR 0022](./decisions/adr-0022-account-authority-and-gameplay-session-ownership.md#canonical-checkpoint-and-source-evidence-binding) defines its bytewise ordering and the separate same-snapshot source-evidence binding. Session behavior carries the exact complete checkpoint array unchanged through authority-event delivery, admission and refresh leases, binding CAS, refresh, rebind, installation acknowledgement, retries/replays, and every request or response digest; it never reconstructs the set from a latest checkpoint, aggregate maximum, or separately read event evidence. +The canonical recipient `outboxCheckpoints` entry schema remains the ADR 0030 `{outboxStreamKey, outboxSequence}` carrier; [ADR 0022](./decisions/adr-0022-account-authority-and-gameplay-session-ownership.md#canonical-checkpoint-and-source-evidence-binding) defines its bytewise ordering and [ADR 0030](./decisions/adr-0030-risk-based-active-session-revocation.md) owns the source-evidence contract. Recipient event consumption pairs the closed event with separate Account-authenticated same-snapshot evidence bound to its exact event identity/digest; that evidence is not added to the event. Session behavior carries the complete recipient checkpoint array unchanged through admission and refresh leases, binding CAS, refresh, rebind, installation acknowledgement, retries/replays, and every request or response digest; it never reconstructs the set from a latest checkpoint, aggregate maximum, or separately read event evidence. An issuer event carries only its exact issuer stream checkpoint under the closed issuer schema and does not expand to the recipient checkpoint array. -Retained per-sequence duplicate evidence is a separate same-snapshot carrier, not an expanded checkpoint entry. Its canonical schema is `{outboxStreamKey, outboxSequence, eventId, eventDigest, authorityTuple, issuanceFence, membershipBaseline, outboxCheckpoints}` when membership applies; a non-membership scope omits `membershipBaseline` rather than fabricating membership values. The complete evidence is retained for each bounded sequence window or proven by an authoritative Account lookup for the exact stream and sequence. A checkpoint array alone, an event ID/digest pair alone, a generation-only match, or evidence assembled from another Account snapshot is never duplicate proof. +Retained per-sequence duplicate evidence is a separate source-evidence carrier, not an expanded checkpoint entry. For recipient membership events, consumers retain the complete closed event evidence and its separate Account-authenticated same-snapshot `authorityTuple`, actual `issuanceFence`, `membershipBaseline`, and `outboxCheckpoints`, bound to the exact event identity/digest; other recipient event types retain their applicable closed event and separately authenticated source evidence. The issuer projection retains or resolves the complete closed issuer event evidence, including exact issuer scope, committed generation/source version and stream checkpoint, with event identity and digest for positive sequences; it does not attach recipient tuple, fence, or checkpoint-set fields. Complete source evidence must remain in the bounded sequence window or be proven by an authoritative lookup for the exact stream and sequence. A recipient checkpoint array alone, an event ID/digest pair alone, a generation-only match, or evidence assembled from another source snapshot is never duplicate proof. ## Canonical Monotonic Integer Strings @@ -32,9 +32,9 @@ Retained per-sequence duplicate evidence is a separate same-snapshot carrier, no Membership-change event delivery and generation-aware session consumption are not yet live. The current `GetTenantMembershipForRuntimeResponse` and `AccountGrpcService` producer expose `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `evaluatedAt`, and `error`; the current Game Session `PLAY` path consumes that response, while roles, the target exact one-tenant `membershipVersion` map carrier, `membershipAuthorityGeneration`, `authorityTuple`, `outboxCheckpoints`, Account event delivery, generation-aware consumers, same-stream reconciliation, remaining player-facing legacy mapping, and focused proof across admission/reconnect paths remain gaps. The versioned Account-owned token-registry rules and binding schema below are target state, not current runtime behavior: the current fallback uses the legacy Account session key rather than the canonical issued-token registry. Game Session must not treat the contract below as fully implemented until those fields, consumers, and proofs converge. The target Account-durable-intent-before-Gateway-marker logout ordering and final Account token-fence invalidation are also not currently proven; the current fallback is Account logout plus local cleanup and bounded expiry, not proof of complete logout. -Account Service is the sole writer of account authority-generation advances and all canonical `session:auth:generation:*` projections, including `session:auth:generation:account:`. Account commits every applicable canonical tuple field, cutoff, `issuanceFence`, and monotonic outbox event together; the generation projection is an asynchronous outbox output, not an atomically committed part of that durable generation/event transaction. Game Session and other downstream services consume Account-owned generation events and projections; they must not advance canonical authority or write canonical projections directly, and they fail closed while projection or freshness/source evidence is missing, stale, malformed, regressed, or ambiguous. Game Session's only generation projection write is its derived `session:game:auth:issuer-generation:v1:` consumer-local record under the ADR 0022 schema. +Account Service is the sole writer of account authority-generation advances and all canonical `session:auth:generation:*` projections, including `session:auth:generation:account:`. Recipient Account-authority changes commit their applicable tuple fields, actual `issuanceFence`, closed source event, and checkpoint together; Account-authenticated same-snapshot recipient evidence separately carries the tuple, actual fence, and full checkpoint set bound to the exact event identity/digest. This separate evidence does not extend the closed event schema or its digest input. Issuer-generation changes use ADR 0030's separate closed issuer source event and snapshot, without recipient tuple, fence, or full checkpoint-set fields. Canonical generation projections are asynchronous outbox outputs, not atomically committed parts of the durable generation/event transaction. Game Session and other downstream services consume Account-owned generation events and projections; they must not advance canonical authority or write canonical projections directly, and they fail closed while projection or freshness/source evidence is missing, stale, malformed, regressed, or ambiguous. Game Session's only issuer-generation projection write is its derived `session:game:auth:issuer-generation:v1:` consumer-local record, with the local consequences described in [Redis Architecture](./system-architecture-redis.md#redis-coordination-invariants). -For account security events, Account alone advances the durable authority tuple, applicable cutoff, and `issuanceFence` and emits the corresponding committed outbox event in the same Account transaction; an asynchronous projection consumer later applies each canonical generation set-if-greater. Game Session consumes that event and projection idempotently, applies the separate derived issuer projection set-if-greater, and revokes only its owned gameplay bindings through the bounded issuer, account, tenant, membership, private-realm, and character-uniqueness indexes plus their ordered repair/CAS protocol; it must not scan Redis, advance Account authority, write canonical projections, or infer authorization from a missing or stale projection. +For account-security events, Account alone advances the durable recipient authority tuple and applicable cutoff/`issuanceFence` and commits the corresponding closed source event and checkpoint in the same Account transaction. The separate Account-authenticated same-snapshot recipient evidence is bound to that event's exact identity/digest; an asynchronous projection consumer later applies each canonical generation set-if-greater. Game Session consumes the event and bound evidence idempotently and revokes only its owned gameplay bindings through the bounded account, tenant, membership, private-realm, and character-uniqueness indexes plus their ordered repair/CAS protocol. Issuer-generation events separately update only the derived issuer projection and issuer-index effects under ADR 0030. Game Session must not scan Redis, advance Account authority, write canonical projections, or infer authorization from a missing or stale projection. ### Playtest Grant and Lifecycle Session Consequences @@ -92,7 +92,7 @@ This is backend role-context maintenance only. It does not prompt for another ga Membership changes that affect tenant access follow a stricter target contract than ordinary role refresh: -1. The Account Service emits a membership-change event containing `accountId`, `tenantId`, `membershipLifecycleState`, `membershipVersion`, complete applicable `authorityTuple`, positive `issuanceFence`, `outboxStreamKey`, `outboxSequence`, the complete stream-key-ordered `outboxCheckpoints`, `changedRoleSet` as the complete post-change role snapshot represented by a sorted array of unique ASCII role identifiers under the canonical bytewise comparator, whether gameplay admission remains allowed, the Account-committed boolean `callerBoundAuthorityInvalidated`, and `eventDigest` from that same authoritative snapshot/checkpoint. +1. The Account Service emits a membership-change event with its closed event-type fields, including `accountId`, `tenantId`, `membershipLifecycleState`, `membershipVersion`, `outboxStreamKey`, `outboxSequence`, `changedRoleSet` as the complete post-change role snapshot represented by a sorted array of unique ASCII role identifiers under the canonical bytewise comparator, whether gameplay admission remains allowed, the Account-committed boolean `callerBoundAuthorityInvalidated`, and `eventDigest` over that closed event schema. Account separately authenticates the complete same-snapshot recipient `authorityTuple`, actual `issuanceFence`, and full stream-key-ordered `outboxCheckpoints` evidence, bound to the exact event ID/digest; the event alone is not recipient admission or rebind evidence. [ADR 0030](./decisions/adr-0030-risk-based-active-session-revocation.md) owns the closed event and separate source-evidence contract. 2. Game Session compares the event against active gameplay bindings for `{accountId, tenantId}`. 3. Losing tenant membership or losing gameplay-admission authority (for example removal of `player` or a required private-realm grant) immediately revokes the affected gameplay sessions. Planned realm or playtest closure uses the owning close-and-drain workflow before grants are revoked; grant revocation itself is not a graceful-drain mechanism. 4. For caller-bound tenant control-plane access, the Account Service must also advance the `{accountId, tenantId}` membership authority generation when membership or tenant-role changes invalidate previously issued tenant authority for that caller. @@ -102,21 +102,21 @@ Membership changes that affect tenant access follow a stricter target contract t Target membership-change event delivery semantics are required, not best-effort folklore: -- Every event must include `schemaVersion`, a stable `eventId`, `eventType`, exact `outboxStreamKey`, `outboxSequence`, `sourceScope`, `occurredAt`, `eventDigest`, and the complete payload tuple `{accountId, tenantId, membershipLifecycleState, membershipVersion, authorityTuple, issuanceFence, changedRoleSet, gameplayAdmissionAllowed, callerBoundAuthorityInvalidated, outboxCheckpoints}`; `outboxCheckpoints` is the complete stream-key-ordered checkpoint set from the same Account snapshot, not a latest-only or aggregate value. +- Every event must include `schemaVersion`, a stable `eventId`, `eventType`, exact `outboxStreamKey`, `outboxSequence`, `sourceScope`, `occurredAt`, `eventDigest`, and its complete declared membership payload, including `{accountId, tenantId, membershipLifecycleState, membershipVersion, changedRoleSet, gameplayAdmissionAllowed, callerBoundAuthorityInvalidated}`. The separately Account-authenticated same-snapshot recipient source evidence includes the applicable complete `authorityTuple`, actual `issuanceFence`, unchanged `membershipBaseline` where applicable, and full stream-key-ordered `outboxCheckpoints`, bound to the exact event ID/digest; these fields are not event-schema or digest fields. A partial, stale, cross-snapshot, or unbound carrier is invalid. [ADR 0030](./decisions/adr-0030-risk-based-active-session-revocation.md) owns the complete source-evidence validation contract. - A role identifier is an ASCII string matching `[A-Za-z][A-Za-z0-9_-]*`; its bytes are used exactly as supplied, so case variants are distinct and whitespace, non-ASCII characters, Unicode escapes that decode to non-ASCII, and other spellings are invalid. `compareRoleIdentifierBytes(a, b)` is the one canonical comparator: compare the unsigned identifier bytes lexicographically, with the shorter identifier first when one is a prefix. Producers validate every identifier, reject bytewise duplicates, and sort `changedRoleSet` with this comparator without Unicode normalization, locale collation, case folding, or other transformation. Consumers apply the same validation and comparator and reject an unsorted, duplicated, malformed, or differently normalized array; `[]` is the only empty representation. -- `eventDigest` has one canonical meaning: it is `sha256:` followed by 64 lowercase hexadecimal characters for SHA-256 over UTF-8 RFC 8785 JSON Canonicalization Scheme bytes of the complete membership-event envelope and payload, excluding only the `eventDigest` field itself. The canonical schema field set is exactly `schemaVersion`, `eventId`, `eventType`, `outboxStreamKey`, `outboxSequence`, `sourceScope`, `accountId`, `tenantId`, `membershipLifecycleState`, `membershipVersion`, `authorityTuple`, `issuanceFence`, `changedRoleSet`, `gameplayAdmissionAllowed`, `callerBoundAuthorityInvalidated`, `outboxCheckpoints`, and `occurredAt`. Every field in that emitted envelope, including `eventDigest`, is required and non-null; `changedRoleSet` is the complete post-change role snapshot as a sorted array of unique role identifiers and uses `[]` when empty, not an added/removed delta or an unordered set. `outboxCheckpoints` is complete, canonicalized in stream-key order, and comes from the same authoritative snapshot as the payload tuple. Any optional members nested inside `authorityTuple` use the canonical authority-tuple presence rules rather than a new event-specific encoding. An absent optional nested member is represented by omission, never by JSON `null`, an empty string, or a sentinel. `outboxSequence` is a canonical unsigned base-10 JSON string. `membershipVersion` uses the canonical exact one-tenant map `{tenantId: version}`; its sole value uses that same unsigned-string grammar. This preserves values beyond IEEE-754 exact-integer range and the shared carrier shape across implementations. RFC 8785 preserves string data as supplied; producers perform no Unicode normalization before canonicalization. No envelope field may be omitted, added, or serialized through an alternate grammar. Account computes the digest and consumers recompute and compare it before applying or acknowledging the event. -- The sole value in the validated exact one-tenant `membershipVersion` map must be monotonic per `{accountId, tenantId}` and must advance on any role or membership change that can affect gameplay or tenant-safe control-plane authority. A consumer may extract that value only as a process-local arbitrary-precision integer after validating the complete map and exact tenant key; the event, digest, projection, and binding retain the map. `membershipAuthorityGeneration` is a separate authority fence that advances only when `callerBoundAuthorityInvalidated=true`, meaning the change invalidates previously issued caller-bound tenant authority. A non-revoking change must carry `callerBoundAuthorityInvalidated=false`, the current unchanged opaque generation, and complete same-snapshot `authorityTuple`/`issuanceFence`/checkpoint evidence proving that no prior caller-bound authority was invalidated. Missing or mismatched proof fails closed. Consumers must not substitute `membershipVersion` for the generation or use either field as the other's proof. +- `eventDigest` has one canonical meaning: it is `sha256:` followed by 64 lowercase hexadecimal characters for SHA-256 over UTF-8 RFC 8785 JSON Canonicalization Scheme bytes of the complete closed membership-event envelope and payload, excluding only the `eventDigest` field itself. The canonical schema field set is exactly `schemaVersion`, `eventId`, `eventType`, `outboxStreamKey`, `outboxSequence`, `sourceScope`, `accountId`, `tenantId`, `membershipLifecycleState`, `membershipVersion`, `changedRoleSet`, `gameplayAdmissionAllowed`, `callerBoundAuthorityInvalidated`, `eventDigest`, and `occurredAt`. Every field in that closed event envelope, including `eventDigest`, is required and non-null; separately authenticated recipient source evidence is not included in the event or digest. `changedRoleSet` is the complete post-change role snapshot as a sorted array of unique role identifiers and uses `[]` when empty, not an added/removed delta or an unordered set. `outboxSequence` is a canonical unsigned base-10 JSON string. `membershipVersion` uses the canonical exact one-tenant map `{tenantId: version}`; its sole value uses that same unsigned-string grammar. This preserves values beyond IEEE-754 exact-integer range and the shared carrier shape across implementations. RFC 8785 preserves string data as supplied; producers perform no Unicode normalization before canonicalization. No closed event field may be omitted, added, or serialized through an alternate grammar. Account computes the digest and consumers recompute and compare it before applying or acknowledging the event. The separate Account-authenticated same-snapshot recipient evidence, including tuple, actual fence, and full checkpoint set, is bound to the exact event ID/digest rather than included in the digest input. +- The sole value in the validated exact one-tenant `membershipVersion` map must be monotonic per `{accountId, tenantId}` and must advance on any role or membership change that can affect gameplay or tenant-safe control-plane authority. A consumer may extract that value only as a process-local arbitrary-precision integer after validating the complete map and exact tenant key; the event, digest, projection, and binding retain the map. `membershipAuthorityGeneration` is a separate authority fence that advances only when `callerBoundAuthorityInvalidated=true`, meaning the change invalidates previously issued caller-bound tenant authority. A non-revoking change must carry `callerBoundAuthorityInvalidated=false`; the separate Account-authenticated same-snapshot source evidence must prove the unchanged opaque generation and complete applicable tuple, actual fence, baseline, and checkpoint set, bound to the exact event ID/digest. Missing or mismatched proof fails closed. Consumers must not substitute `membershipVersion` for the generation or use either field as the other's proof. - Consumers maintain two independent high-water marks per `{accountId, tenantId}`. `membershipVersion` orders membership projection state, and the membership projection payload, including the complete `changedRoleSet` snapshot, changes only when the event's version is newer than the stored membership version. `membershipAuthorityGeneration` is an independent set-if-greater revocation fence. An event with a newer authority generation and an equal or older membership version advances only that separate authority fence and triggers authoritative membership reconciliation; it must not apply its role set, `changedRoleSet`, `gameplayAdmissionAllowed`, or other membership payload over the newer projection and must not downgrade projection state. An event with a newer membership version updates membership state from that event's complete post-change role snapshot even when the authority generation is unchanged, subject to the complete Account evidence check. Only an event that is not newer on either dimension is a duplicate/no-op. -- Consumers maintain `lastAppliedSourceOutboxSequence` per exact `outboxStreamKey` plus bounded retained duplicate evidence using the canonical separate schema `{outboxStreamKey, outboxSequence, eventId, eventDigest, authorityTuple, issuanceFence, membershipBaseline, outboxCheckpoints}` when membership applies. For sequence `0`, permitted only when the Account-owned stream has no committed event, `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` are omitted from the projection, and there is no duplicate-evidence entry; JSON `null`, an empty string, a zero digest, or another sentinel is invalid. For every positive sequence, `lastAppliedSourceEventId`, `lastAppliedSourceEventDigest`, and every applicable duplicate-evidence field are required non-null values in their canonical formats. An event at or below `lastAppliedSourceOutboxSequence` is a no-op only when the complete retained evidence matches or an authoritative Account lookup for the exact `(outboxStreamKey, outboxSequence)` proves the same event identity, complete payload including `membershipLifecycleState` where applicable, `authorityTuple`, `issuanceFence`, `membershipBaseline` where applicable, complete `outboxCheckpoints`, and `eventDigest`; a watermark or event ID/digest pair alone is never duplicate proof. For a new event above the watermark, the next sequence must be contiguous; a higher sequence is a gap only within that same stream, and an unrelated issuer, account, tenant, membership, or grant stream never creates a gap. If older evidence has aged out, the lookup is unavailable, or the same sequence has different authoritative evidence or digest, the consumer quarantines the stream and stops affected admission/reconnect until exact Account reconciliation succeeds. A same-key gap or same-sequence mismatch, including any invalid absent/null representation, stops affected admission/reconnect and requires Account reconciliation of the exact checkpoint before processing resumes; it must never be accepted as an idempotent duplicate. -- An event whose `membershipAuthorityGeneration` is lower than the current consumer or Account value must not apply its payload, even when its `membershipVersion` is newer. The consumer rejects that payload, quarantines the affected stream/scope, and reconciles one complete Account snapshot containing the authority generation, membership map, full `outboxCheckpoints`, and same-snapshot event evidence before resuming; it must not choose the newer membership version or silently preserve the lower-generation event. +- Consumers maintain `lastAppliedSourceOutboxSequence` per exact `outboxStreamKey` plus bounded retained event-identity/digest evidence and the corresponding Account-authenticated source evidence as separate, same-snapshot carriers. For sequence `0`, permitted only when the Account-owned stream has no committed event, `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` are omitted from the projection, and there is no duplicate-evidence entry; JSON `null`, an empty string, a zero digest, or another sentinel is invalid. For every positive sequence, `lastAppliedSourceEventId`, `lastAppliedSourceEventDigest`, and every applicable duplicate-evidence field are required non-null values in their canonical formats. An event at or below `lastAppliedSourceOutboxSequence` is a no-op only when the complete retained closed event and its separately bound source evidence match, or an authoritative Account lookup for the exact `(outboxStreamKey, outboxSequence)` proves the same event identity, complete payload including `membershipLifecycleState` where applicable, source evidence, and `eventDigest`; a watermark or event ID/digest pair alone is never duplicate proof. For a new event above the watermark, the next sequence must be contiguous; a higher sequence is a gap only within that same stream, and an unrelated issuer, account, tenant, membership, or grant stream never creates a gap. If older evidence has aged out, the lookup is unavailable, or the same sequence has different authoritative evidence or digest, the consumer quarantines the stream and stops affected admission/reconnect until exact Account reconciliation succeeds. A same-key gap or same-sequence mismatch, including any invalid absent/null representation, stops affected admission/reconnect and requires Account reconciliation of the exact checkpoint before processing resumes; it must never be accepted as an idempotent duplicate. +- An event whose `membershipAuthorityGeneration` is lower than the current consumer or Account value must not apply its payload, even when its `membershipVersion` is newer. The consumer rejects that payload, quarantines the affected stream/scope, and reconciles one complete Account snapshot containing the separate Account-authenticated authority evidence (including the membership map and full `outboxCheckpoints`) bound to the exact event identity/digest before resuming; it must not choose the newer membership version or silently preserve the lower-generation event. - If Game Session detects a version gap or has no prior version for an active binding, it must reconcile immediately via the authoritative internal membership API before deciding whether the session remains valid. - Account Service owns the version increment rules; other services must not synthesize membership versions locally. - The two high-waters have independent meanings and must be stored independently per `{accountId, tenantId}`: `membershipVersionHighWater` orders the Account membership projection, while `membershipAuthorityGenerationHighWater` is the set-if-greater revocation fence for previously issued caller-bound authority. `lastAppliedSourceOutboxSequence` is a separate exact-stream delivery watermark and is never replaced by either membership high-water. A newer generation with an equal or older membership version is valid ordering, advances the separate revocation fence without applying or downgrading the membership projection payload, and requires authoritative membership reconciliation before affected gameplay is retained or admitted. A newer membership version with an unchanged generation is valid only when the Account snapshot proves that the change did not invalidate previously issued tenant authority; it updates membership state but does not imply revocation. A membership-version advance that removes gameplay authority without the corresponding Account generation evidence, a generation value that regresses relative to the Account snapshot, or any pair assembled from different checkpoints is inconsistent. - On an inconsistent pair, Game Session stops new admission and reconnect/resume for the affected scope and does not choose the larger value, reset either high-water, or substitute one field for the other. It requests one authoritative Account membership snapshot containing both values, `gameplayAdmissionAllowed`, `evaluatedAt`, the applicable authority tuple, and its outbox checkpoint. Only after that atomic snapshot reconciles both high-waters and the membership state may validation resume; unavailable reconciliation remains `AUTH_UNAVAILABLE`, while reachable contradictory or revoked evidence remains denied/revoked. It must retain a newer authority fence even when the membership version was already seen, but must not apply that event's older membership payload or treat a membership-version advance alone as proof of revocation. - Focused proof must show that Account emits the event's `membershipAuthorityGeneration` from the same committed snapshot: advanced when `callerBoundAuthorityInvalidated=true`, or unchanged when that flag is false. Game Session rejects missing or mismatched generation evidence rather than substituting `membershipVersion`. -Target transaction and consumer contract: once implemented, Account commits each security, membership, grant, or billing authority change, the corresponding durable Account-owned authority-generation or grant-version advance, every applicable cutoff and `issuanceFence`, and its monotonic outbox event in one database transaction or composite CAS/fence. Redis and other downstream projections then idempotently reflect the committed authority state. The cutoff workflow does not report enforcement complete until the required projection and consumer convergence succeeds. Game Session consumes the durable events through an idempotent consumer and maintains the canonical bounded active-binding indexes listed below; correctness must not depend on wildcard Redis scans. -The downstream generation projection uses set-if-greater semantics and may not move authority backward. For a membership or authority-generation event, the Account authority-generation commit atomically includes the exact one-tenant `membershipVersion` map, complete applicable `authorityTuple`, `issuanceFence`, full stream-key-ordered `outboxCheckpoints`, and the event payload/digest from that same durable snapshot; a consumer must reject any event assembled from different snapshots. +Target recipient-authority transaction and consumer contract: once implemented, Account commits each recipient security, membership, grant, or billing authority change, the corresponding durable Account-owned authority-generation or grant-version advance, every applicable cutoff and actual `issuanceFence`, and the closed source event/checkpoint plus separate Account-authenticated same-snapshot recipient evidence in one database transaction or composite CAS/fence. That recipient evidence binds the full tuple, actual fence, and complete checkpoint set to the exact event ID/digest; the fields are not added to the closed event or its digest input. Issuer-generation source events and snapshots follow the separate closed schema in ADR 0030 and carry no recipient tuple, fence, or full checkpoint set. Redis and other downstream projections then idempotently reflect the committed authority state. The cutoff workflow does not report enforcement complete until the required projection and consumer convergence succeeds. Game Session consumes the durable events and their separately bound source evidence through an idempotent consumer and maintains the canonical bounded active-binding indexes listed below; correctness must not depend on wildcard Redis scans. +The downstream generation projection uses set-if-greater semantics and may not move authority backward. Each event type has its own closed versioned schema, with separately authenticated same-source evidence where applicable. A membership event carries the exact one-tenant `membershipVersion` map in its closed payload; separate Account-authenticated evidence from the same snapshot binds the applicable `authorityTuple`, actual `issuanceFence`, and full stream-key-ordered `outboxCheckpoints` to that event's exact ID/digest. A consumer rejects evidence assembled from different snapshots or incorrectly included in the event digest. Issuer-generation events use the separate issuer scope, generation/source-version, stream-checkpoint, and positive-sequence event-identity/digest evidence defined by [ADR 0030](./decisions/adr-0030-risk-based-active-session-revocation.md), without recipient tuple, fence, or checkpoint-set fields. For every registry, lease or lease-fence, binding or binding-index, token-identity fence, non-entitlement Account evidence, lease commit, token issuance dependency, outbox/checkpoint delivery, issuer-generation projection, or required Account reconciliation dependency, an unavailable or timed-out dependency returns retryable `AUTH_UNAVAILABLE`. The distinct ADR 0028 entitlement-only path returns `ENTITLEMENT_UNAVAILABLE` when entitlement evaluation alone is unavailable and no eligible same-binding LKG entitlement value supplies that input; it never covers a failed lease, binding, token-identity fence, non-entitlement authority read, lease commit, token issuance dependency, outbox/checkpoint delivery, projection, or reconciliation dependency. Separately, ADR 0037 bounded active-binding continuity may keep an already-admitted connected binding operating only under its prior-positive, unexpired authority-freshness lease and live coordination-health predicate. That continuity does not authorize new admission, reconnect/resume/rebind, scope expansion, lease renewal, token issuance/refresh, or extension or recreation of the lease. A reachable missing, malformed, stale, regressed, expired, or mismatched value is invalid/revoked. No cache, empty projection, Redis presence/absence, or local binding may override that classification. @@ -309,7 +309,7 @@ Security- and billing-related events (for example, account bans, password resets - Advance the applicable `authorityTuple.accountAuthorityGeneration`, `accountSecurityCutoff`, and `issuanceFence`, then project `session:auth:generation:account:` set-if-greater so previously issued tokens become invalid without requiring key scans or timestamp comparisons. Downstream services consume the resulting Account-owned event/projection and must not write the account-generation state themselves. - Emit the committed Account-owned security event; Game Session consumes it idempotently and revokes only its own affected gameplay bindings across tenants so active sockets are kicked and must re-login under the new security conditions. Account does not discover, delete, or write Game Session gameplay keys. - For **tenant-level billing events**, see the subscription-state mapping below and [Subscription Management](./microservices/account-service/subscription-management.md#tenant-availability-and-quota-enforcement) for when revocation is mandatory versus when quotas and warnings apply. -- For **tenant membership changes**, the Account Service is the authoritative source of membership versioning and change events. Each event carries the Account-committed `authorityTuple.membershipAuthorityGeneration` for the exact `{accountId, tenantId}` scope, complete applicable `authorityTuple`, `issuanceFence`, and separate `membershipVersion`; consumers must use the generation as the authority fence, compare both membership fields independently, treat missing or malformed evidence as a contract failure, reconcile same-stream gaps from Account, and revoke gameplay immediately when the caller loses tenant membership or gameplay-admission authority for that tenant. +- For **tenant membership changes**, the Account Service is the authoritative source of membership versioning and change events. The closed event carries the exact `membershipVersion` and declared membership fields; separate Account-authenticated same-snapshot evidence supplies the applicable `authorityTuple` (including `membershipAuthorityGeneration`), actual `issuanceFence`, `membershipBaseline`, and full `outboxCheckpoints`, bound to the event's exact ID/digest. Consumers must use the generation as the authority fence, compare both membership fields independently, treat missing or malformed evidence as a contract failure, reconcile same-stream gaps from Account, and revoke gameplay immediately when the caller loses tenant membership or gameplay-admission authority for that tenant. ### Billing State and Revocation Rules diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index dc2071f006..ee6a583f62 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -83,3 +83,9 @@ Entry format: - Expected pattern: independently observe the committed operation or receipt, capture its fixed coverage fence before own tuple locks, then lock in canonical Account-first order and revalidate exact immutable evidence before checking flush coverage and the original database-time bound. Never force a marker or extend the deadline to make proof pass. - Current status: the SQL and Java ordering correction and idle-primary/stale-snapshot definitions are prepared; physical execution remains required. Assertions must not depend on asynchronous background WAL flushing remaining idle. - Reconsideration trigger: consume corrected exact-head PostgreSQL proof; unrelated concurrent WAL can still conservatively prevent coverage, and unavailable proof remains denied. + +- `2026-10-08`: Heap observation is not a WAL-free durability precondition + - Observation: exact Account CI at `2b19e46fa` still failed five confirmation cases after moving capture before tuple locks. The idle assertion observed a 72-byte advance, but the raw JUnit artifact cannot identify that WAL record. PostgreSQL heap/index reads can perform pruning and emit WAL; successful read-only statements are not evidence that the insertion position stayed unchanged. The earlier EXCEPTION/subtransaction explanation was not established and must not be reported as the cause. + - Expected pattern: establish a fixed SERIALIZABLE snapshot and a database-owned upper fence before heap observation, then prove independent committed visibility within that same snapshot and revalidate immutable evidence under canonical owner locks. Keep original expiry and fail closed on uncovered WAL; do not create markers, force a flush or weaken durability to satisfy a test. + - Current status: the scoped SQL/fixture correction is prepared for consolidated validation. Physical proof remains required; the exact cause of the observed record is unresolved without statement-level WAL evidence. + - Reconsideration trigger: consume corrected exact-head PostgreSQL execution. Global pre-call LSN equality is not a stable assertion under background activity; exact temporal and binding guarantees still need executed owner proof. 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 9a567b49da..8f4472270a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,9 +8,11 @@ This is a non-normative implementation tracker for player access and session. Ca ### Account Admission-Lease Prerequisite -Latest physical evidence supersedes the local-only confirmation evidence below: exact `28a1ef9a53be8c8423f34738d05fe3509a61dc57` [CI run 37709000871](https://github.com/benhook1013/FireMUD/actions/runs/37709000871), on merge `da108e97de9d01688abe3ef4a24ea64b2cf7386c` with exact base `7985e8a6f6354587f5c01649ede3d0cecde9fde2`, executes 1,339 Account cases with seven skips and five failures. All eighteen lease PostgreSQL cases execute: thirteen pass, while five confirmation cases reject the fixture's non-durable primary configuration. The installed Testcontainers PostgreSQL 2.0.5 constructor defaults to `fsync=off`. The corrected lease suite opts into `fsync=on` and `synchronous_commit=on` from container startup and explicitly reads back those settings and primary status; an unsuitable external database is rejected without changing its configuration. This repair preserves the production durability guard and all eighteen existing lease cases, adding one live-settings test. Corrected confirmation success and idle-database WAL coverage remain unproved; passing unrelated storage cases does not establish them. +Latest physical evidence is the manually dispatched exact `2b19e46fa4adb4c3c0c8434f4867cca6d9f86b81` [Account CI run 37712881776](https://github.com/benhook1013/FireMUD/actions/runs/37712881776): 1,355 cases execute, seven skip and seven fail. All twenty-one lease PostgreSQL cases execute, with five confirmation failures; all seven first-JOIN PostgreSQL cases execute, with two fixture failures. The Account job and run identify the exact published head; checkout step logs were unavailable while aggregate CI remained pending at observer handoff. WAL coverage still fails despite the corrected durable fixture: the idle case observes a 72-byte pre-capture advance, whose exact record is not established by the artifact. PostgreSQL heap reads can emit pruning WAL, so observing a row before capture is not a WAL-free ordering guarantee. The JOIN fixture's legacy `player` role prevents its fresh canonical empty global-role source birth; the correction removes that assignment, preserving denial and replay assertions. Five World-client socket mTLS, sixteen Draft-fence PostgreSQL, seven restriction-birth PostgreSQL, sixteen security-operation PostgreSQL and seven source-evidence PostgreSQL cases pass. These executed failures, not the earlier local green checks, govern the current confirmation proof limit. -The corrected durability observer captures its fixed insertion fence after independent committed observation and before its own tuple-lock WAL, then takes Account-first locks and revalidates the complete immutable operation or receipt. Otherwise an idle primary can conservatively fail coverage by waiting for the observer's own uncommitted partial WAL page. Java calls the SQL proof function before its exact locked carrier readback; both remain in the owned writable SERIALIZABLE transaction. New definitions preserve all nineteen prior lease cases and add pre-lock capture/independent idle readback and deterministic stale-snapshot `40001`; concurrent exact retained replay also runs after the original expiry without changing the receipt. Local R55 passes full Account checks, jOOQ generation, formatting, static analysis, integration compilation, boot packaging and documentation checks in 2m37s: 1,170 unit cases and eight non-database integration cases execute without failures/errors, three unit cases skip and all 173 PostgreSQL cases skip. The twenty-one lease PostgreSQL definitions compile but do not execute locally. The automatic [42a2083 CI run](https://github.com/benhook1013/FireMUD/actions/runs/37711528914) selected a module matrix without Account, so it supplies no corrected Account execution proof; a full exact-head manual run is required. Background writer timing is not asserted to remain idle, and unrelated uncovered WAL still denies rather than forcing a flush or extending expiry. Current authority, finalization, installation and activation remain separately gated. +Historical physical failure at `28a1ef9a53be8c8423f34738d05fe3509a61dc57` [CI run 37709000871](https://github.com/benhook1013/FireMUD/actions/runs/37709000871), on merge `da108e97de9d01688abe3ef4a24ea64b2cf7386c` with exact base `7985e8a6f6354587f5c01649ede3d0cecde9fde2`, executes 1,339 Account cases with seven skips and five failures. All eighteen lease PostgreSQL cases execute: thirteen pass, while five confirmation cases reject the fixture's non-durable primary configuration. The installed Testcontainers PostgreSQL 2.0.5 constructor defaults to `fsync=off`. The corrected lease suite opts into `fsync=on` and `synchronous_commit=on` from container startup and explicitly reads back those settings and primary status; an unsuitable external database is rejected without changing its configuration. This repair preserves the production durability guard and all eighteen existing lease cases, adding one live-settings test. Corrected confirmation success and idle-database WAL coverage remain unproved; passing unrelated storage cases does not establish them. + +The corrected observer enforces the SQL-owned writable SERIALIZABLE snapshot and captures the database insertion fence before heap observation. An independently visible committed operation or receipt in that same fixed snapshot proves its COMMIT preceded the fence; own top-level/subtransaction evidence is excluded. Account-first locks and complete immutable revalidation follow. The outer creation function enters the insert guard before heap reads; exact retained replay suppresses insertion and reads the original receipt without new proof or expiry. Java still invokes SQL before its locked carrier readback. All twenty-one definitions remain; stronger in-method cases cover direct unsupported-isolation/read-only calls, own/subtransaction rejection, exact expired replay and fixed-snapshot proof without fragile global-LSN equality. Corrected local R57 passes full Account checks, generation, formatting, static analysis, integration compilation, boot packaging and documentation checks in 2m15s: 1,170 unit and eight non-database integration cases execute without failures/errors, three unit cases skip and all 173 PostgreSQL cases skip. New exact-head PostgreSQL execution of this correction is still required. Earlier R55 also passed local checks but skipped PostgreSQL. The automatic [42a2083 run](https://github.com/benhook1013/FireMUD/actions/runs/37711528914) omitted Account; the actual exact-head manual failure is recorded above. Unrelated uncovered WAL still denies rather than forcing a flush or extending expiry. Current authority, finalization, installation and activation remain separately gated; the [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#admission-lease-confirmation-preparation) owns the algorithm rather than this tracker. The pending-denial extension also checks Account security-state `WAITING` operations and exact `ACCOUNT:` / `GLOBAL_ROLES:` source changes in `WAITING`, independently of the target tenant's lifecycle journal. V91 versions only the matching persisted Account tuple, preserving logical state, counters, events and retained pending evidence. Source-change producers lock sorted, deduplicated Accounts before source and operation locks. New PostgreSQL definitions cover stale snapshots, both READ_COMMITTED lock orders, cross-account and cross-tenant scope, unchanged source/JOIN state, terminal draft changes that cannot clear a separate security operation, and historical committed JOIN replay. Corrected local R53 passes full Account checks, jOOQ generation, formatting, static analysis, integration compilation, boot packaging and documentation validation. Its test reports retain 1,170 executed unit outcomes with three skips and zero failures/errors from R52's unchanged unit boundary; eight non-database integration cases execute and 171 PostgreSQL cases skip without Docker. Flyway sanity passes twelve sets and 169 versioned files. R51 exposed three integration-fixture compilation errors and R52 exposed seven nullable fixture readbacks; bounded corrections preserve the denial assertions and use explicit non-null checks, not suppressions. These additions are negative protection only, not authenticated restriction authorization or a positive admission result; their new physical execution remains required. diff --git a/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql b/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql index ebd0d45bf5..ca70da43ab 100644 --- a/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql +++ b/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql @@ -106,6 +106,9 @@ CREATE FUNCTION account_gameplay_admission_confirmation_guard() RETURNS TRIGGER DECLARE operation account_gameplay_admission_lease_operations%ROWTYPE; locked_operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_commit_confirmations%ROWTYPE; + locked_receipt account_gameplay_admission_commit_confirmations%ROWTYPE; + own_xid TEXT; finalization_status TEXT; insert_fence pg_lsn; flush_fence pg_lsn; @@ -124,6 +127,25 @@ BEGIN RAISE EXCEPTION 'Account admission confirmation proof is database derived' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_db_proof'; END IF; + IF current_setting('transaction_isolation') IS DISTINCT FROM 'serializable' + OR current_setting('transaction_read_only') IS DISTINCT FROM 'off' THEN + RAISE EXCEPTION 'Account admission confirmation writable SERIALIZABLE transaction required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_transaction_required'; + END IF; + IF pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Account admission confirmation durable primary required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_durable_primary'; + END IF; + -- Establish the fixed transaction snapshot before the fence and before any heap read. + -- A subsequently visible independent row committed before this snapshot, hence before + -- this WAL upper bound. Even a SELECT can emit heap-pruning WAL; capture must precede it. + PERFORM pg_current_snapshot(); + own_xid := pg_current_xact_id_if_assigned()::text; + insert_fence := pg_current_wal_insert_lsn(); + IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN + RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; + END IF; SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = NEW.request_id; IF NOT FOUND THEN RAISE EXCEPTION 'Account admission confirmation operation missing' @@ -135,28 +157,12 @@ BEGIN RAISE EXCEPTION 'Account admission confirmation exact committed binding required' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; END IF; - BEGIN - finalization_status := pg_xact_status(operation.finalization_xid::xid8); - EXCEPTION WHEN OTHERS THEN - RAISE EXCEPTION 'Account admission confirmation finalization proof unavailable' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_finalization_unavailable'; - END; - IF finalization_status IS DISTINCT FROM 'committed' THEN + -- The stamp is top-level even when finalization ran in a released subtransaction. + IF operation.finalization_xid = own_xid THEN RAISE EXCEPTION 'Account admission confirmation requires independent finalization commit' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_finalization_independent'; END IF; - IF pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN - RAISE EXCEPTION 'Account admission confirmation durable primary required' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_durable_primary'; - END IF; - -- Independent committed visibility precedes this fixed insert fence; the original COMMIT - -- WAL is therefore covered. Capture BEFORE this proof transaction's tuple locks emit WAL: - -- an idle primary need not flush an uncommitted partial page containing those lock records. - insert_fence := pg_current_wal_insert_lsn(); - IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN - RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; - END IF; + SELECT * INTO receipt FROM account_gameplay_admission_commit_confirmations WHERE request_id = NEW.request_id; PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; IF NOT FOUND THEN RAISE EXCEPTION 'Account admission confirmation owner missing' @@ -168,6 +174,34 @@ BEGIN RAISE EXCEPTION 'Account admission confirmation exact committed binding required' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; END IF; + IF receipt.request_id IS NOT NULL THEN + SELECT * INTO locked_receipt FROM account_gameplay_admission_commit_confirmations + WHERE request_id = NEW.request_id FOR UPDATE; + IF NOT FOUND OR locked_receipt IS DISTINCT FROM receipt + OR receipt.account_uuid IS DISTINCT FROM operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid THEN + RAISE EXCEPTION 'Account admission confirmation immutable binding conflict' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_conflict'; + END IF; + -- Suppress an exact replay INSERT, including after expiry. The caller reads the retained + -- receipt; no new proof, XID, deadline or timing bound replaces its original evidence. + RETURN NULL; + END IF; + BEGIN + finalization_status := pg_xact_status(operation.finalization_xid::xid8); + EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Account admission confirmation finalization proof unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_finalization_unavailable'; + END; + IF finalization_status IS DISTINCT FROM 'committed' THEN + RAISE EXCEPTION 'Account admission confirmation requires independent finalization commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_finalization_independent'; + END IF; -- Account-first locking serializes first receipt creation, and exact locked revalidation -- preserves the independently observed immutable operation. Only the pre-lock fence needs -- coverage; this bounded polling creates no marker, forces no flush and renews no deadline. @@ -214,6 +248,16 @@ DECLARE operation account_gameplay_admission_lease_operations%ROWTYPE; receipt account_gameplay_admission_commit_confirmations%ROWTYPE; BEGIN + -- Enter the guard before either operation/receipt heap read. It owns the snapshot/fence + -- and suppresses exact retained replay without renewing proof. A stale SERIALIZABLE + -- conflict must surface as 40001 rather than a raw uniqueness failure. + INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) + VALUES (requested_request_id, expected_sha, expected_decision) + ON CONFLICT (request_id) DO NOTHING RETURNING * INTO receipt; + IF FOUND THEN + RETURN NEXT receipt; + RETURN; + END IF; SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = requested_request_id; IF NOT FOUND THEN RAISE EXCEPTION 'Account admission confirmation operation missing' @@ -225,19 +269,6 @@ BEGIN RAISE EXCEPTION 'Account admission confirmation exact committed binding required' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; END IF; - SELECT * INTO receipt FROM account_gameplay_admission_commit_confirmations WHERE request_id = requested_request_id; - IF NOT FOUND THEN - -- The INSERT guard owns initial proof observation and capture before any tuple lock. - -- A concurrent stale SERIALIZABLE insertion reports 40001 through ON CONFLICT rather - -- than leaking a raw uniqueness failure. No caller proof or renewed deadline is accepted. - INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) - VALUES (requested_request_id, expected_sha, expected_decision) - ON CONFLICT (request_id) DO NOTHING RETURNING * INTO receipt; - IF FOUND THEN - RETURN NEXT receipt; - RETURN; - END IF; - END IF; -- Exact retained replay may occur after expiry. It locks Account first and revalidates the -- immutable original decision, but neither re-proves nor replaces the receipt's timing bound. PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; @@ -277,10 +308,29 @@ DECLARE receipt account_gameplay_admission_commit_confirmations%ROWTYPE; locked_operation account_gameplay_admission_lease_operations%ROWTYPE; locked_receipt account_gameplay_admission_commit_confirmations%ROWTYPE; + own_xid TEXT; insert_fence pg_lsn; flush_fence pg_lsn; observation INTEGER; BEGIN + IF current_setting('transaction_isolation') IS DISTINCT FROM 'serializable' + OR current_setting('transaction_read_only') IS DISTINCT FROM 'off' THEN + RAISE EXCEPTION 'Account admission confirmation writable SERIALIZABLE transaction required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_transaction_required'; + END IF; + IF pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Account admission confirmation durable primary required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_durable_primary'; + END IF; + -- Fix the snapshot and WAL upper bound before heap reads or assigning our own XID. + -- Independent receipt visibility in that same snapshot covers its prior COMMIT. + PERFORM pg_current_snapshot(); + own_xid := pg_current_xact_id_if_assigned()::text; + insert_fence := pg_current_wal_insert_lsn(); + IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN + RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; + END IF; SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = requested_request_id; IF NOT FOUND THEN RAISE EXCEPTION 'Account admission confirmation operation missing' @@ -303,20 +353,10 @@ BEGIN -- MVCC visibility plus exclusion of our own top-level XID also excludes our subtransactions. -- Historical receipts need not retain pg_xact_status data forever: fresh WAL coverage below -- covers their independently visible original COMMIT without consulting vacuum-pruned status. - IF receipt.confirmation_xid = pg_current_xact_id()::text THEN + IF receipt.confirmation_xid = own_xid THEN RAISE EXCEPTION 'Account admission confirmation requires independent receipt commit' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_receipt_independent'; END IF; - IF pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN - RAISE EXCEPTION 'Account admission confirmation durable primary required' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_durable_primary'; - END IF; - -- Capture after independent receipt visibility, before Account/operation/receipt lock WAL. - insert_fence := pg_current_wal_insert_lsn(); - IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN - RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; - END IF; PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; IF NOT FOUND THEN RAISE EXCEPTION 'Account admission confirmation owner missing' diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index c72bd24077..26d1c805fa 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -783,26 +783,41 @@ void idlePrimaryConfirmationCapturesBeforeLocksAndIndependentlyReadsExactReceipt tx(context, () -> repository.recordCommitted(original, decision)); var unchanged = storageSnapshot(context); - // This fixture is idle: no marker, forced flush or unrelated writer is used to make proof - // succeed. The original finalizer's synchronous COMMIT already covers the pre-lock fence. + String finalizationXid = operation(context, original).get("finalization_xid", String.class); + // No marker, forced flush or unrelated writer is used to make proof succeed. Establish a + // fixed snapshot before the call and prove the original finalizer is independently visible. + // Background WAL may advance, so a pre-call global LSN need not equal the stored fence. var receipt = tx( context, () -> { - String beforeLocks = + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT pg_visible_in_snapshot(?::xid8, pg_current_snapshot()) " + + "AND pg_current_xact_id_if_assigned() IS NULL AS independent", + finalizationXid)) + .get("independent", Boolean.class)) + .isTrue(); + String beforeHeapReads = Objects.requireNonNull( context.dsl().fetchOne("SELECT pg_current_wal_insert_lsn()::text AS lsn")) .get("lsn", String.class); var created = confirm(context, original, decision); - assertThat(created.get("wal_insert_lsn", String.class)).isEqualTo(beforeLocks); assertThat( Objects.requireNonNull( context .dsl() .fetchOne( - "SELECT pg_current_wal_insert_lsn() > ?::pg_lsn AS advanced", - beforeLocks)) - .get("advanced", Boolean.class)) + "SELECT ?::pg_lsn >= ?::pg_lsn " + + "AND ?::pg_lsn >= ?::pg_lsn AS snapshot_fence_covered", + created.get("wal_insert_lsn", String.class), + beforeHeapReads, + created.get("wal_flush_lsn", String.class), + created.get("wal_insert_lsn", String.class))) + .get("snapshot_fence_covered", Boolean.class)) .isTrue(); return created; }); @@ -810,24 +825,17 @@ void idlePrimaryConfirmationCapturesBeforeLocksAndIndependentlyReadsExactReceipt tx( context, () -> { - String beforeLocks = - Objects.requireNonNull( - context.dsl().fetchOne("SELECT pg_current_wal_insert_lsn()::text AS lsn")) - .get("lsn", String.class); - assertThat(readConfirmation(context, original, decision)).isEqualTo(receipt); - // Independent exact readback succeeds with its pre-call fence covered and advances WAL - // through its tuple locks. Background flush progress does not affect this assertion. assertThat( Objects.requireNonNull( context .dsl() .fetchOne( - "SELECT pg_current_wal_insert_lsn() > ?::pg_lsn " - + "AND pg_current_wal_flush_lsn() >= ?::pg_lsn AS pre_call_fence_covered", - beforeLocks, - beforeLocks)) - .get("pre_call_fence_covered", Boolean.class)) + "SELECT pg_visible_in_snapshot(?::xid8, pg_current_snapshot()) " + + "AND pg_current_xact_id_if_assigned() IS NULL AS independent", + receipt.get("confirmation_xid", String.class))) + .get("independent", Boolean.class)) .isTrue(); + assertThat(readConfirmation(context, original, decision)).isEqualTo(receipt); return null; }); assertThat(storageSnapshot(context)).isEqualTo(unchanged); @@ -945,6 +953,17 @@ void sameTransactionAndReleasedSubtransactionCannotConfirmOriginalFinalization() context, () -> confirm(context, original, decision), "requires independent finalization commit"); + assertDeniedInSavepoint( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) VALUES (?, ?, ?)", + requestId(original), + original.sha256(), + decision), + "requires independent finalization commit"); return null; }); } @@ -1028,6 +1047,38 @@ void confirmationRejectsChangedBindingsAndCallerProofAndRemainsImmutable() { .hasMessageContaining("finalization transaction is database stamped"); tx(context, () -> repository.recordCommitted(original, decision)); var unchanged = storageSnapshot(context); + // SQL owns the transaction prerequisite even for callers bypassing the Java owner. + for (int isolation : + List.of( + TransactionDefinition.ISOLATION_READ_COMMITTED, + TransactionDefinition.ISOLATION_REPEATABLE_READ)) { + var unsupported = + new TransactionTemplate(new DataSourceTransactionManager(context.dataSource())); + unsupported.setIsolationLevel(isolation); + for (Supplier action : + List.>of( + () -> confirm(context, original, decision), + () -> readConfirmation(context, original, decision), + () -> + context + .dsl() + .execute( + "INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) VALUES (?, ?, ?)", + request, + original.sha256(), + decision))) { + assertThatThrownBy(() -> unsupported.execute(status -> action.get())) + .hasMessageContaining("writable SERIALIZABLE transaction required"); + } + } + var readOnly = new TransactionTemplate(new DataSourceTransactionManager(context.dataSource())); + readOnly.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> readOnly.execute(status -> readConfirmation(context, original, decision))) + .hasMessageContaining("writable SERIALIZABLE transaction required"); + assertThatThrownBy(() -> readOnly.execute(status -> confirm(context, original, decision))) + .hasMessageContaining("read-only transaction"); assertThatThrownBy( () -> tx( @@ -1112,19 +1163,24 @@ void sameTransactionReceiptReadAndRolledBackConfirmationCannotProveDurability() var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); UUID decision = UUID.randomUUID(); tx(context, () -> repository.recordCommitted(original, decision)); - assertThatThrownBy( - () -> - tx( - context, - () -> { - confirm(context, original, decision); - assertDeniedInSavepoint( - context, - () -> readConfirmation(context, original, decision), - "requires independent receipt commit"); - throw new IllegalStateException("roll back confirmation commit"); - })) - .hasMessageContaining("roll back confirmation commit"); + for (boolean subtransaction : List.of(false, true)) { + assertThatThrownBy( + () -> + tx( + context, + () -> { + if (subtransaction) context.dsl().execute("SAVEPOINT receipt_creation"); + confirm(context, original, decision); + if (subtransaction) + context.dsl().execute("RELEASE SAVEPOINT receipt_creation"); + assertDeniedInSavepoint( + context, + () -> readConfirmation(context, original, decision), + "requires independent receipt commit"); + throw new IllegalStateException("roll back confirmation commit"); + })) + .hasMessageContaining("roll back confirmation commit"); + } assertThat( context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) .isZero(); @@ -1159,8 +1215,20 @@ void concurrentConfirmationsRetainOneOriginalReceiptWithoutAdvancingSources() th .isEqualTo(1); var retained = tx(context, () -> confirm(context, original, decision)); waitPastDeadline(context, original); - // Both duplicates now replay an expired retained receipt. They must never enter the fresh - // INSERT guard, restamp its temporal bound or allocate replacement evidence. + assertThat( + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) VALUES (?, ?, ?) ON CONFLICT (request_id) DO NOTHING", + requestId(original), + original.sha256(), + decision))) + .isZero(); + // Both duplicates enter the INSERT guard but replay the expired retained receipt without + // taking fresh temporal proof, restamping its bound or allocating replacement evidence. try (var executor = Executors.newFixedThreadPool(2)) { var left = executor.submit(duplicate); var right = executor.submit(duplicate); 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 4ada1c1fee..d16909a079 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 @@ -508,7 +508,6 @@ private Account createAccount() { input.setUsername("canonical-join-" + suffix); input.setEmail("canonical-join-" + suffix + "@example.test"); input.setPasswordHash("integration-fixture-hash"); - input.setRole("player"); return inTransaction(() -> accounts.save(input)); } From 109a118f7754fe68e77aab0f09c27c751b733d98 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:37:53 +1300 Subject: [PATCH 16/16] Account: diagnose strict WAL coverage and correct JOIN row snapshots --- .../player-access-and-session.md | 6 ++++- ..._admission_durable_commit_confirmation.sql | 22 +++++++++++++++---- ...anonicalFirstJoinEventIntegrationTest.java | 12 +++++----- 3 files changed, 29 insertions(+), 11 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 8f4472270a..17644c05aa 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,11 @@ This is a non-normative implementation tracker for player access and session. Ca ### Account Admission-Lease Prerequisite -Latest physical evidence is the manually dispatched exact `2b19e46fa4adb4c3c0c8434f4867cca6d9f86b81` [Account CI run 37712881776](https://github.com/benhook1013/FireMUD/actions/runs/37712881776): 1,355 cases execute, seven skip and seven fail. All twenty-one lease PostgreSQL cases execute, with five confirmation failures; all seven first-JOIN PostgreSQL cases execute, with two fixture failures. The Account job and run identify the exact published head; checkout step logs were unavailable while aggregate CI remained pending at observer handoff. WAL coverage still fails despite the corrected durable fixture: the idle case observes a 72-byte pre-capture advance, whose exact record is not established by the artifact. PostgreSQL heap reads can emit pruning WAL, so observing a row before capture is not a WAL-free ordering guarantee. The JOIN fixture's legacy `player` role prevents its fresh canonical empty global-role source birth; the correction removes that assignment, preserving denial and replay assertions. Five World-client socket mTLS, sixteen Draft-fence PostgreSQL, seven restriction-birth PostgreSQL, sixteen security-operation PostgreSQL and seven source-evidence PostgreSQL cases pass. These executed failures, not the earlier local green checks, govern the current confirmation proof limit. +Latest exact `1baaaaa355fe54e7bcd4bbd6ee6d954de776acf1` [Account CI job](https://github.com/benhook1013/FireMUD/actions/runs/37715618727/job/113111358439) fails after physical execution: 1,170 unit and 185 integration cases execute, three unit and four Redis cases skip, and five integration cases fail without errors. All 21 lease PostgreSQL cases execute (17 pass, four fail); all seven first-JOIN PostgreSQL cases execute (six pass, one fails). Checkout merge `ee8db660b9d13c5c3609317ec43ef5d72e901b6d` has the exact base/head parents and source tree. Three lease failures establish creation-guard WAL coverage timeout; the Java-owner failure exposes only generic `UNAVAILABLE`, so its failing phase is not established. The fixed snapshot/pre-heap observer ordering remains unchanged. PostgreSQL's WAL writer normally covers complete pages, not every later partial-page record: a fixed global fence can remain conservatively uncovered, and longer waits or retries alone do not prove coverage. The offending records' provenance is unproved; original physical COMMIT-before-expiry remains a gate, not a logical timestamp substitute. + +The bounded continuation preserves every proof predicate and deadline, adds internal SQL timeout diagnostics for capture/snapshot/XID/flush/time and failure phase, and leaves Java's cause/description/trailer redaction unchanged. The attempted cause retention failed the existing redaction unit test in R59 and was removed; that safety assertion is not weakened. The JOIN fixture's complete no-mutation snapshots now query the actual numeric Account owner row plus canonical `tenant_uuid`, rather than nonexistent membership `account_uuid`; the separately read Account UUID and all assertions remain. Consolidated local validation and new exact-head PostgreSQL execution of these corrections are pending. This diagnostic checkpoint does not claim successful confirmation, current restriction authority or admission. + +Earlier physical evidence is the manually dispatched exact `2b19e46fa4adb4c3c0c8434f4867cca6d9f86b81` [Account CI run 37712881776](https://github.com/benhook1013/FireMUD/actions/runs/37712881776): 1,355 cases execute, seven skip and seven fail. All twenty-one lease PostgreSQL cases execute, with five confirmation failures; all seven first-JOIN PostgreSQL cases execute, with two fixture failures. The Account job and run identify the exact published head; checkout step logs were unavailable while aggregate CI remained pending at observer handoff. WAL coverage still fails despite the corrected durable fixture: the idle case observes a 72-byte pre-capture advance, whose exact record is not established by the artifact. PostgreSQL heap reads can emit pruning WAL, so observing a row before capture is not a WAL-free ordering guarantee. The JOIN fixture's legacy `player` role prevents its fresh canonical empty global-role source birth; the correction removes that assignment, preserving denial and replay assertions. Five World-client socket mTLS, sixteen Draft-fence PostgreSQL, seven restriction-birth PostgreSQL, sixteen security-operation PostgreSQL and seven source-evidence PostgreSQL cases pass. These executed failures, not the earlier local green checks, govern the current confirmation proof limit. Historical physical failure at `28a1ef9a53be8c8423f34738d05fe3509a61dc57` [CI run 37709000871](https://github.com/benhook1013/FireMUD/actions/runs/37709000871), on merge `da108e97de9d01688abe3ef4a24ea64b2cf7386c` with exact base `7985e8a6f6354587f5c01649ede3d0cecde9fde2`, executes 1,339 Account cases with seven skips and five failures. All eighteen lease PostgreSQL cases execute: thirteen pass, while five confirmation cases reject the fixture's non-durable primary configuration. The installed Testcontainers PostgreSQL 2.0.5 constructor defaults to `fsync=off`. The corrected lease suite opts into `fsync=on` and `synchronous_commit=on` from container startup and explicitly reads back those settings and primary status; an unsuitable external database is rejected without changing its configuration. This repair preserves the production durability guard and all eighteen existing lease cases, adding one live-settings test. Corrected confirmation success and idle-database WAL coverage remain unproved; passing unrelated storage cases does not establish them. diff --git a/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql b/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql index ca70da43ab..579800746a 100644 --- a/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql +++ b/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql @@ -110,7 +110,9 @@ DECLARE locked_receipt account_gameplay_admission_commit_confirmations%ROWTYPE; own_xid TEXT; finalization_status TEXT; + fixed_snapshot pg_snapshot; insert_fence pg_lsn; + initial_flush_fence pg_lsn; flush_fence pg_lsn; observed_before_ms BIGINT; observation INTEGER; @@ -139,9 +141,10 @@ BEGIN -- Establish the fixed transaction snapshot before the fence and before any heap read. -- A subsequently visible independent row committed before this snapshot, hence before -- this WAL upper bound. Even a SELECT can emit heap-pruning WAL; capture must precede it. - PERFORM pg_current_snapshot(); + fixed_snapshot := pg_current_snapshot(); own_xid := pg_current_xact_id_if_assigned()::text; insert_fence := pg_current_wal_insert_lsn(); + initial_flush_fence := pg_current_wal_flush_lsn(); IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; @@ -217,7 +220,10 @@ BEGIN EXIT WHEN flush_fence IS NOT NULL AND flush_fence >= insert_fence; IF observation = 50 THEN RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage', + DETAIL = format('phase=create snapshot=%s own_xid_if_assigned=%s finalization_xid=%s receipt_xid=%s insert_fence=%s initial_flush=%s final_flush=%s observed_db_ms=%s unchanged_expiry_ms=%s', + fixed_snapshot, own_xid, operation.finalization_xid, receipt.confirmation_xid, + insert_fence, initial_flush_fence, flush_fence, observed_before_ms, operation.expires_at_ms); END IF; PERFORM pg_sleep(0.01); END LOOP; @@ -309,8 +315,11 @@ DECLARE locked_operation account_gameplay_admission_lease_operations%ROWTYPE; locked_receipt account_gameplay_admission_commit_confirmations%ROWTYPE; own_xid TEXT; + fixed_snapshot pg_snapshot; insert_fence pg_lsn; + initial_flush_fence pg_lsn; flush_fence pg_lsn; + observed_before_ms BIGINT; observation INTEGER; BEGIN IF current_setting('transaction_isolation') IS DISTINCT FROM 'serializable' @@ -324,9 +333,10 @@ BEGIN END IF; -- Fix the snapshot and WAL upper bound before heap reads or assigning our own XID. -- Independent receipt visibility in that same snapshot covers its prior COMMIT. - PERFORM pg_current_snapshot(); + fixed_snapshot := pg_current_snapshot(); own_xid := pg_current_xact_id_if_assigned()::text; insert_fence := pg_current_wal_insert_lsn(); + initial_flush_fence := pg_current_wal_flush_lsn(); IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; @@ -378,8 +388,12 @@ BEGIN flush_fence := pg_current_wal_flush_lsn(); EXIT WHEN flush_fence IS NOT NULL AND flush_fence >= insert_fence; IF observation = 50 THEN + observed_before_ms := ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint; RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' - USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage', + DETAIL = format('phase=receipt-read snapshot=%s own_xid_if_assigned=%s finalization_xid=%s receipt_xid=%s insert_fence=%s initial_flush=%s final_flush=%s observed_db_ms=%s unchanged_expiry_ms=%s', + fixed_snapshot, own_xid, operation.finalization_xid, receipt.confirmation_xid, + insert_fence, initial_flush_fence, flush_fence, observed_before_ms, operation.expires_at_ms); END IF; PERFORM pg_sleep(0.01); END LOOP; 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 d16909a079..3fedc05571 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 @@ -786,8 +786,8 @@ private JoinOwnerSnapshot joinOwnerSnapshot() { rowSetJson( dsl, "account_tenant_membership", - "account_uuid = ? AND tenant_uuid = ?", - accountUuid, + "account_id = ? AND tenant_uuid = ?", + account.getId(), tenantUuid), rowSetJson( dsl, @@ -799,15 +799,15 @@ private JoinOwnerSnapshot joinOwnerSnapshot() { dsl, "account_tenant_membership_role_snapshots", "membership_id IN (SELECT id FROM account_tenant_membership " - + "WHERE account_uuid = ? AND tenant_uuid = ?)", - accountUuid, + + "WHERE account_id = ? AND tenant_uuid = ?)", + account.getId(), tenantUuid), rowSetJson( dsl, "account_tenant_membership_role_snapshot_roles", "membership_id IN (SELECT id FROM account_tenant_membership " - + "WHERE account_uuid = ? AND tenant_uuid = ?)", - accountUuid, + + "WHERE account_id = ? AND tenant_uuid = ?)", + account.getId(), tenantUuid), rowSetJson( dsl, "account_authority_outbox_events", "outbox_stream_key = ?", accountStream),