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