From 6ac431ad8c243e4a0f2c416942623aee08d82f7c Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Wed, 7 Oct 2026 11:59:03 +1300
Subject: [PATCH 01/19] feat(account): prepare canonical request-bound gameplay
login owner
---
.../account-service/runtime-and-data.md | 2 +
.../player-access-and-session.md | 6 +
services/account-service/build.gradle.kts | 3 +
.../dto/AccountAuthEvidenceBundle.java | 808 ++++++
.../AccountGameplayTokenIdentityFence.java | 80 +
.../dto/CanonicalGameplayLoginRequest.java | 30 +
.../dto/GameplayCredentialSourceContext.java | 30 +
.../dto/InitialGameplayLoginResult.java | 259 ++
.../AccountAuthEvidenceBundleRepository.java | 683 +++++
...countGameplayCredentialRequestBinding.java | 29 +
...tGameplayDelegationIssuanceRepository.java | 2504 +++++++++++++++++
...ountGameplayDelegationPendingIdentity.java | 2 +
...yDelegationResponseEnvelopeRepository.java | 1224 ++++++++
...tGameplayTokenIdentityFenceRepository.java | 243 ++
...ountGenerationProjectionRedisContract.java | 110 +
...tionProjectionRedisScriptContribution.java | 43 +
...rrentGenerationProjectionRedisSupport.java | 183 ++
.../AccountGameplayCanonicalLoginOwner.java | 272 ++
...eplayCredentialRequestDigestKeySource.java | 49 +
...ountGameplayCredentialRequestDigester.java | 100 +
...GameplayDelegationAuthorityProjection.java | 772 +++++
...eplayDelegationCommittedIssuanceOwner.java | 455 +++
...meplayDelegationIssuanceCommitService.java | 436 +++
.../AccountGameplayDelegationRedisClient.java | 1503 ++++++++++
...playDelegationRedisScriptContribution.java | 67 +
...playDelegationResponseEnvelopeService.java | 36 +
...meplayDelegationResponseRecoveryOwner.java | 113 +
.../AccountGameplayDelegationSigner.java | 1302 +++++++++
...ccountGameplayDelegationTokenRegistry.java | 236 ++
.../AccountResponseEnvelopeCryptography.java | 403 +++
.../AccountResponseEnvelopeKeyring.java | 291 ++
...ntSelectedGameplayAuthorityProjection.java | 226 ++
...on.redis.contracts.RedisScriptContribution | 2 +
...eplay_login_credential_request_binding.sql | 87 +
.../account_generation_projection_cas.lua | 54 +
...-session-delegation-activate-committed.lua | 62 +
...e-session-delegation-authority-project.lua | 127 +
...me-session-delegation-pending-register.lua | 39 +
...session-delegation-activate-committed.json | 33 +
...n-delegation-authority-project-issuer.json | 29 +
...e-session-delegation-pending-register.json | 28 +
.../account-generation-projection-cas.json | 27 +
...cted-membership-generation-projection.json | 15 +
...selected-tenant-generation-projection.json | 15 +
...denceBundlePersistenceIntegrationTest.java | 362 +++
...ionIssuancePersistenceIntegrationTest.java | 2084 ++++++++++++++
...nseEnvelopePersistenceIntegrationTest.java | 570 ++++
...nseRecoveryPersistenceIntegrationTest.java | 513 ++++
...GameplayDelegationCommitSignerFixture.java | 511 ++++
...ameplayDelegationRedisIntegrationTest.java | 1778 ++++++++++++
.../dto/AccountAuthEvidenceBundleTest.java | 371 +++
.../dto/InitialGameplayLoginResultTest.java | 183 ++
...countAuthEvidenceBundleRepositoryTest.java | 159 ++
...eplayDelegationIssuanceRepositoryTest.java | 869 ++++++
...GameplayDelegationPendingIdentityTest.java | 18 +-
...egationResponseEnvelopeRepositoryTest.java | 981 +++++++
...eplayTokenIdentityFenceRepositoryTest.java | 291 ++
...GenerationProjectionRedisContractTest.java | 110 +
...ccountGameplayCanonicalLoginOwnerTest.java | 556 ++++
...GameplayCredentialRequestDigesterTest.java | 188 ++
...playDelegationAuthorityProjectionTest.java | 696 +++++
...yDelegationCommittedIssuanceOwnerTest.java | 265 ++
...ayDelegationIssuanceCommitServiceTest.java | 154 +
...ountGameplayDelegationRedisClientTest.java | 848 ++++++
...DelegationResponseEnvelopeServiceTest.java | 54 +
...ayDelegationResponseRecoveryOwnerTest.java | 229 ++
.../AccountGameplayDelegationSignerTest.java | 1406 +++++++++
...layDelegationSignerTestFixtureFactory.java | 47 +
...ntGameplayDelegationTokenRegistryTest.java | 471 ++++
.../AccountMountedJwtSignerBundleTest.java | 4 +
...countResponseEnvelopeCryptographyTest.java | 358 +++
.../AccountResponseEnvelopeKeyringTest.java | 159 ++
...lectedGameplayAuthorityProjectionTest.java | 217 ++
...meplayCredentialRequestBindingFixture.java | 11 +
74 files changed, 27480 insertions(+), 1 deletion(-)
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundle.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalGameplayLoginRequest.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/GameplayCredentialSourceContext.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResult.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBinding.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContract.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisScriptContribution.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CurrentGenerationProjectionRedisSupport.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigestKeySource.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigester.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitService.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeService.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwner.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptography.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyring.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjection.java
create mode 100644 services/account-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution
create mode 100644 services/account-service/src/main/resources/db/migration/V81__account_gameplay_login_credential_request_binding.sql
create mode 100644 services/account-service/src/main/resources/redis/account_generation_projection_cas.lua
create mode 100644 services/account-service/src/main/resources/redis/lua/account-game-session-delegation-activate-committed.lua
create mode 100644 services/account-service/src/main/resources/redis/lua/account-game-session-delegation-authority-project.lua
create mode 100644 services/account-service/src/main/resources/redis/lua/account-game-session-delegation-pending-register.lua
create mode 100644 services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-activate-committed.json
create mode 100644 services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-authority-project-issuer.json
create mode 100644 services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-pending-register.json
create mode 100644 services/account-service/src/main/resources/redis/scripts/account-generation-projection-cas.json
create mode 100644 services/account-service/src/main/resources/redis/scripts/account-selected-membership-generation-projection.json
create mode 100644 services/account-service/src/main/resources/redis/scripts/account-selected-tenant-generation-projection.json
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopePersistenceIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResultTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepositoryTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepositoryTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContractTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigesterTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwnerTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitServiceTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeServiceTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwnerTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTestFixtureFactory.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistryTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java
create mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBindingFixture.java
diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md
index 8c348ad475..6156cb1dee 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 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).
The source-only tenant-authority foundation adds Account-local non-paid entitlement storage, its immutable billing outbox, and typed tenant-authority source/current-checkpoint owners. It imports no public provisioning facade, operational activation, credential release, or gameplay admission. Physical PostgreSQL and runtime proof remain pending; see the [tenant-authority source foundation status](../../../project-management/implementation-tracking/player-access-and-session.md#account-tenant-authority-source-foundation).
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 3c726047e5..ec63f76525 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,12 @@ This is a non-normative implementation tracker for player access and session. Ca
## Current Status
+### Credential-Bound Account LOGIN Owner
+
+The source-only 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).
+
+The recovered result carries the original verified immutable evidence bundle alongside the private credential: Account and token identity, issuance times and fence, authority tuple, ordered stream/sequence checkpoints, and separately identified positive source-event evidence. None of this metadata creates tenant membership or gameplay admission. Independent compilation and focused proof for this extracted cut are pending. Its PostgreSQL and Redis definitions are not local execution evidence; the canonical-owner PostgreSQL fixture uses an explicitly labeled deterministic credential verifier, not production password or OTP-verification proof. The Account gRPC facade, trusted Game Session socket-context/attempt producer, protected key provisioning, runtime composition and fresh-image LOGIN → PLAY → LOOK proof are not activated by this cut; the current receiver remains fail-closed. `AA-2.1` remains partial.
+
Account's persisted UUID backs registration REST/gRPC output and the Account component of its existing Account/profile-local and legacy tenant exports. The canonical mapper rejects missing, nil, unprovenanced, or source-row-mismatched identity; registration audit uses the exact same UUID. The Account-local UUID-to-row resolver remains within Account. The current candidate extends UUID identity through Account authentication, bootstrap, and profile producers and through the carrier paths described below; tenant identity fields and unrelated numeric-only consumers remain incomplete. `GrpcClientAuth` already canonicalizes UUID identity; the shared direct Account-claim reader is `SessionContext.currentAccountUuidOrNull`, now used by Logging & Admin actor attribution and Automation Scripting dry-run principal keys. Social & Groups current-account authorization and Game Session's numeric control-plane owner authorization still compare numeric identifiers. Social's persisted relationship subjects currently have no trusted Account UUID mapping, so cross-account Account profile/presence calls remain a separate unresolved boundary. The focused PostgreSQL migration and repository cases are present but were skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no deployed/fresh-runtime or global downstream migration proof. The local export remains partial Account/profile data, not a full portable export. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md).
The Account source-currentness and first-JOIN persistence stage adds V40 to the inherited V30–V39 authority-storage and retention-safety foundation. Newly repository-created Accounts and genuinely new issuers receive Account-owner-proven sequence-zero source baselines; retained rows are not backfilled. Exact security-relevant Account updates couple source generation, issuance fence, canonical event, and current readback in the owner transaction. The owner-local first-JOIN coordinator retains membership, pair/event, audit, and terminal-operation evidence. The inherited storage stage reports 493 unit tests and 13 targeted physical PostgreSQL cases across separate earlier runs, with 42 integration skips in its no-fixture run. These are persistence-preparation facts: they do not prove the cross-service target-through-commit gate or alter tracked PLAY/Smoke status, and the stage itself does not enable signer provisioning, LOGIN, PLAY, or activation.
diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts
index 441e0c6a66..6121a39f0b 100644
--- a/services/account-service/build.gradle.kts
+++ b/services/account-service/build.gradle.kts
@@ -2,6 +2,7 @@
apply(from = "${rootDir}/gradle/proto-convention.gradle")
plugins {
+ `java-test-fixtures`
id("net.firedevops.firemud.secured-stateful-service-conventions")
id("net.firedevops.firemud.aop-conventions")
id("net.firedevops.firemud.jooq-conventions")
@@ -17,4 +18,6 @@ dependencies {
implementation(libs.spring.boot.starter.mail)
implementation(libs.argon2)
implementation(libs.stripe.java)
+ testImplementation(testFixtures(project(":account-service")))
+ integrationTestImplementation(testFixtures(project(":account-service")))
}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundle.java
new file mode 100644
index 0000000000..54188382cf
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundle.java
@@ -0,0 +1,808 @@
+package net.firedevops.firemud.accountservice.dto;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.core.type.TypeReference;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Closed canonical Account-owned {@code account-auth-evidence-bundle/v1} value for the explicitly
+ * non-tenant Game Session-to-Account delegation.
+ *
+ *
This codec validates shape and canonical bytes only. It does not establish that owner source
+ * rows, event history, cutoff applicability, or the caller are authentic/current. The DTO itself is
+ * never proof; the Account repository must derive and persist it only from locked owner readback.
+ */
+public final class AccountAuthEvidenceBundle {
+ public static final String SCHEMA = "account-auth-evidence-bundle/v1";
+ // The existing Account response-envelope AEAD binding accepts at most 8 KiB for this value.
+ public static final int MAX_CANONICAL_BYTES = 8 * 1024;
+
+ private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}");
+ private static final Pattern EVENT_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}");
+ private static final Pattern UUID_TEXT =
+ Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}");
+ private static final Pattern V4_UUID_TEXT =
+ Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}");
+ private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}");
+ private static final Pattern NONNEGATIVE_DECIMAL = Pattern.compile("0|[1-9][0-9]{0,18}");
+ private static final Pattern POSITIVE_XID8 = Pattern.compile("[1-9][0-9]{0,19}");
+ private static final Pattern WORKLOAD =
+ Pattern.compile(
+ "^spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/game-session-service$");
+
+ private static final Set ROOT_FIELDS =
+ Set.of(
+ "schema",
+ "bundleRef",
+ "snapshotIdentity",
+ "evaluationIdentity",
+ "issuer",
+ "profile",
+ "audience",
+ "scope",
+ "operation",
+ "tokenIdentity",
+ "authorityTuple",
+ "issuanceFence",
+ "membershipVersion",
+ "authoritySourceVersions",
+ "accountIdentitySource",
+ "outboxCheckpoints");
+ private static final Set BUNDLE_REF_FIELDS =
+ Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization");
+ private static final Set SCOPE_FIELDS = Set.of("kind", "accountId", "tenantIds");
+ private static final Set OPERATION_FIELDS =
+ Set.of(
+ "operationId",
+ "requestId",
+ "requestDigest",
+ "callerWorkload",
+ "callerContextId",
+ "accountId");
+ private static final Set TOKEN_IDENTITY_FIELDS =
+ Set.of("jti", "tokenGeneration", "iat", "nbf", "exp");
+ private static final Set AUTHORITY_TUPLE_FIELDS =
+ Set.of(
+ "issuerAuthGeneration",
+ "accountAuthorityGeneration",
+ "tenantAuthorityGeneration",
+ "membershipAuthorityGeneration",
+ "privateRealmGrantVersions");
+ private static final Set OPTIONAL_AUTHORITY_TUPLE_FIELDS =
+ Set.of("accountSecurityCutoff");
+ private static final Set AUTHORITY_SOURCE_VERSION_FIELDS =
+ Set.of("issuerSourceVersion", "accountSourceVersion", "issuanceFenceSourceVersion");
+ private static final Set ACCOUNT_IDENTITY_FIELDS =
+ Set.of("sourceRowId", "provenance", "sourceNumericId");
+ private static final Set OUTBOX_CHECKPOINT_FIELDS =
+ Set.of("outboxStreamKey", "outboxSequence", "sourceEventId", "sourceEventDigest");
+ private static final Set ZERO_OUTBOX_CHECKPOINT_FIELDS =
+ Set.of("outboxStreamKey", "outboxSequence");
+ private static final Set ACCOUNT_SECURITY_CUTOFF_FIELDS =
+ Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence");
+ private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER;
+ private static final String PROFILE = GameSessionAccountDelegationProfile.PROFILE;
+ private static final String AUDIENCE = GameSessionAccountDelegationProfile.AUDIENCE;
+ private static final JsonMapper JSON =
+ JsonMapper.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .build();
+
+ private final Map fields;
+ private final byte[] canonicalBytes;
+
+ private AccountAuthEvidenceBundle(Map fields, byte[] canonicalBytes) {
+ this.fields = immutableMap(fields);
+ this.canonicalBytes = canonicalBytes.clone();
+ }
+
+ /**
+ * Encodes the supplied closed value. This factory is not an authenticity boundary; production
+ * persistence must derive the values from locked owner readback and independently compare all
+ * source rows and event payloads.
+ */
+ public static AccountAuthEvidenceBundle fromOwnerEvaluation(OwnerEvaluation evaluation) {
+ Objects.requireNonNull(evaluation, "Account owner evaluation is required");
+ Map fields = fields(evaluation);
+ validateFields(fields);
+ return canonicalValue(fields);
+ }
+
+ /** Strictly parses the exact closed canonical bundle encoding. */
+ public static AccountAuthEvidenceBundle parseCanonical(byte[] value) {
+ if (value == null || value.length == 0 || value.length > MAX_CANONICAL_BYTES) {
+ throw invalid("Account auth-evidence bundle is absent or exceeds its byte bound");
+ }
+ String text = strictUtf8(value);
+ final Map parsed;
+ try {
+ parsed = JSON.readValue(text, new TypeReference<>() {});
+ } catch (RuntimeException ex) {
+ throw invalid("Account auth-evidence bundle JSON is malformed");
+ }
+ validateFields(parsed);
+ byte[] canonical = canonicalize(text);
+ if (!Arrays.equals(value, canonical)) {
+ throw invalid("Account auth-evidence bundle bytes are not canonical");
+ }
+ return new AccountAuthEvidenceBundle(parsed, canonical);
+ }
+
+ public byte[] canonicalBytes() {
+ return canonicalBytes.clone();
+ }
+
+ /** Lowercase SHA-256 digest of these exact canonical bytes. */
+ public String canonicalSha256() {
+ try {
+ return java.util.HexFormat.of()
+ .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(canonicalBytes));
+ } catch (java.security.NoSuchAlgorithmException ex) {
+ throw new IllegalStateException("SHA-256 is unavailable");
+ }
+ }
+
+ public Map fields() {
+ return immutableMap(fields);
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ return this == other
+ || other instanceof AccountAuthEvidenceBundle bundle
+ && Arrays.equals(canonicalBytes, bundle.canonicalBytes);
+ }
+
+ @Override
+ public int hashCode() {
+ return Arrays.hashCode(canonicalBytes);
+ }
+
+ @Override
+ public String toString() {
+ return "AccountAuthEvidenceBundle[redacted]";
+ }
+
+ private static Map fields(OwnerEvaluation evaluation) {
+ Map root = new LinkedHashMap<>();
+ root.put("schema", SCHEMA);
+ Map ref = new LinkedHashMap<>();
+ ref.put("bundleVersion", evaluation.bundleReference().bundleVersion());
+ ref.put("sourceVersion", evaluation.bundleReference().sourceVersion());
+ ref.put("sourceFence", evaluation.bundleReference().sourceFence());
+ ref.put("linearization", evaluation.bundleReference().linearization());
+ root.put("bundleRef", ref);
+ root.put("snapshotIdentity", evaluation.snapshotIdentity());
+ root.put("evaluationIdentity", evaluation.evaluationIdentity());
+ root.put("issuer", ISSUER);
+ root.put("profile", PROFILE);
+ root.put("audience", AUDIENCE);
+
+ Map scope = new LinkedHashMap<>();
+ scope.put("kind", "account");
+ scope.put("accountId", evaluation.accountId().toString());
+ scope.put("tenantIds", List.of());
+ root.put("scope", scope);
+
+ OperationIdentity operation = evaluation.operation();
+ Map operationFields = new LinkedHashMap<>();
+ operationFields.put("operationId", operation.operationId().toString());
+ operationFields.put("requestId", operation.requestId().toString());
+ operationFields.put("requestDigest", operation.requestDigest());
+ operationFields.put("callerWorkload", operation.callerWorkload());
+ operationFields.put("callerContextId", operation.callerContextId().toString());
+ operationFields.put("accountId", operation.accountId().toString());
+ root.put("operation", operationFields);
+
+ TokenIdentity token = evaluation.token();
+ Map tokenFields = new LinkedHashMap<>();
+ tokenFields.put("jti", token.jti().toString());
+ tokenFields.put("tokenGeneration", Long.toString(token.tokenGeneration()));
+ tokenFields.put("iat", token.issuedAtEpochSecond());
+ tokenFields.put("nbf", token.notBeforeEpochSecond());
+ tokenFields.put("exp", token.expiresAtEpochSecond());
+ root.put("tokenIdentity", tokenFields);
+
+ root.put("authorityTuple", deepCopyMap(evaluation.authorityTuple()));
+ root.put("issuanceFence", decimal(evaluation.issuanceFence()));
+ root.put("membershipVersion", Map.of());
+
+ AuthoritySourceVersions sourceVersions = evaluation.authoritySourceVersions();
+ Map versions = new LinkedHashMap<>();
+ versions.put("issuerSourceVersion", decimal(sourceVersions.issuerSourceVersion()));
+ versions.put("accountSourceVersion", decimal(sourceVersions.accountSourceVersion()));
+ versions.put(
+ "issuanceFenceSourceVersion", decimal(sourceVersions.issuanceFenceSourceVersion()));
+ root.put("authoritySourceVersions", versions);
+
+ AccountIdentitySource accountSource = evaluation.accountIdentitySource();
+ Map accountIdentity = new LinkedHashMap<>();
+ accountIdentity.put("sourceRowId", decimal(accountSource.sourceRowId()));
+ accountIdentity.put("provenance", accountSource.provenance().name());
+ accountIdentity.put("sourceNumericId", decimal(accountSource.sourceNumericId()));
+ root.put("accountIdentitySource", accountIdentity);
+
+ List