diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bf376f34e4..3bb43fe4e5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -977,6 +977,16 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepositoryIntegrationTest#exhaustedSequenceRejectsAppendWithoutChangingEventCheckpointOrCallerSentinel()' \ account-service + - name: 🔎 Verify Account committed connect source readback proof + if: ${{ matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#readsExactCommittedOriginalSourceAndLostResultWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline()' \ + account-service + - name: 🔎 Verify Game Session PostgreSQL proof case if: ${{ matrix.module == 'game-session-service' }} run: | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 9bbd75cbd6..5a782484e1 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -28,6 +28,8 @@ The live runtime membership response carries `accountId`, `tenantId`, `membershi The latest local Unit 1B source checkpoint also rejects both cached idempotent replay and freshly constructed success when the complete selected-target authority evidence is unavailable. This is a fail-closed guard, not a complete Account-signed `gameplay-connect` producer, durable issuance proof, or activation of the target `IssueConnectToken` RPC; end-to-end source evidence and consumer proof remain open. +The next unwired Account component reads an original successful V35 connect-issuance operation and its exact purpose-bound encrypted response envelope under the Account row fence. Its local successful-envelope payload is the strict UTF-8 compact Account JWT, not a reconstructed token or a second credential. It verifies the independently signed Gateway context, the exact Game Session workload identity, Account UUID provenance and approved retained tenant mapping, the stored token hash and identity, the original Account signature/profile, and complete original source/context correspondence. It rechecks the unchanged source and context deadlines after any fence wait. Its immutable result is original-source evidence only: stored authority/postcondition digest binding is not proof of current authority, registry readiness, or admission. This component is not registered as a runtime credential producer or RPC handler; fresh tenant handoff, complete Account-authenticated evidence, current-authority and registry consumption, protected key delivery, and end-to-end exchange remain separate activation gates. Focused proof status is recorded in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md). + The current `application.yml` and `application-prod.yml` no longer classify `GetTenantMembershipForRuntime` or `GetTenantEntitlementsForRuntime` as gRPC public methods. The membership request now carries typed `PlayerExecutionContext`, and Game Session sends that typed context; Account's handler still denies before producer/data access with `FAILED_PRECONDITION`. The held-back candidate producer/consumer path remains incomplete, so this typed request is not a working admission path or proof of the target membership/entitlement snapshot. The entitlement and realm-grant reads retain their local request shapes and must likewise remain denied until their exact caller/target contracts are carried and verified. An unwired Account membership-snapshot reader now forms an exact one-tenant version map, a complete ordered four-stream checkpoint set, and separate positive membership source-event evidence only from a fenced local transaction. Its issuer, account, and tenant streams can presently prove sequence zero only while their durable generation and source-version baselines remain at one and no committed outbox head exists; advanced upstream history fails closed until its source-event proof is implemented. A never-joined pair's positive version/generation baseline and absence history are read under the same fence; a changed account-local issuance fence is preserved. This reader is not the gRPC response, does not authenticate the runtime caller, and does not enable the denied method or Game Session admission. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 3cc7dad3f4..e111cd6cb8 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -164,3 +164,8 @@ Entry format: - Context: Account counter-exhaustion tests belong to #2876, whose test-result inspector is diagnostic-only; the strict required-suite/case interface exists only in its later descendant. - Observation: inspection before publication caught an unsupported strict CI step in the older ancestor. The uncommitted step was removed and the required execution gate placed in #2911, preserving source-test ownership without copying future tooling into the ancestor. Local PostgreSQL skips remain explicitly unproved. - Expected pattern: verify a workflow command against that exact branch's tooling version, not the latest tail; gate composed runtime proof where the required tool exists, then keep owning-PR and composed-descendant proof distinct. + +- `2026-10-01`: Observe the earliest actual transaction in PostgreSQL contention proof + - Context: the complete Account snapshot/first-JOIN test held the Account row `FOR UPDATE` and waited for JOIN's explicit Account-lock spy. JOIN first inserts its PENDING intent, whose foreign-key check can already wait on that same row. + - Observation: exact CI timed out at the later spy, not at a source invariant. Instrumenting the actual intent-insert backend before the real insert retained the exact `pg_blocking_pids` correlation and complete before/after DTO assertions; corrected CI `36778631119` executed the race once successfully. Worker exceptions are surfaced rather than hidden behind a latch timeout. + - Expected pattern: trace earlier foreign-key and deferred-trigger work before selecting a concurrency signal; prove the exact blocked backend/owner relation and do not fix a misplaced signal by extending timeouts or changing production transaction order. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 0bb07841a4..8b057933b3 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -29,7 +29,7 @@ The preserved 5B implementation work was rebuilt into #2826 Schema, the dependen | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | | 1A | Identity, entitlement, and hosted terms | Provisional; earlier broad discovery closed by judgment, required implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Provisional; required producer/consumer implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861), [#2873](https://github.com/benhook1013/FireMUD/pull/2873) → [#2876](https://github.com/benhook1013/FireMUD/pull/2876) → [#2880](https://github.com/benhook1013/FireMUD/pull/2880) → [#2881](https://github.com/benhook1013/FireMUD/pull/2881) → [#2911](https://github.com/benhook1013/FireMUD/pull/2911) | Earlier discovery and train pre-review did not complete the section. The tail contains JOIN recovery, retained tenant mapping, durable pair authority, authenticated snapshot preparation, purpose-separated envelopes and one-use exchange storage. Exact #2881 `b2a2f31b0` [CI 36703863842](https://github.com/benhook1013/FireMUD/actions/runs/36703863842) executed 29 JOIN, 9 connect-issuance and 9 bare-LOGIN storage PostgreSQL cases without skips or failures; Account and Game Session jobs passed, while aggregate CI remains red on recorded inherited failures. These are storage/snapshot proofs, not end-to-end credential issuance or live admission. #2911 converges the complete selected-target contract and shared signed-context component proof while denying obsolete incomplete/HMAC first-party issuance and admission; it does not enable the producer/consumer path. Required Account connect/delegation producers, full authority/consumer proof, fresh Game Design tenant handoff, protected ring delivery, durable reconnect, HTTPS/mail/abuse and live browser proof remain open in the [Player Access tracker](../implementation-tracking/player-access-and-session.md). Membership RPC and credential activation stay denied; the ring mount stays unpublished. | +| 1B | Admission, session continuity, and reconnect | Provisional; required producer/consumer implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861), [#2873](https://github.com/benhook1013/FireMUD/pull/2873) → [#2876](https://github.com/benhook1013/FireMUD/pull/2876) → [#2880](https://github.com/benhook1013/FireMUD/pull/2880) → [#2881](https://github.com/benhook1013/FireMUD/pull/2881) → [#2911](https://github.com/benhook1013/FireMUD/pull/2911) → [#2914](https://github.com/benhook1013/FireMUD/pull/2914) | Earlier discovery and train pre-review did not complete the section. Exact #2911 `78c3fe886` [CI 36778631119](https://github.com/benhook1013/FireMUD/actions/runs/36778631119) executed 30 JOIN, 9 connect-issuance and 9 bare-LOGIN storage PostgreSQL cases without skips or failures, including the complete snapshot/first-JOIN race; both authority-exhaustion methods and Game Session strict cases also passed. Aggregate CI remains red on routed inherited failures. #2914 adds unwired original committed-connect source readback and strict signed-source/context correspondence; its seven new PostgreSQL cases are pending executed proof. These are component prerequisites, not credential issuance or live admission. Required complete Account authority/consumer evidence, connect/delegation producers and registry, fresh Game Design tenant handoff, protected ring delivery, durable reconnect, HTTPS/mail/abuse and live browser proof remain open in the [Player Access tracker](../implementation-tracking/player-access-and-session.md). Membership RPC and credential activation stay denied; the ring mount stays unpublished. | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | | 2A | Tick scheduling and region authority | Queued | — | — | 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 771e6c3d9b..7d2fd6be1c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,11 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The resumed Account runtime-authority candidate adds an Account-fenced pair-preparation boundary for runtime snapshots: a verified never-joined pair reuses durable absence enrollment and exact readback, while retained active membership requires its existing receipt/event proof and preserved counters. Unmapped tenants, inactive membership, and absent rows with retained history remain denied; neither enrollment nor exact retry creates membership or an authority event. The pure snapshot reader still rejects an absent baseline. Local `:account-service:check -PfullCheck --no-configuration-cache` passed with 389 unit cases executed and all 83 integration cases compiled/discovered but skipped without Docker, including the new concurrent preparation/first-JOIN proof and the preserved connect-issuance recovery cases. #2880 owns composing this preparation with its complete typed same-snapshot response. This is not authenticated RPC, database execution, or admission proof; the runtime membership RPC, credential paths, and Account ring mount remain disabled. +The next Account-owned committed-connect source reader is an unwired prerequisite, not an authorization or credential producer. It recovers a complete successful V35 receipt and purpose-bound envelope by exact identity, checks the original compact JWT hash/JTI and asymmetric signature against the closed selected-target profile, verifies the Gateway assertion independently, and proves source/context correspondence under the Account row fence and approved retained tenant mapping. It requires the exact Game Session peer and an active owner transaction before data access, returns no raw credential, and rechecks unchanged deadlines after a fence wait. The consolidated local Account check passed with 413 unit cases executed, including 11 original-source verifier and four early-denial cases; all 105 PostgreSQL cases compiled but skipped without Docker, including the seven new source-readback cases. The CI strict inspector requires that new suite and both exact reread and fence-expiry methods to execute without skips. This component does not supply fresh tenant authority, authenticated current-eligibility evidence, an issued-token registry, protected key delivery, or a working bare-LOGIN exchange; those gates remain open and no runtime path or mount is enabled. + +Exact #2911 `78c3fe88614708a4cd224800ac0f1bd6d03b310e` [CI 36778631119](https://github.com/benhook1013/FireMUD/actions/runs/36778631119) passed both strict Account PostgreSQL gates: JOIN 30/30, connect issuance 9/9, bare-LOGIN storage 9/9, authority-generation 2/2 and authority-outbox 4/4, all zero skips/failures. The complete nonadmitting snapshot versus concurrent first-JOIN case and both exhaustion rollback methods each executed once. Game Session strict Script Pin 25/25 and WebSocket 16/16 also passed. Account and Game Session checks disabled build/configuration cache and executed their tasks; aggregate CI remains red on separately routed shared tooling, Game Design fixture and Automation formatting failures. This closes those source/component database-proof gaps, not the live authenticated snapshot, complete immutable Account evidence bundle, credential producer/registry, or end-to-end bare-LOGIN gates below. The runtime RPC and credential paths remain denied, and the ring mount remains unpublished. + +Account-fenced runtime snapshot preparation reuses durable absence enrollment and exact readback for a verified never-joined pair, while retained active membership requires its existing receipt/event proof and preserved counters. Unmapped tenants, inactive membership, and absent rows with retained history remain denied; neither enrollment nor exact retry creates membership or an authority event. The pure snapshot reader still rejects an absent baseline. #2880 composes preparation with the complete typed same-snapshot response, and the executed PostgreSQL proof above covers that nonadmitting DTO against concurrent first JOIN. It does not prove an authenticated runtime RPC or admission; those paths and the Account ring mount remain disabled. The unmerged #2876 `account-auth-authority-event/v1` correction uses ADR 0030's exact one-tenant `membershipVersion` map in the producer, strict shared codec, canonical digest vectors, immutable evidence, and Account exact retry/readback comparisons. The Account producer may extract a local numeric value only after validating the map; it does not persist or transmit a scalar event field. Shared codec and Account/Game Session vector tests execute locally; PostgreSQL JOIN/reconciliation tests compile but skip without Docker, and the runtime membership RPC remains denied until its complete same-snapshot producer and consumer proof is ready. The unactivated Account ring materializer binds a dedicated service-account username in the protected source record, checks server-reported identity before Secret access, and returns a typed non-secret receipt with source generation/predecessor and exact Secret UID/resourceVersion readback. A focused read-side verifier now checks its closed typed shape, canonical digest, and exact source, writer, and Secret bindings; this remains local structural proof, not authenticated environment/secrets-channel publication. Sole-writer RBAC, protected custody, handoff, deployment readback, and live readiness remain unproved, so no Account ring mount is published. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCommittedConnectSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCommittedConnectSource.java new file mode 100644 index 0000000000..928010f67e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCommittedConnectSource.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.security.MessageDigest; +import java.util.Objects; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceOperation.Lifecycle; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; + +/** Exact committed Account source receipt and its purpose-bound encrypted response envelope. */ +public record AccountCommittedConnectSource( + AccountConnectTokenIssuanceOperation operation, + AccountConnectTokenResponseEnvelope responseEnvelope) { + + public AccountCommittedConnectSource { + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(responseEnvelope, "responseEnvelope"); + AccountEnvelopeBinding binding = responseEnvelope.binding(); + if (operation.lifecycle() != Lifecycle.COMMITTED + || !"SUCCESS".equals(operation.outcomeCode()) + || operation.tokenIdentity() == null + || operation.tokenIdentity().isBlank() + || operation.tokenHash() == null + || operation.contextEvidenceDigest() == null + || operation.authorityTupleDigest() == null + || operation.issuanceFenceDigest() == null + || operation.postconditionDigest() == null + || !operation.operationId().equals(responseEnvelope.operationId()) + || binding.operationKind() != AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE + || !operation.operationId().toString().equals(binding.operationId()) + || !operation.requestId().equals(binding.requestId()) + || !Long.toString(operation.accountId()).equals(binding.accountId()) + || !Long.toString(operation.tenantId()).equals(binding.tenantId()) + || !operation + .connectScopeHash() + .equals(AccountJoinDigest.tokenHash(binding.connectScopeId())) + || !sameDigest(operation.requestDigest(), binding.requestDigest()) + || !sameDigest(operation.contextEvidenceDigest(), binding.contextEvidenceDigest()) + || !sameDigest(operation.authorityTupleDigest(), binding.authorityTupleDigest()) + || !sameDigest(operation.issuanceFenceDigest(), binding.issuanceFenceDigest()) + || !sameDigest(operation.postconditionDigest(), binding.postconditionDigest())) { + throw new IllegalArgumentException( + "Committed Account connect source evidence is incomplete or mismatched"); + } + } + + @Override + public String toString() { + return "AccountCommittedConnectSource[operationId=" + + operation.operationId() + + ", lifecycle=" + + operation.lifecycle() + + ", encryptedResponse=]"; + } + + private static boolean sameDigest(byte[] left, byte[] right) { + return left != null && right != null && MessageDigest.isEqual(left, right); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java index 9ef48d7f71..020f06680e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java @@ -102,6 +102,58 @@ public Optional find( return operation; } + /** + * Reads a successful committed source result using only its exact caller identity. The request + * digest and all AEAD evidence are recovered from the immutable winning operation row; callers + * must not derive or substitute a digest when they only possess the original scope and request + * IDs. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCommittedResponseEnvelope( + AccountConnectTokenIssuanceIdentity identity) { + validateIdentity(identity); + Optional stored = readOperation(identity); + if (stored.isEmpty()) { + return Optional.empty(); + } + + AccountConnectTokenIssuanceOperation operation = stored.orElseThrow(); + if (operation.lifecycle() != Lifecycle.COMMITTED + || !"SUCCESS".equals(operation.outcomeCode()) + || operation.tokenIdentity() == null + || operation.tokenIdentity().isBlank() + || operation.tokenHash() == null + || operation.contextEvidenceDigest() == null + || operation.authorityTupleDigest() == null + || operation.issuanceFenceDigest() == null + || operation.postconditionDigest() == null) { + throw new IllegalStateException( + "Connect-token source operation is not a complete committed success"); + } + + AccountEnvelopeBinding binding = + new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE, + operation.operationId().toString(), + identity.requestId(), + Long.toString(identity.accountId()), + Long.toString(identity.tenantId()), + identity.connectScopeId(), + null, + operation.requestDigest(), + operation.contextEvidenceDigest(), + operation.authorityTupleDigest(), + operation.issuanceFenceDigest(), + operation.postconditionDigest()); + AccountConnectTokenResponseEnvelope envelope = + readResponseEnvelope(identity, operation.requestDigest(), binding) + .orElseThrow( + () -> + new IllegalStateException( + "Committed connect-token source has no exact response envelope")); + return Optional.of(new AccountCommittedConnectSource(operation, envelope)); + } + /** * Adds previously absent token/authority evidence to the first writer's still-PENDING row. * Existing evidence is write-once; retries may confirm the same bytes but cannot replace them. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java new file mode 100644 index 0000000000..3cf47cbf1c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java @@ -0,0 +1,337 @@ +package net.firedevops.firemud.accountservice.security; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.PublicKey; +import java.security.Signature; +import java.security.interfaces.EdECPublicKey; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.DateTimeException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.json.JsonFactory; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Verifies an Account-signed selected-target gameplay-connect JWT source. + * + *

This original-source component verifies only against the Account public keys explicitly + * supplied at construction. It does not read or publish keys, issue tokens, consult current + * authority, or authorize gameplay admission. + */ +public final class AccountGameplayConnectSourceVerifier { + private static final String INVALID_TOKEN_MESSAGE = "invalid Account gameplay-connect source JWT"; + private static final String SAFE_PROJECTION_CORRELATION_ID = + "account-gameplay-connect-source-verifier"; + private static final long MAX_FUTURE_ISSUED_AT_SECONDS = 5L; + private static final Set HEADER_FIELDS = Set.of("alg", "kid", "typ"); + private static final JsonFactory JSON_FACTORY = + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build(); + private static final JsonMapper JSON = + JsonMapper.builder(JSON_FACTORY) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS) + .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) + .build(); + + private final String exactIssuer; + private final Map registeredKeys; + private final int maxCompactJwtBytes; + private final Clock clock; + + /** + * Creates an isolated source verifier with the exact Account issuer and public-key registry. + * + * @param exactIssuer exact Account {@code iss} value accepted by this verifier + * @param registeredKeys Account-registered public keys indexed by their exact JOSE {@code kid} + * @param maxCompactJwtBytes maximum UTF-8 byte length of an accepted compact JWT + * @param clock clock used for current source-token time checks + */ + public AccountGameplayConnectSourceVerifier( + String exactIssuer, + Map registeredKeys, + int maxCompactJwtBytes, + Clock clock) { + if (exactIssuer == null || exactIssuer.isBlank()) { + throw new IllegalArgumentException("exact Account issuer is required"); + } + if (registeredKeys == null || registeredKeys.isEmpty()) { + throw new IllegalArgumentException("Account verification keys are required"); + } + if (maxCompactJwtBytes <= 0) { + throw new IllegalArgumentException("maximum compact JWT size must be positive"); + } + if (clock == null) { + throw new IllegalArgumentException("clock is required"); + } + + Map copiedKeys = new LinkedHashMap<>(); + for (Map.Entry entry : registeredKeys.entrySet()) { + String kid = entry.getKey(); + PublicKey key = entry.getValue(); + if (kid == null || kid.isBlank() || !isSupportedKey(key)) { + throw new IllegalArgumentException("Account verification key registry is invalid"); + } + copiedKeys.put(kid, key); + } + this.exactIssuer = exactIssuer; + this.registeredKeys = Collections.unmodifiableMap(copiedKeys); + this.maxCompactJwtBytes = maxCompactJwtBytes; + this.clock = clock; + } + + /** + * Verifies a compact Account gameplay-connect source JWT and returns its closed source claims. + * + *

Every verification failure has the same sanitized exception message. Neither the source + * token, credential material, nor detailed parser or cryptographic failures are retained. + * + * @param compactJwt compact Account-signed JWT + * @return deeply immutable exact source-claim map; the compact JWT is never included + * @throws IllegalArgumentException if the token is malformed, untrusted, expired, or outside the + * registered source profile + */ + public Map verify(String compactJwt) { + try { + return verifyInternal(compactJwt); + } catch (RuntimeException | GeneralSecurityException ex) { + throw invalidToken(); + } + } + + private Map verifyInternal(String compactJwt) throws GeneralSecurityException { + String[] segments = splitCanonicalCompactJwt(compactJwt); + byte[] protectedHeaderBytes = decodeCanonicalBase64Url(segments[0]); + byte[] payloadBytes = decodeCanonicalBase64Url(segments[1]); + byte[] signatureBytes = decodeCanonicalBase64Url(segments[2]); + + Map header = parseJsonObject(protectedHeaderBytes); + validateProtectedHeaderShape(header); + String algorithm = requireText(header, "alg"); + String kid = requireText(header, "kid"); + if (header.containsKey("typ") && !"JWT".equals(header.get("typ"))) { + throw invalidToken(); + } + + PublicKey key = registeredKeys.get(kid); + if (key == null) { + throw invalidToken(); + } + String jcaAlgorithm = requireCompatibleAlgorithm(algorithm, key); + verifySignature(segments[0], segments[1], signatureBytes, key, jcaAlgorithm); + + Map sourceClaims = parseJsonObject(payloadBytes); + Instant now = clock.instant(); + validateIssuerAudienceAndTime(sourceClaims, now); + + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + sourceClaims, now.getEpochSecond(), SAFE_PROJECTION_CORRELATION_ID); + return deepImmutableObject(sourceClaims); + } + + private String[] splitCanonicalCompactJwt(String compactJwt) { + if (compactJwt == null || compactJwt.isEmpty() || compactJwt.length() > maxCompactJwtBytes) { + throw invalidToken(); + } + for (int index = 0; index < compactJwt.length(); index++) { + if (compactJwt.charAt(index) > 0x7f) { + throw invalidToken(); + } + } + + int firstDot = compactJwt.indexOf('.'); + int secondDot = firstDot < 0 ? -1 : compactJwt.indexOf('.', firstDot + 1); + if (firstDot <= 0 + || secondDot <= firstDot + 1 + || secondDot == compactJwt.length() - 1 + || compactJwt.indexOf('.', secondDot + 1) >= 0) { + throw invalidToken(); + } + return new String[] { + compactJwt.substring(0, firstDot), + compactJwt.substring(firstDot + 1, secondDot), + compactJwt.substring(secondDot + 1) + }; + } + + private byte[] decodeCanonicalBase64Url(String segment) { + try { + byte[] decoded = Base64.getUrlDecoder().decode(segment); + String canonical = Base64.getUrlEncoder().withoutPadding().encodeToString(decoded); + if (!canonical.equals(segment)) { + throw invalidToken(); + } + return decoded; + } catch (IllegalArgumentException ex) { + throw invalidToken(); + } + } + + private Map parseJsonObject(byte[] jsonBytes) { + try (var parser = JSON_FACTORY.createParser(jsonBytes)) { + Object decoded = JSON.readValue(parser, Object.class); + if (parser.nextToken() != null || !(decoded instanceof Map rawObject)) { + throw invalidToken(); + } + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : rawObject.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw invalidToken(); + } + result.put(key, entry.getValue()); + } + return result; + } catch (RuntimeException ex) { + throw invalidToken(); + } + } + + private void validateProtectedHeaderShape(Map header) { + if (!HEADER_FIELDS.containsAll(header.keySet()) + || !header.containsKey("alg") + || !header.containsKey("kid")) { + throw invalidToken(); + } + } + + private String requireCompatibleAlgorithm(String algorithm, PublicKey key) { + if (key instanceof RSAPublicKey) { + return switch (algorithm) { + case "RS256" -> "SHA256withRSA"; + case "RS384" -> "SHA384withRSA"; + case "RS512" -> "SHA512withRSA"; + default -> throw invalidToken(); + }; + } + if (key instanceof EdECPublicKey edKey + && "Ed25519".equals(edKey.getParams().getName()) + && "EdDSA".equals(algorithm)) { + return "Ed25519"; + } + throw invalidToken(); + } + + private void verifySignature( + String protectedSegment, + String payloadSegment, + byte[] signatureBytes, + PublicKey key, + String jcaAlgorithm) + throws GeneralSecurityException { + if (signatureBytes.length == 0) { + throw invalidToken(); + } + if ("Ed25519".equals(jcaAlgorithm) && signatureBytes.length != 64) { + throw invalidToken(); + } + byte[] signingInput = + (protectedSegment + "." + payloadSegment).getBytes(StandardCharsets.US_ASCII); + Signature verifier = Signature.getInstance(jcaAlgorithm); + verifier.initVerify(key); + verifier.update(signingInput); + if (!verifier.verify(signatureBytes)) { + throw invalidToken(); + } + } + + private void validateIssuerAudienceAndTime(Map claims, Instant now) { + if (!exactIssuer.equals(claims.get("iss")) + || !(claims.get("iss") instanceof String) + || !"gameplay-connect".equals(claims.get("aud"))) { + throw invalidToken(); + } + BigInteger issuedAt = requireInteger(claims, "iat"); + BigInteger expiresAt = requireInteger(claims, "exp"); + if (issuedAt.signum() <= 0 || expiresAt.compareTo(issuedAt) <= 0) { + throw invalidToken(); + } + try { + Instant issuedAtInstant = Instant.ofEpochSecond(issuedAt.longValueExact()); + Instant expiresAtInstant = Instant.ofEpochSecond(expiresAt.longValueExact()); + if (!now.isBefore(expiresAtInstant) + || issuedAt + .subtract(BigInteger.valueOf(now.getEpochSecond())) + .compareTo(BigInteger.valueOf(MAX_FUTURE_ISSUED_AT_SECONDS)) + > 0) { + throw invalidToken(); + } + // Force validation of both epoch-second claims before the shared profile codec sees them. + if (issuedAtInstant.isAfter(expiresAtInstant)) { + throw invalidToken(); + } + } catch (ArithmeticException | DateTimeException ex) { + throw invalidToken(); + } + } + + private BigInteger requireInteger(Map values, String field) { + Object value = values.get(field); + if (!(value instanceof BigInteger integer)) { + throw invalidToken(); + } + return integer; + } + + private String requireText(Map values, String field) { + Object value = values.get(field); + if (!(value instanceof String text) || text.isBlank()) { + throw invalidToken(); + } + return text; + } + + private Map deepImmutableObject(Map source) { + Map copy = new LinkedHashMap<>(); + source.forEach((key, value) -> copy.put(key, deepImmutableValue(value))); + return Collections.unmodifiableMap(copy); + } + + private Object deepImmutableValue(Object value) { + if (value == null + || value instanceof String + || value instanceof Boolean + || value instanceof BigInteger + || value instanceof BigDecimal) { + return value; + } + if (value instanceof Map sourceMap) { + Map copy = new LinkedHashMap<>(); + for (Map.Entry entry : sourceMap.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw invalidToken(); + } + copy.put(key, deepImmutableValue(entry.getValue())); + } + return Collections.unmodifiableMap(copy); + } + if (value instanceof List sourceList) { + List copy = new ArrayList<>(sourceList.size()); + for (Object entry : sourceList) { + copy.add(deepImmutableValue(entry)); + } + return Collections.unmodifiableList(copy); + } + throw invalidToken(); + } + + private static boolean isSupportedKey(PublicKey key) { + return (key instanceof RSAPublicKey rsaKey && rsaKey.getModulus().bitLength() >= 2048) + || (key instanceof EdECPublicKey edKey && "Ed25519".equals(edKey.getParams().getName())); + } + + private static IllegalArgumentException invalidToken() { + return new IllegalArgumentException(INVALID_TOKEN_MESSAGE); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java new file mode 100644 index 0000000000..7f3f21d132 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java @@ -0,0 +1,312 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PublicKey; +import java.time.Clock; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountCommittedConnectSource; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.GatewayConnectContext; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unwired, non-authorizing readback of the original committed Account gameplay-connect source. This + * component verifies provenance and source/context correspondence only; it does not establish + * current gameplay authority, registry readiness, or admission. + */ +public final class AccountCommittedConnectSourceReader { + private final AccountConnectTokenIssuanceRepository issuanceRepository; + private final AccountRepository accountRepository; + private final AccountTenantIdentityResolver tenantIdentityResolver; + private final AccountJoinOperationRepository joinOperationRepository; + private final AccountEnvelopeCrypto envelopeCrypto; + private final AccountGameplayConnectSourceVerifier sourceVerifier; + private final Map gatewayVerificationKeys; + private final Clock clock; + private final String expectedGameSessionPeerUri; + + public AccountCommittedConnectSourceReader( + AccountConnectTokenIssuanceRepository issuanceRepository, + AccountRepository accountRepository, + AccountTenantIdentityResolver tenantIdentityResolver, + AccountJoinOperationRepository joinOperationRepository, + AccountEnvelopeCrypto envelopeCrypto, + AccountGameplayConnectSourceVerifier sourceVerifier, + Map gatewayVerificationKeys, + Clock clock, + String workloadNamespace) { + this.issuanceRepository = Objects.requireNonNull(issuanceRepository, "issuanceRepository"); + this.accountRepository = Objects.requireNonNull(accountRepository, "accountRepository"); + this.tenantIdentityResolver = + Objects.requireNonNull(tenantIdentityResolver, "tenantIdentityResolver"); + this.joinOperationRepository = + Objects.requireNonNull(joinOperationRepository, "joinOperationRepository"); + this.envelopeCrypto = Objects.requireNonNull(envelopeCrypto, "envelopeCrypto"); + this.sourceVerifier = Objects.requireNonNull(sourceVerifier, "sourceVerifier"); + this.gatewayVerificationKeys = Map.copyOf(gatewayVerificationKeys); + if (this.gatewayVerificationKeys.isEmpty()) { + throw new IllegalArgumentException("Gateway verification keys are required"); + } + this.clock = Objects.requireNonNull(clock, "clock"); + if (workloadNamespace == null || workloadNamespace.isBlank()) { + throw new IllegalArgumentException("Account workload namespace is required"); + } + this.expectedGameSessionPeerUri = + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + .filter(identity -> workloadNamespace.equals(identity.namespace())) + .map(GrpcPeerIdentity::uri) + .orElseThrow( + () -> new IllegalArgumentException("Account workload namespace is invalid")); + } + + /** + * Reads and verifies one original committed source in the caller's owner transaction. The exact + * Game Session peer, Gateway assertion, account fence, retained tenant association, source + * envelope, Account JWT signature/profile, and complete source/context correspondence are all + * checked before returning immutable evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public OriginalSourceEvidence read( + AccountConnectTokenIssuanceIdentity identity, String signedGatewayContext) { + Objects.requireNonNull(identity, "identity"); + requireGameSessionPeer(); + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Committed Account source readback requires an active owner transaction"); + } + GatewayConnectContext initialContext = verifyGatewayContext(signedGatewayContext); + requireContextRequestIdentity(identity, initialContext); + + // The same Account row fence serializes this identity/provenance read with JOIN and other + // fenced Account work. The retained tenant association resolver separately verifies its + // approved row and exact current source-evidence digest in this owner transaction. + joinOperationRepository.lockAccount(identity.accountId()); + Account account = + accountRepository + .findById(identity.accountId()) + .orElseThrow(() -> new IllegalStateException("Account source identity is absent")); + UUID accountUuid = requireAccountIdentity(account, identity.accountId()); + requireContextValue(initialContext, "accountId", accountUuid.toString()); + + ApprovedAssociation tenantAssociation = tenantIdentityResolver.resolve(identity.tenantId()); + if (tenantAssociation.legacyTenantId() != identity.tenantId()) { + throw new IllegalStateException("Account source tenant identity is mismatched"); + } + requireContextValue( + initialContext, "tenantId", tenantAssociation.canonicalTenantId().toString()); + + AccountCommittedConnectSource committedSource = + issuanceRepository + .readCommittedResponseEnvelope(identity) + .orElseThrow(() -> new IllegalStateException("Committed Account source is absent")); + byte[] compactJwtBytes = + envelopeCrypto.decrypt( + committedSource.responseEnvelope().envelope(), + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + committedSource.responseEnvelope().binding()); + try { + String compactJwt = decodeStrictUtf8(compactJwtBytes); + byte[] actualTokenHash = sha256(compactJwtBytes); + if (!MessageDigest.isEqual(committedSource.operation().tokenHash(), actualTokenHash)) { + throw new IllegalStateException("Committed Account source token hash does not match"); + } + + Map sourceClaims = sourceVerifier.verify(compactJwt); + if (!Objects.equals(sourceClaims.get("jti"), committedSource.operation().tokenIdentity())) { + throw new IllegalStateException("Committed Account source token identity does not match"); + } + GatewayConnectContextCodec.requireVerifiedAccountSourceMatchesGatewayContext( + sourceClaims, initialContext); + + // A transaction may wait on the Account fence after the Gateway originally verified its + // short-lived context. Recheck the unchanged signed assertion at the current clock without + // restamping or extending any deadline before returning the evidence. + GatewayConnectContext currentContext = verifyGatewayContext(signedGatewayContext); + if (!initialContext.kid().equals(currentContext.kid()) + || !initialContext.claims().equals(currentContext.claims())) { + throw new IllegalStateException("Gateway source context changed during Account readback"); + } + Map currentSourceClaims = sourceVerifier.verify(compactJwt); + if (!sourceClaims.equals(currentSourceClaims)) { + throw new IllegalStateException("Account source claims changed during source readback"); + } + GatewayConnectContextCodec.requireVerifiedAccountSourceMatchesGatewayContext( + currentSourceClaims, currentContext); + + return new OriginalSourceEvidence( + committedSource.operation().operationId(), + committedSource.responseEnvelope().envelope().keyId(), + actualTokenHash, + currentContext.kid(), + currentSourceClaims, + currentContext.claims()); + } finally { + java.util.Arrays.fill(compactJwtBytes, (byte) 0); + } + } + + private GatewayConnectContext verifyGatewayContext(String signedGatewayContext) { + return GatewayConnectContextCodec.verifyAndDecode( + signedGatewayContext, gatewayVerificationKeys, clock); + } + + private void requireGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !expectedGameSessionPeerUri.equals(peer.uri())) { + throw new AdminAuthorizationException( + "Committed Account source readback requires the exact Game Session workload identity"); + } + } + + private static void requireContextRequestIdentity( + AccountConnectTokenIssuanceIdentity identity, GatewayConnectContext context) { + if (!identity.connectScopeId().equals(context.text("connectScopeId")) + || !identity.requestId().equals(context.text("connectRequestId"))) { + throw new IllegalArgumentException( + "Gateway context does not match the exact Account source request identity"); + } + } + + private static UUID requireAccountIdentity(Account account, long numericAccountId) { + if (account.getId() == null + || account.getId() != numericAccountId + || account.getAccountUuid() == null + || account.getAccountUuidProvenance() == null + || account.getAccountUuidSourceNumericId() == null + || account.getAccountUuidSourceNumericId() != numericAccountId) { + throw new IllegalStateException("Account canonical identity provenance is mismatched"); + } + return account.getAccountUuid(); + } + + private static void requireContextValue( + GatewayConnectContext context, String field, String expectedValue) { + if (!expectedValue.equals(context.text(field))) { + throw new IllegalArgumentException( + "Gateway context does not match the retained Account " + field); + } + } + + private static String decodeStrictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException exception) { + throw new IllegalStateException("Committed Account source envelope is not strict UTF-8"); + } + } + + private static byte[] sha256(byte[] bytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + /** + * Immutable, non-authorizing exact original-source readback. It never exposes the compact JWT. + */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Verified claim maps and nested JSON values are deeply copied into immutable containers " + + "by the canonical constructor before record accessors expose them") + public record OriginalSourceEvidence( + UUID operationId, + String responseEnvelopeKeyId, + byte[] sourceTokenHash, + String gatewayKeyId, + Map originalSourceClaims, + Map gatewayContextClaims) { + public OriginalSourceEvidence { + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(responseEnvelopeKeyId, "responseEnvelopeKeyId"); + Objects.requireNonNull(gatewayKeyId, "gatewayKeyId"); + if (sourceTokenHash == null || sourceTokenHash.length != 32) { + throw new IllegalArgumentException("source token hash must be 32 bytes"); + } + sourceTokenHash = sourceTokenHash.clone(); + originalSourceClaims = immutableObject(originalSourceClaims); + gatewayContextClaims = immutableObject(gatewayContextClaims); + } + + @Override + public byte[] sourceTokenHash() { + return sourceTokenHash.clone(); + } + + @Override + public String toString() { + return "OriginalSourceEvidence[operationId=" + + operationId + + ", source=, gatewayContext=]"; + } + + private static Map immutableObject(Map source) { + Objects.requireNonNull(source, "claims"); + Map copy = new LinkedHashMap<>(); + source.forEach((key, value) -> copy.put(key, immutableValue(value))); + return Collections.unmodifiableMap(copy); + } + + private static Object immutableValue(Object value) { + if (value == null + || value instanceof String + || value instanceof Boolean + || value instanceof BigInteger + || value instanceof java.math.BigDecimal) { + return value; + } + if (value instanceof Map source) { + Map copy = new LinkedHashMap<>(); + source.forEach( + (key, nested) -> { + if (!(key instanceof String text)) { + throw new IllegalArgumentException("claim object keys must be strings"); + } + copy.put(text, immutableValue(nested)); + }); + return Collections.unmodifiableMap(copy); + } + if (value instanceof List source) { + List copy = new ArrayList<>(source.size()); + source.forEach(nested -> copy.add(immutableValue(nested))); + return Collections.unmodifiableList(copy); + } + throw new IllegalArgumentException("unsupported verified claim value"); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java new file mode 100644 index 0000000000..0b1e04e981 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java @@ -0,0 +1,1030 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.security.Signature; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountCommittedConnectSource; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceOperation.Lifecycle; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException.Failure; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader.OriginalSourceEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import net.firedevops.firemud.common.security.GatewayConnectContextSignature; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +@Testcontainers(disabledWithoutDocker = true) +// Peer identity is context-scoped here; this proves the component caller guard, not network mTLS. +class AccountCommittedConnectSourceReaderIntegrationTest { + private static final String WORKLOAD_NAMESPACE = "account-test"; + private static final String ACCOUNT_ISSUER = "https://account.example.test"; + private static final String ACCOUNT_KEY_ID = "account-test-key"; + private static final String GATEWAY_KEY_ID = "gateway-test-key"; + private static final long LEGACY_TENANT_ID = 77L; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Base64.Encoder BASE64_URL = Base64.getUrlEncoder().withoutPadding(); + private static final SecureRandom FIXTURE_RANDOM = new SecureRandom(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @TempDir Path tempDir; + + @Test + void readsExactCommittedOriginalSourceAndLostResultWithoutMutation() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newSource(prepared, SourceState.COMMITTED); + Snapshot before = sourceSnapshot(prepared, source.identity()); + + OriginalSourceEvidence first = + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> prepared.reader().read(source.identity(), source.gatewayEnvelope()))); + OriginalSourceEvidence reread = + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> prepared.reader().read(source.identity(), source.gatewayEnvelope()))); + + assertThat(first.operationId()).isEqualTo(reread.operationId()); + assertThat(first.responseEnvelopeKeyId()).isEqualTo(reread.responseEnvelopeKeyId()); + assertThat(first.gatewayKeyId()).isEqualTo(GATEWAY_KEY_ID); + assertThat(first.sourceTokenHash()).containsExactly(reread.sourceTokenHash()); + assertThat(first.originalSourceClaims()).isEqualTo(source.sourceClaims()); + assertThat(first.gatewayContextClaims()).isEqualTo(source.gatewayClaims()); + assertThat(first.originalSourceClaims()).containsEntry("aud", "gameplay-connect"); + assertThat(first.originalSourceClaims().get("jti")).isEqualTo(source.tokenIdentity()); + assertThat(first.toString()).doesNotContain(source.identity().connectScopeId()); + assertThatThrownBy(() -> first.originalSourceClaims().put("extra", "value")) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> + ((Map) first.originalSourceClaims().get("authorityTuple")) + .put("extra", BigInteger.ONE)) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(before); + } + + @Test + void requiresExactGameSessionCallerAndRegisteredGatewayAndAccountKeys() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newSource(prepared, SourceState.COMMITTED); + + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "account-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .read(source.identity(), source.gatewayEnvelope())))) + .isInstanceOf(AdminAuthorizationException.class); + + assertThatThrownBy( + () -> + withoutPeer( + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .read(source.identity(), source.gatewayEnvelope())))) + .isInstanceOf(AdminAuthorizationException.class); + + assertThatThrownBy( + () -> + withPeer( + peer("other-account-test", "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .read(source.identity(), source.gatewayEnvelope())))) + .isInstanceOf(AdminAuthorizationException.class); + + Snapshot beforeOutsideTransaction = sourceSnapshot(prepared, source.identity()); + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> prepared.reader().read(source.identity(), source.gatewayEnvelope()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(beforeOutsideTransaction); + + SourceFixture unknownGateway = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, false, true, false, false)); + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .read( + unknownGateway.identity(), + unknownGateway.gatewayEnvelope())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown Gateway verification key"); + + SourceFixture unknownSource = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(true, false, false, false, false, false, false)); + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .read( + unknownSource.identity(), + unknownSource.gatewayEnvelope())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("invalid Account gameplay-connect source JWT"); + } + + @Test + void rejectsWrongStoredTokenHashJtiAndSourceTargetCorrespondence() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture wrongHash = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, true, false, false, false, false, false)); + SourceFixture wrongJti = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, true, false, false, false, false)); + SourceFixture wrongTarget = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, true, false, false, false)); + + assertReadRejected(prepared, wrongHash, IllegalStateException.class, "token hash"); + assertReadRejected(prepared, wrongJti, IllegalStateException.class, "token identity"); + assertReadRejected( + prepared, wrongTarget, IllegalArgumentException.class, "does not exactly preserve"); + } + + @Test + void requiresPresentCommittedSuccessfulV35SourceAndResponseEnvelope() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture absent = newSource(prepared, SourceState.ABSENT); + SourceFixture pending = newSource(prepared, SourceState.PENDING); + SourceFixture failed = newSource(prepared, SourceState.FAILED); + + assertReadRejected(prepared, absent, IllegalStateException.class, "source is absent"); + assertReadRejected( + prepared, pending, IllegalStateException.class, "not a complete committed success"); + assertReadRejected( + prepared, failed, IllegalStateException.class, "not a complete committed success"); + } + + @Test + void rejectsUnmappedAndChangedRetainedTenantEvidence() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture unmappedTenant = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, false, false, false, true)); + assertReadRejected( + prepared, + unmappedTenant, + IllegalStateException.class, + "approved Account tenant association is absent"); + + SourceFixture changedRetainedEvidence = newSource(prepared, SourceState.COMMITTED); + inTransaction( + prepared.db().transaction(), + () -> + prepared + .db() + .dsl() + .execute( + "UPDATE account_legacy_tenant_sources " + + "SET captured_at = captured_at + INTERVAL '1 second' " + + "WHERE legacy_tenant_id = ?", + prepared.tenantId())); + assertReadRejected( + prepared, + changedRetainedEvidence, + IllegalStateException.class, + "approved Account source evidence differs from retained rows"); + } + + @Test + void rejectsWrongPurposeAndWrongPurposeKeyForStoredEnvelope() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newSource(prepared, SourceState.COMMITTED); + AccountCommittedConnectSource stored = + inTransaction( + prepared.db().transaction(), + () -> + prepared + .db() + .issuanceRepository() + .readCommittedResponseEnvelope(source.identity()) + .orElseThrow()); + AccountEnvelopeBinding otherPurposeBinding = + new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE, + UUID.randomUUID().toString(), + "other-request", + Long.toString(source.identity().accountId()), + Long.toString(source.identity().tenantId()), + source.identity().connectScopeId(), + UUID.randomUUID().toString(), + digest("other-request"), + digest("other-context"), + digest("other-authority"), + digest("other-fence"), + digest("other-postcondition")); + assertThatThrownBy( + () -> + prepared + .db() + .envelopeCrypto() + .decrypt( + stored.responseEnvelope().envelope(), + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, + otherPurposeBinding)) + .isInstanceOf(AccountEnvelopeCryptoException.class) + .extracting(exception -> ((AccountEnvelopeCryptoException) exception).failure()) + .isEqualTo(Failure.PURPOSE_MISMATCH); + + AccountCommittedConnectSourceReader wrongKeyReader = + readerWithCrypto(prepared, differentConnectPurposeKey()); + assertReadRejected( + wrongKeyReader, + prepared, + source, + AccountEnvelopeCryptoException.class, + "AUTHENTICATION_FAILED"); + } + + @Test + void doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, false, false, true, false)); + CountDownLatch accountRowLocked = new CountDownLatch(1); + CountDownLatch releaseAccountRow = new CountDownLatch(1); + CountDownLatch readerBackendIdentified = new CountDownLatch(1); + AtomicInteger blockerBackendPid = new AtomicInteger(); + AtomicInteger readerBackendPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + Future blocker = + executor.submit( + () -> + inTransaction( + prepared.db().transaction(), + () -> { + blockerBackendPid.set(requirePositiveBackendPid(prepared.db().dsl())); + prepared + .db() + .dsl() + .resultQuery( + "SELECT id FROM accounts WHERE id = ? FOR UPDATE", + prepared.accountId()) + .fetchOne(); + accountRowLocked.countDown(); + if (!await(releaseAccountRow, 20, TimeUnit.SECONDS)) { + throw new IllegalStateException("Account fence holder was not released"); + } + return null; + })); + try { + assertThat(accountRowLocked.await(5, TimeUnit.SECONDS)).isTrue(); + Future reader = + executor.submit( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> { + readerBackendPid.set( + requirePositiveBackendPid(prepared.db().dsl())); + readerBackendIdentified.countDown(); + return prepared + .reader() + .read(source.identity(), source.gatewayEnvelope()); + }))); + if (!readerBackendIdentified.await(5, TimeUnit.SECONDS)) { + try { + reader.get(0, TimeUnit.MILLISECONDS); + } catch (java.util.concurrent.ExecutionException failure) { + throw new AssertionError( + "Reader failed before identifying its backend", failure.getCause()); + } catch (java.util.concurrent.TimeoutException stillRunning) { + // The bounded identity wait elapsed while the worker was still running. + } + throw new AssertionError( + "Reader backend PID was not identified before the bounded deadline"); + } + assertThat( + awaitAccountFenceBlock( + prepared.db().dsl(), + readerBackendPid.get(), + blockerBackendPid.get(), + Duration.ofSeconds(5))) + .as("the exact reader backend is blocked by the exact Account row fence backend") + .isTrue(); + + // The source token remains valid; only the Gateway's signed, shortened deadline expires. + prepared.clock().advance(Duration.ofSeconds(3)); + releaseAccountRow.countDown(); + assertThatThrownBy(() -> reader.get(10, TimeUnit.SECONDS)) + .satisfies( + thrown -> { + Throwable cause = thrown; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + assertThat(cause) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Gateway context is expired"); + }); + } finally { + releaseAccountRow.countDown(); + blocker.get(10, TimeUnit.SECONDS); + executor.shutdownNow(); + } + } + + private PreparedAccount newPreparedAccount() throws Exception { + String schema = + "account_source_" + UUID.randomUUID().toString().replace("-", "").substring(0, 16); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("25") + .load() + .migrate(); + + DSLContext seedDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + long accountId = + insertRetainedRows(seedDsl, LEGACY_TENANT_ID, "source-reader-" + UUID.randomUUID()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + var sourceEvidence = new LegacyTenantSourceEvidence(dsl); + var generations = new AccountAuthorityGenerationRepository(dsl); + var associations = + new ApprovedLegacyTenantAssociationRepository( + dsl, sourceEvidence, WORKLOAD_NAMESPACE, generations); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + UUID tenantUuid = UUID.randomUUID(); + String retainedEvidenceDigest = sourceEvidence.digest(LEGACY_TENANT_ID); + inTransaction( + transaction, + () -> + associations.importApproved( + LEGACY_TENANT_ID, approvedAssociation(retainedEvidenceDigest, tenantUuid))); + + byte[] bareLoginKey = new byte[32]; + byte[] connectTokenKey = new byte[32]; + FIXTURE_RANDOM.nextBytes(bareLoginKey); + do { + FIXTURE_RANDOM.nextBytes(connectTokenKey); + } while (MessageDigest.isEqual(bareLoginKey, connectTokenKey)); + Path manifest = tempDir.resolve("account-response-ring-" + UUID.randomUUID() + ".v1"); + String ringManifest = + "version=1\nactiveKeyId=test-key\nkey:test-key:bare-login=" + + BASE64_URL.encodeToString(bareLoginKey) + + "\nkey:test-key:connect-token=" + + BASE64_URL.encodeToString(connectTokenKey) + + "\n"; + Files.writeString(manifest, ringManifest, StandardCharsets.US_ASCII); + AccountEnvelopeCrypto envelopeCrypto = new AccountEnvelopeCrypto(manifest); + + KeyPair accountKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + KeyPair unknownAccountKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + KeyPair gatewayKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + KeyPair unknownGatewayKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + TestClock clock = new TestClock(Instant.parse("2026-10-01T00:00:00Z")); + AccountGameplayConnectSourceVerifier verifier = + new AccountGameplayConnectSourceVerifier( + ACCOUNT_ISSUER, Map.of(ACCOUNT_KEY_ID, accountKeyPair.getPublic()), 16 * 1024, clock); + Map gatewayKeys = + Map.of(GATEWAY_KEY_ID, gatewayKeyPair.getPublic()); + AccountConnectTokenIssuanceRepository issuanceRepository = + new AccountConnectTokenIssuanceRepository(dsl); + AccountRepository accountRepository = new AccountRepository(dsl); + AccountTenantIdentityResolver tenantResolver = + new AccountTenantIdentityResolver(associations, sourceEvidence, WORKLOAD_NAMESPACE); + AccountJoinOperationRepository joinRepository = new AccountJoinOperationRepository(dsl); + AccountCommittedConnectSourceReader reader = + new AccountCommittedConnectSourceReader( + issuanceRepository, + accountRepository, + tenantResolver, + joinRepository, + envelopeCrypto, + verifier, + gatewayKeys, + clock, + WORKLOAD_NAMESPACE); + TestContext db = new TestContext(dsl, transaction, issuanceRepository, envelopeCrypto); + return new PreparedAccount( + db, + accountId, + LEGACY_TENANT_ID, + accountUuid, + tenantUuid, + accountKeyPair, + unknownAccountKeyPair, + gatewayKeyPair, + unknownGatewayKeyPair, + verifier, + gatewayKeys, + accountRepository, + tenantResolver, + joinRepository, + reader, + clock); + } + + private SourceFixture newSource(PreparedAccount prepared, SourceState state) throws Exception { + return newSource(prepared, state, SourceOptions.NORMAL); + } + + private SourceFixture newSource( + PreparedAccount prepared, SourceState state, SourceOptions options) throws Exception { + String requestId = "source-request-" + UUID.randomUUID(); + String connectScopeId = "source-scope-" + UUID.randomUUID(); + long sourceTenantId = + options.unmappedTenant() ? prepared.tenantId() + 1000L : prepared.tenantId(); + UUID sourceTenantUuid = options.unmappedTenant() ? UUID.randomUUID() : prepared.tenantUuid(); + AccountConnectTokenIssuanceIdentity identity = + new AccountConnectTokenIssuanceIdentity( + prepared.accountId(), sourceTenantId, connectScopeId, requestId); + String tokenIdentity = "source-jti-" + UUID.randomUUID(); + Map sourceClaims = + sourceClaims( + prepared.accountUuid(), sourceTenantUuid, identity, tokenIdentity, prepared.clock()); + KeyPair tokenSigner = + options.unknownSourceKey() ? prepared.unknownAccountKeyPair() : prepared.accountKeyPair(); + String tokenKeyId = options.unknownSourceKey() ? "unregistered-account-key" : ACCOUNT_KEY_ID; + byte[] compactJwt = signAccountJwt(sourceClaims, tokenKeyId, tokenSigner); + byte[] storedHash = sha256(compactJwt); + if (options.wrongHash()) { + storedHash[0] ^= 0x01; + } + String storedTokenIdentity = options.wrongJti() ? "different-source-jti" : tokenIdentity; + + Map gatewaySourceClaims = new LinkedHashMap<>(sourceClaims); + if (options.wrongTarget()) { + gatewaySourceClaims.put("worldSlug", "different-world"); + } + Map projectedGatewayClaims = + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + gatewaySourceClaims, + prepared.clock().instant().getEpochSecond(), + "gateway-request-" + UUID.randomUUID()); + Map gatewayClaims = new LinkedHashMap<>(projectedGatewayClaims); + if (options.shortGatewayDeadline()) { + gatewayClaims.put( + "expiresAt", BigInteger.valueOf(prepared.clock().instant().getEpochSecond() + 2L)); + } + byte[] gatewayPayload = JSON.writeValueAsBytes(gatewayClaims); + KeyPair gatewaySigner = + options.unknownGatewayKey() ? prepared.unknownGatewayKeyPair() : prepared.gatewayKeyPair(); + String gatewayKid = options.unknownGatewayKey() ? "unregistered-gateway-key" : GATEWAY_KEY_ID; + String gatewayEnvelope = + GatewayConnectContextSignature.sign(gatewayPayload, gatewayKid, gatewaySigner.getPrivate()); + + if (state != SourceState.ABSENT) { + byte[] requestDigest = + sha256(("source-request-digest:" + requestId).getBytes(StandardCharsets.UTF_8)); + inTransaction( + prepared.db().transaction(), + () -> { + var claim = prepared.db().issuanceRepository().claim(identity, requestDigest); + if (state == SourceState.PENDING) { + return null; + } + AccountEnvelopeBinding binding = + new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE, + claim.operation().operationId().toString(), + identity.requestId(), + Long.toString(identity.accountId()), + Long.toString(identity.tenantId()), + identity.connectScopeId(), + null, + requestDigest, + digest("context:" + requestId), + digest("authority:" + requestId), + digest("fence:" + requestId), + digest("postcondition:" + requestId)); + boolean success = state == SourceState.COMMITTED; + byte[] plaintext = + success + ? compactJwt + : "deterministic issuance failure".getBytes(StandardCharsets.UTF_8); + AccountEncryptedEnvelope encrypted = + prepared + .db() + .envelopeCrypto() + .encrypt(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, binding, plaintext); + prepared + .db() + .issuanceRepository() + .completeWithEnvelope( + claim, + requestDigest, + success ? Lifecycle.COMMITTED : Lifecycle.FAILED, + success ? "SUCCESS" : "SOURCE_UNAVAILABLE", + success ? storedTokenIdentity : null, + success ? storedHash : null, + binding, + encrypted); + return null; + }); + } + return new SourceFixture(identity, gatewayEnvelope, sourceClaims, gatewayClaims, tokenIdentity); + } + + private AccountEnvelopeCrypto differentConnectPurposeKey() throws Exception { + byte[] bareLoginKey = new byte[32]; + byte[] connectTokenKey = new byte[32]; + FIXTURE_RANDOM.nextBytes(bareLoginKey); + do { + FIXTURE_RANDOM.nextBytes(connectTokenKey); + } while (MessageDigest.isEqual(bareLoginKey, connectTokenKey)); + Path manifest = tempDir.resolve("wrong-account-response-ring-" + UUID.randomUUID() + ".v1"); + String ringManifest = + "version=1\nactiveKeyId=test-key\nkey:test-key:bare-login=" + + BASE64_URL.encodeToString(bareLoginKey) + + "\nkey:test-key:connect-token=" + + BASE64_URL.encodeToString(connectTokenKey) + + "\n"; + Files.writeString(manifest, ringManifest, StandardCharsets.US_ASCII); + return new AccountEnvelopeCrypto(manifest); + } + + private static AccountCommittedConnectSourceReader readerWithCrypto( + PreparedAccount prepared, AccountEnvelopeCrypto crypto) { + return new AccountCommittedConnectSourceReader( + prepared.db().issuanceRepository(), + prepared.accountRepository(), + prepared.tenantResolver(), + prepared.joinRepository(), + crypto, + prepared.verifier(), + prepared.gatewayKeys(), + prepared.clock(), + WORKLOAD_NAMESPACE); + } + + private static Map sourceClaims( + UUID accountUuid, + UUID tenantUuid, + AccountConnectTokenIssuanceIdentity identity, + String tokenIdentity, + Clock clock) { + BigInteger one = BigInteger.ONE; + BigInteger now = BigInteger.valueOf(clock.instant().getEpochSecond()); + Map tenantGeneration = Map.of(tenantUuid.toString(), one); + Map accountSecurityCutoff = + Map.of( + "accountAuthorityGeneration", one, + "outboxStreamKey", "account:auth-authority:v1:account/" + accountUuid, + "outboxSequence", one); + Map tenantBillingCutoffEntry = + Map.of( + "tenantAuthorityGeneration", + one, + "tenantBillingSequence", + BigInteger.ZERO, + "outboxStreamKey", + "account:auth-authority:v1:tenant/" + tenantUuid, + "outboxSequence", + one); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", one, + "accountAuthorityGeneration", one, + "tenantAuthorityGeneration", tenantGeneration, + "membershipAuthorityGeneration", tenantGeneration, + "privateRealmGrantVersions", List.of(), + "accountSecurityCutoff", accountSecurityCutoff, + "tenantBillingCutoff", Map.of(tenantUuid.toString(), tenantBillingCutoffEntry)); + Map claims = new LinkedHashMap<>(); + claims.put("iss", ACCOUNT_ISSUER); + claims.put("aud", "gameplay-connect"); + claims.put("iat", now.subtract(one)); + claims.put("exp", now.add(BigInteger.valueOf(20))); + claims.put("jti", tokenIdentity); + claims.put("accountId", accountUuid.toString()); + claims.put("tenantId", tenantUuid.toString()); + claims.put("realmId", UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb").toString()); + claims.put("worldSlug", "world"); + claims.put("realmSlug", "realm"); + claims.put( + "playableStateNamespaceId", + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc").toString()); + claims.put("playableStateScope", "PLAYABLE_STATE_SCOPE_SHARED"); + claims.put( + "gameInstanceId", UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString()); + claims.put("pointerVersion", one); + claims.put("catalogRevision", one); + claims.put("connectScopeId", identity.connectScopeId()); + claims.put("requestId", identity.requestId()); + claims.put("authorityTuple", authorityTuple); + claims.put("membershipVersion", tenantGeneration); + claims.put("replayAdmissionFence", one); + return claims; + } + + private static byte[] signAccountJwt(Map claims, String keyId, KeyPair signer) + throws Exception { + String header = "{\"alg\":\"EdDSA\",\"kid\":\"" + keyId + "\",\"typ\":\"JWT\"}"; + String encodedHeader = BASE64_URL.encodeToString(header.getBytes(StandardCharsets.US_ASCII)); + String encodedPayload = BASE64_URL.encodeToString(JSON.writeValueAsBytes(claims)); + String signingInput = encodedHeader + "." + encodedPayload; + Signature signature = Signature.getInstance("Ed25519"); + signature.initSign(signer.getPrivate()); + signature.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + return (signingInput + "." + BASE64_URL.encodeToString(signature.sign())) + .getBytes(StandardCharsets.US_ASCII); + } + + private static ResolveLegacyAccountTenantAssociationResponse approvedAssociation( + String sourceEvidenceDigest, UUID tenantUuid) { + return ResolveLegacyAccountTenantAssociationResponse.newBuilder() + .setLegacyAccountTenantId(LEGACY_TENANT_ID) + .setCanonicalTenantId(tenantUuid.toString()) + .setSourceLegacyGameTenantId("legacy-game-source-reader") + .setSourceGameRowId(7L) + .setAccountEvidenceDigest(sourceEvidenceDigest) + .setOperationId(UUID.randomUUID().toString()) + .setManifestDigest("sha256:" + "b".repeat(64)) + .setManifestSignature(Base64.getEncoder().encodeToString(new byte[64])) + .setTargetNamespace(WORKLOAD_NAMESPACE) + .setSignerKeyId("game-design-owner-test") + .setApprovedBy("owner@example.test") + .setApprovalReference("committed-connect-source-test") + .setSignedAt("2026-10-01T00:00:00Z") + .setOperationEntryCount(1) + .setManifestSchemaVersion(1) + .build(); + } + + private static long insertRetainedRows(DSLContext dsl, long tenantId, String username) { + Number inserted = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash, tenant_id) " + + "VALUES (?, ?, 'hash', ?) RETURNING id", + username, + username + "@example.test", + tenantId) + .fetchOne(0, Number.class), + "Account insertion did not return an identifier"); + long accountId = inserted.longValue(); + if (accountId <= 0L) { + throw new IllegalStateException("Account insertion returned a non-positive identifier"); + } + dsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed) VALUES (?, ?, TRUE)", + accountId, + tenantId); + dsl.execute("INSERT INTO profiles (account_id, tenant_id) VALUES (?, ?)", accountId, tenantId); + return accountId; + } + + private static int requirePositiveBackendPid(DSLContext dsl) { + Integer backendPid = + Objects.requireNonNull( + dsl.resultQuery("SELECT pg_backend_pid()").fetchOne(0, Integer.class), + "PostgreSQL did not return a backend PID"); + if (backendPid <= 0) { + throw new IllegalStateException("PostgreSQL returned a non-positive backend PID"); + } + return backendPid; + } + + private static Snapshot sourceSnapshot( + PreparedAccount prepared, AccountConnectTokenIssuanceIdentity identity) { + String scopeHash = AccountJoinDigest.tokenHash(identity.connectScopeId()); + Record row = + prepared + .db() + .dsl() + .resultQuery( + "SELECT operation_id, status, updated_at::text, " + + "(SELECT count(*) FROM account_connect_token_response_envelopes e " + + "WHERE e.operation_id = o.operation_id) " + + "FROM account_connect_token_issuance_operations o " + + "WHERE account_id = ? AND tenant_id = ? AND connect_scope_hash = ? AND request_id = ?", + identity.accountId(), + identity.tenantId(), + scopeHash, + identity.requestId()) + .fetchOne(); + return row == null + ? new Snapshot(null, null, null, 0L) + : new Snapshot( + row.get(0, UUID.class), + row.get(1, String.class), + row.get(2, String.class), + row.get(3, Long.class)); + } + + private static boolean awaitAccountFenceBlock( + DSLContext dsl, int readerBackendPid, int blockerBackendPid, Duration timeout) + throws InterruptedException { + long deadline = System.nanoTime() + timeout.toNanos(); + while (System.nanoTime() < deadline) { + Boolean blocked = + dsl.resultQuery( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity waiting " + + "WHERE waiting.pid = ? " + + "AND waiting.wait_event_type = 'Lock' " + + "AND waiting.query ILIKE '%for update%' " + + "AND ? = ANY(pg_blocking_pids(waiting.pid)))", + readerBackendPid, blockerBackendPid) + .fetchOne(0, Boolean.class); + if (Boolean.TRUE.equals(blocked)) { + return true; + } + Thread.sleep(10L); + } + return false; + } + + private static boolean await(CountDownLatch latch, long timeout, TimeUnit unit) { + try { + return latch.await(timeout, unit); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + return false; + } + } + + private static void assertReadRejected( + PreparedAccount prepared, + SourceFixture source, + Class exceptionType, + String messageFragment) { + assertReadRejected(prepared.reader(), prepared, source, exceptionType, messageFragment); + } + + private static void assertReadRejected( + AccountCommittedConnectSourceReader reader, + PreparedAccount prepared, + SourceFixture source, + Class exceptionType, + String messageFragment) { + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> reader.read(source.identity(), source.gatewayEnvelope())))) + .isInstanceOf(exceptionType) + .hasMessageContaining(messageFragment); + } + + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { + Context scoped = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = scoped.attach(); + try { + return action.get(); + } finally { + scoped.detach(previous); + } + } + + private static T withoutPeer(Supplier action) { + Context previous = Context.ROOT.attach(); + try { + return action.get(); + } finally { + Context.ROOT.detach(previous); + } + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static byte[] digest(String value) { + return sha256(value.getBytes(StandardCharsets.UTF_8)); + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (Exception exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static T inTransaction(TransactionTemplate transaction, Supplier work) { + return transaction.execute(status -> work.get()); + } + + private enum SourceState { + ABSENT, + PENDING, + COMMITTED, + FAILED + } + + private record SourceOptions( + boolean unknownSourceKey, + boolean wrongHash, + boolean wrongJti, + boolean wrongTarget, + boolean unknownGatewayKey, + boolean shortGatewayDeadline, + boolean unmappedTenant) { + private static final SourceOptions NORMAL = + new SourceOptions(false, false, false, false, false, false, false); + } + + private record TestContext( + DSLContext dsl, + TransactionTemplate transaction, + AccountConnectTokenIssuanceRepository issuanceRepository, + AccountEnvelopeCrypto envelopeCrypto) {} + + private record PreparedAccount( + TestContext db, + long accountId, + long tenantId, + UUID accountUuid, + UUID tenantUuid, + KeyPair accountKeyPair, + KeyPair unknownAccountKeyPair, + KeyPair gatewayKeyPair, + KeyPair unknownGatewayKeyPair, + AccountGameplayConnectSourceVerifier verifier, + Map gatewayKeys, + AccountRepository accountRepository, + AccountTenantIdentityResolver tenantResolver, + AccountJoinOperationRepository joinRepository, + AccountCommittedConnectSourceReader reader, + TestClock clock) {} + + private record SourceFixture( + AccountConnectTokenIssuanceIdentity identity, + String gatewayEnvelope, + Map sourceClaims, + Map gatewayClaims, + String tokenIdentity) {} + + private record Snapshot(UUID operationId, String status, String updatedAt, long envelopeCount) {} + + private static final class TestClock extends Clock { + private volatile Instant now; + private final ZoneId zone; + + private TestClock(Instant initial) { + this(initial, ZoneOffset.UTC); + } + + private TestClock(Instant initial, ZoneId zone) { + now = initial; + this.zone = zone; + } + + private void advance(Duration duration) { + now = now.plus(duration); + } + + @Override + public ZoneId getZone() { + return zone; + } + + @Override + public Clock withZone(ZoneId zone) { + return new TestClock(now, zone); + } + + @Override + public Instant instant() { + return now; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java new file mode 100644 index 0000000000..546a4a97fd --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java @@ -0,0 +1,420 @@ +package unit.net.firedevops.firemud.accountservice.security; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AccountGameplayConnectSourceVerifierTest { + private static final String ISSUER = "https://account.example.test"; + private static final String RSA_KID = "account-rsa-current"; + private static final String ED_KID = "account-ed-current"; + private static final int MAX_COMPACT_JWT_BYTES = 16 * 1024; + private static final Instant NOW = Instant.parse("2026-04-06T12:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final long NOW_SECONDS = NOW.getEpochSecond(); + private static final String ACCOUNT_ID = "00000000-0000-4000-8000-000000000001"; + private static final String TENANT_ID = "00000000-0000-4000-8000-000000000002"; + private static final String REALM_ID = "00000000-0000-4000-8000-000000000003"; + private static final String GAME_INSTANCE_ID = "00000000-0000-4000-8000-000000000004"; + private static final String NAMESPACE_ID = "00000000-0000-4000-8000-000000000005"; + private static final String TEST_LIFECYCLE_ID = "00000000-0000-4000-8000-000000000006"; + private static final BigInteger LARGE_ACCOUNT_GENERATION = + new BigInteger("123456789012345678901234567890"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private KeyPair rsaKeyPair; + private KeyPair edKeyPair; + + @BeforeEach + void setUp() throws Exception { + KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); + rsa.initialize(2048); + rsaKeyPair = rsa.generateKeyPair(); + edKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + } + + @Test + void verifiesRsaSourceAndPreservesExactDeeplyImmutableClaims() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + String compactJwt = sign(claims, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()); + + Map verified = verifier().verify(compactJwt); + + assertEquals(ISSUER, verified.get("iss")); + assertEquals("gameplay-connect", verified.get("aud")); + assertEquals(BigInteger.valueOf(NOW_SECONDS - 1), verified.get("iat")); + assertEquals(BigInteger.valueOf(NOW_SECONDS + 29), verified.get("exp")); + assertEquals( + BigInteger.valueOf(19), + verified.get("membershipVersion") instanceof Map map ? map.get(TENANT_ID) : null); + assertEquals( + LARGE_ACCOUNT_GENERATION, + ((Map) verified.get("authorityTuple")).get("accountAuthorityGeneration")); + assertFalse(verified.containsKey("rawJWT")); + assertFalse(verified.containsValue(compactJwt)); + + assertThrows(UnsupportedOperationException.class, () -> verified.put("extra", "value")); + Map tuple = objectMap(verified.get("authorityTuple")); + assertThrows(UnsupportedOperationException.class, () -> tuple.put("extra", "value")); + Map tenantGenerations = objectMap(tuple.get("tenantAuthorityGeneration")); + assertThrows( + UnsupportedOperationException.class, + () -> tenantGenerations.put(TENANT_ID, BigInteger.TEN)); + Map billingCutoffs = objectMap(tuple.get("tenantBillingCutoff")); + Map tenantCutoff = objectMap(billingCutoffs.get(TENANT_ID)); + assertThrows( + UnsupportedOperationException.class, + () -> tenantCutoff.put("outboxSequence", BigInteger.TEN)); + } + + @Test + void verifiesEd25519SourceAndOptionalProtectedHeaderType() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + String compactJwt = sign(claims, "EdDSA", ED_KID, null, edKeyPair.getPrivate()); + AccountGameplayConnectSourceVerifier verifier = + new AccountGameplayConnectSourceVerifier( + ISSUER, Map.of(ED_KID, edKeyPair.getPublic()), MAX_COMPACT_JWT_BYTES, CLOCK); + + assertEquals("request-1", verifier.verify(compactJwt).get("requestId")); + } + + @Test + void rejectsRsaVerificationKeysBelow2048BitsAtConstruction() throws Exception { + KeyPairGenerator weakRsa = KeyPairGenerator.getInstance("RSA"); + weakRsa.initialize(1024); + KeyPair weakKeyPair = weakRsa.generateKeyPair(); + + IllegalArgumentException failure = + assertThrows( + IllegalArgumentException.class, + () -> + new AccountGameplayConnectSourceVerifier( + ISSUER, + Map.of("account-rsa-weak", weakKeyPair.getPublic()), + MAX_COMPACT_JWT_BYTES, + CLOCK)); + + assertEquals("Account verification key registry is invalid", failure.getMessage()); + } + + @Test + void acceptsLifecycleBoundNonPublicTargetAndKeepsGrantValuesImmutable() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + claims.put("realmSlug", "preview"); + claims.put("playtestLifecycleId", TEST_LIFECYCLE_ID); + claims.put("playtestStateGeneration", BigInteger.valueOf(3)); + Map tuple = objectMap(claims.get("authorityTuple")); + tuple.put( + "privateRealmGrantVersions", + List.of( + Map.of( + "tenantId", + TENANT_ID, + "worldSlug", + "emberfall", + "realmSlug", + "preview", + "playtestLifecycleId", + TEST_LIFECYCLE_ID, + "grantVersion", + BigInteger.valueOf(7)))); + String compactJwt = sign(claims, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()); + + Map verified = verifier().verify(compactJwt); + + Map verifiedTuple = objectMap(verified.get("authorityTuple")); + List grants = (List) verifiedTuple.get("privateRealmGrantVersions"); + assertThrows(UnsupportedOperationException.class, grants::clear); + Map grant = objectMap(grants.getFirst()); + assertThrows( + UnsupportedOperationException.class, () -> grant.put("grantVersion", BigInteger.TEN)); + } + + @Test + void rejectsUnknownKidWrongSignatureAndWrongIssuerWithOneSanitizedFailure() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + String unknownKid = sign(claims, "RS256", "other-account-key", "JWT", rsaKeyPair.getPrivate()); + KeyPair wrongPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); + String wrongSignature = sign(claims, "RS256", RSA_KID, "JWT", wrongPair.getPrivate()); + Map wrongIssuerClaims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + wrongIssuerClaims.put("iss", "https://other-account.example.test"); + String wrongIssuer = sign(wrongIssuerClaims, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()); + + assertSanitizedFailure(unknownKid); + assertSanitizedFailure(wrongSignature); + assertSanitizedFailure(wrongIssuer); + } + + @Test + void rejectsExpiredFutureAndOverlongSourceTimesBeforeProjection() throws Exception { + Map expired = sourceClaims(NOW_SECONDS - 5, NOW_SECONDS); + Map future = sourceClaims(NOW_SECONDS + 6, NOW_SECONDS + 20); + Map overlong = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 30); + + assertSanitizedFailure(sign(expired, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + assertSanitizedFailure(sign(future, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + assertSanitizedFailure(sign(overlong, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + } + + @Test + void rejectsNonCanonicalMalformedAndOversizedCompactJwts() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + String compactJwt = sign(claims, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()); + String[] segments = compactJwt.split("\\.", -1); + + assertSanitizedFailure(null); + assertSanitizedFailure("one.two"); + assertSanitizedFailure(compactJwt + ".fourth"); + assertSanitizedFailure(segments[0] + "=." + segments[1] + "." + segments[2]); + AccountGameplayConnectSourceVerifier tinyLimitVerifier = + new AccountGameplayConnectSourceVerifier( + ISSUER, Map.of(RSA_KID, rsaKeyPair.getPublic()), 8, CLOCK); + assertSanitizedFailure(tinyLimitVerifier, compactJwt); + } + + @Test + void rejectsDuplicateAndUnregisteredProtectedHeaderFields() throws Exception { + String payload = JSON.writeValueAsString(sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29)); + String duplicateKidHeader = + "{\"alg\":\"RS256\",\"kid\":\"" + + RSA_KID + + "\",\"kid\":\"" + + RSA_KID + + "\",\"typ\":\"JWT\"}"; + String remoteKeyHeader = + "{\"alg\":\"RS256\",\"kid\":\"" + + RSA_KID + + "\",\"typ\":\"JWT\",\"jku\":\"https://attacker.invalid/keys\"}"; + String criticalHeader = + "{\"alg\":\"RS256\",\"kid\":\"" + RSA_KID + "\",\"typ\":\"JWT\",\"crit\":[]}"; + String embeddedKeyHeader = + "{\"alg\":\"RS256\",\"kid\":\"" + RSA_KID + "\",\"typ\":\"JWT\",\"jwk\":{\"kty\":\"RSA\"}}"; + + assertSanitizedFailure( + signRaw(duplicateKidHeader, payload, "SHA256withRSA", rsaKeyPair.getPrivate())); + assertSanitizedFailure( + signRaw(remoteKeyHeader, payload, "SHA256withRSA", rsaKeyPair.getPrivate())); + assertSanitizedFailure( + signRaw(criticalHeader, payload, "SHA256withRSA", rsaKeyPair.getPrivate())); + assertSanitizedFailure( + signRaw(embeddedKeyHeader, payload, "SHA256withRSA", rsaKeyPair.getPrivate())); + } + + @Test + void rejectsDuplicateClaimsExtraFieldsWrongProfileAndMalformedNumericValues() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + String validPayload = JSON.writeValueAsString(claims); + String duplicateClaimPayload = + validPayload.replaceFirst( + "\"iss\":\"[^\"]+\",", "\"iss\":\"" + ISSUER + "\",\"iss\":\"" + ISSUER + "\","); + assertSanitizedFailure( + signRaw( + canonicalHeader(RSA_KID, "RS256", "JWT"), + duplicateClaimPayload, + "SHA256withRSA", + rsaKeyPair.getPrivate())); + + Map extra = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + extra.put("rawJWT", "must-not-escape"); + assertSanitizedFailure(sign(extra, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + + Map otherProfile = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + otherProfile.put("aud", "player-bootstrap"); + assertSanitizedFailure(sign(otherProfile, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + + Map stringCounter = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + Map stringTuple = objectMap(stringCounter.get("authorityTuple")); + stringTuple.put("tenantAuthorityGeneration", new LinkedHashMap<>(Map.of(TENANT_ID, "13"))); + assertSanitizedFailure(sign(stringCounter, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + + Map fractionalTime = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + fractionalTime.put("iat", new BigDecimal(NOW_SECONDS - 1 + ".0")); + assertSanitizedFailure(sign(fractionalTime, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + } + + @Test + void rejectsSelectedTargetAndMembershipMapChanges() throws Exception { + Map wrongTenant = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + wrongTenant.put("tenantId", "00000000-0000-4000-8000-000000000099"); + + Map wrongMembershipKey = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + wrongMembershipKey.put( + "membershipVersion", + Map.of("00000000-0000-4000-8000-000000000099", BigInteger.valueOf(19))); + + assertSanitizedFailure(sign(wrongTenant, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + assertSanitizedFailure( + sign(wrongMembershipKey, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); + } + + @Test + void rejectsAlgorithmAndKeyTypeMismatchAndNoneOrHmacAlgorithms() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); + String payload = JSON.writeValueAsString(claims); + String rsaWithEdAlgorithm = + signRaw( + canonicalHeader(RSA_KID, "EdDSA", "JWT"), + payload, + "SHA256withRSA", + rsaKeyPair.getPrivate()); + String none = + signRaw( + canonicalHeader(RSA_KID, "none", "JWT"), + payload, + "SHA256withRSA", + rsaKeyPair.getPrivate()); + String hmac = + signRaw( + canonicalHeader(RSA_KID, "HS256", "JWT"), + payload, + "SHA256withRSA", + rsaKeyPair.getPrivate()); + + assertSanitizedFailure(rsaWithEdAlgorithm); + assertSanitizedFailure(none); + assertSanitizedFailure(hmac); + } + + private AccountGameplayConnectSourceVerifier verifier() { + return new AccountGameplayConnectSourceVerifier( + ISSUER, Map.of(RSA_KID, rsaKeyPair.getPublic()), MAX_COMPACT_JWT_BYTES, CLOCK); + } + + private void assertSanitizedFailure(String compactJwt) { + assertSanitizedFailure(verifier(), compactJwt); + } + + private void assertSanitizedFailure( + AccountGameplayConnectSourceVerifier verifier, String compactJwt) { + IllegalArgumentException failure = + assertThrows(IllegalArgumentException.class, () -> verifier.verify(compactJwt)); + assertEquals("invalid Account gameplay-connect source JWT", failure.getMessage()); + assertNull(failure.getCause()); + if (compactJwt != null) { + assertFalse(failure.getMessage().contains(compactJwt)); + } + } + + private static Map sourceClaims(long issuedAt, long expiresAt) { + Map claims = new LinkedHashMap<>(); + claims.put("iss", ISSUER); + claims.put("aud", "gameplay-connect"); + claims.put("iat", BigInteger.valueOf(issuedAt)); + claims.put("exp", BigInteger.valueOf(expiresAt)); + claims.put("jti", "connect-jti-1"); + claims.put("accountId", ACCOUNT_ID); + claims.put("tenantId", TENANT_ID); + claims.put("realmId", REALM_ID); + claims.put("worldSlug", "emberfall"); + claims.put("realmSlug", "public-production"); + claims.put("playableStateNamespaceId", NAMESPACE_ID); + claims.put("playableStateScope", "PLAYABLE_STATE_SCOPE_SHARED"); + claims.put("gameInstanceId", GAME_INSTANCE_ID); + claims.put("pointerVersion", BigInteger.valueOf(23)); + claims.put("catalogRevision", BigInteger.valueOf(41)); + claims.put("connectScopeId", "scope-1"); + claims.put("requestId", "request-1"); + claims.put("authorityTuple", authorityTuple()); + claims.put("membershipVersion", Map.of(TENANT_ID, BigInteger.valueOf(19))); + claims.put("replayAdmissionFence", BigInteger.valueOf(29)); + return claims; + } + + private static Map authorityTuple() { + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", BigInteger.valueOf(2)); + tuple.put("accountAuthorityGeneration", LARGE_ACCOUNT_GENERATION); + tuple.put("tenantAuthorityGeneration", Map.of(TENANT_ID, BigInteger.valueOf(13))); + tuple.put("membershipAuthorityGeneration", Map.of(TENANT_ID, BigInteger.valueOf(17))); + tuple.put("privateRealmGrantVersions", List.of()); + tuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + LARGE_ACCOUNT_GENERATION, + "outboxStreamKey", + "account:auth-authority:v1:account/" + ACCOUNT_ID, + "outboxSequence", + BigInteger.valueOf(31))); + tuple.put( + "tenantBillingCutoff", + Map.of( + TENANT_ID, + Map.of( + "tenantAuthorityGeneration", BigInteger.valueOf(13), + "tenantBillingSequence", BigInteger.valueOf(5), + "outboxStreamKey", "account:auth-authority:v1:tenant/" + TENANT_ID, + "outboxSequence", BigInteger.valueOf(37)))); + return tuple; + } + + private static String sign( + Map claims, + String algorithm, + String kid, + String type, + java.security.PrivateKey privateKey) + throws Exception { + String header = canonicalHeader(kid, algorithm, type); + String payload = JSON.writeValueAsString(claims); + String jcaAlgorithm = + switch (algorithm) { + case "RS256" -> "SHA256withRSA"; + case "RS384" -> "SHA384withRSA"; + case "RS512" -> "SHA512withRSA"; + case "EdDSA" -> "Ed25519"; + default -> "SHA256withRSA"; + }; + return signRaw(header, payload, jcaAlgorithm, privateKey); + } + + private static String signRaw( + String header, String payload, String jcaAlgorithm, java.security.PrivateKey privateKey) + throws Exception { + String protectedSegment = encode(header.getBytes(StandardCharsets.UTF_8)); + String payloadSegment = encode(payload.getBytes(StandardCharsets.UTF_8)); + byte[] signingInput = + (protectedSegment + "." + payloadSegment).getBytes(StandardCharsets.US_ASCII); + Signature signer = Signature.getInstance(jcaAlgorithm); + signer.initSign(privateKey); + signer.update(signingInput); + return protectedSegment + "." + payloadSegment + "." + encode(signer.sign()); + } + + private static String canonicalHeader(String kid, String algorithm, String type) { + if (type == null) { + return "{\"alg\":\"" + algorithm + "\",\"kid\":\"" + kid + "\"}"; + } + return "{\"alg\":\"" + algorithm + "\",\"kid\":\"" + kid + "\",\"typ\":\"" + type + "\"}"; + } + + private static String encode(byte[] value) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(value); + } + + @SuppressWarnings("unchecked") + private static Map objectMap(Object value) { + assertInstanceOf(Map.class, value); + return (Map) value; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java new file mode 100644 index 0000000000..4952b4afcf --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java @@ -0,0 +1,156 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import java.security.KeyPairGenerator; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Map; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountCommittedConnectSourceReaderGuardTest { + private static final String WORKLOAD_NAMESPACE = "account-unit"; + private static final AccountConnectTokenIssuanceIdentity IDENTITY = + new AccountConnectTokenIssuanceIdentity(101L, 202L, "connect-scope-1", "request-1"); + private static final Clock CLOCK = + Clock.fixed(Instant.parse("2026-04-06T12:00:00Z"), ZoneOffset.UTC); + + private AccountConnectTokenIssuanceRepository issuanceRepository; + private AccountRepository accountRepository; + private AccountTenantIdentityResolver tenantIdentityResolver; + private AccountJoinOperationRepository joinOperationRepository; + private AccountEnvelopeCrypto envelopeCrypto; + private AccountGameplayConnectSourceVerifier sourceVerifier; + private AccountCommittedConnectSourceReader reader; + private GrpcPeerIdentity expectedGameSessionPeer; + + @BeforeEach + void setUp() throws Exception { + issuanceRepository = mock(AccountConnectTokenIssuanceRepository.class); + accountRepository = mock(AccountRepository.class); + tenantIdentityResolver = mock(AccountTenantIdentityResolver.class); + joinOperationRepository = mock(AccountJoinOperationRepository.class); + envelopeCrypto = mock(AccountEnvelopeCrypto.class); + sourceVerifier = mock(AccountGameplayConnectSourceVerifier.class); + expectedGameSessionPeer = peer(WORKLOAD_NAMESPACE, "game-session-service"); + + var gatewayKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair().getPublic(); + reader = + new AccountCommittedConnectSourceReader( + issuanceRepository, + accountRepository, + tenantIdentityResolver, + joinOperationRepository, + envelopeCrypto, + sourceVerifier, + Map.of("gateway-test", gatewayKey), + CLOCK, + WORKLOAD_NAMESPACE); + } + + @Test + void missingPeerIsDeniedBeforeAnyRepositoryOrCredentialInteraction() { + AdminAuthorizationException failure = + assertThrows( + AdminAuthorizationException.class, + () -> withoutPeer(() -> reader.read(IDENTITY, "unparsed-gateway-context"))); + + assertEquals( + "Committed Account source readback requires the exact Game Session workload identity", + failure.getMessage()); + verifyNoCollaboratorInteractions(); + } + + @Test + void wrongServicePeerIsDeniedBeforeAnyRepositoryOrCredentialInteraction() { + assertPeerDeniedBeforeInteractions(peer(WORKLOAD_NAMESPACE, "world-management-service")); + } + + @Test + void wrongNamespaceGameSessionPeerIsDeniedBeforeAnyRepositoryOrCredentialInteraction() { + assertPeerDeniedBeforeInteractions(peer("other-account-unit", "game-session-service")); + } + + @Test + void exactPeerWithoutOwnerTransactionIsDeniedBeforeAnyRepositoryOrCredentialInteraction() { + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> + withPeer( + expectedGameSessionPeer, + () -> reader.read(IDENTITY, "unparsed-gateway-context"))); + + assertEquals( + "Committed Account source readback requires an active owner transaction", + failure.getMessage()); + verifyNoCollaboratorInteractions(); + } + + private void assertPeerDeniedBeforeInteractions(GrpcPeerIdentity peer) { + AdminAuthorizationException failure = + assertThrows( + AdminAuthorizationException.class, + () -> withPeer(peer, () -> reader.read(IDENTITY, "unparsed-gateway-context"))); + + assertEquals( + "Committed Account source readback requires the exact Game Session workload identity", + failure.getMessage()); + verifyNoCollaboratorInteractions(); + } + + private void verifyNoCollaboratorInteractions() { + verifyNoInteractions( + issuanceRepository, + accountRepository, + tenantIdentityResolver, + joinOperationRepository, + envelopeCrypto, + sourceVerifier); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { + Context scoped = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = scoped.attach(); + try { + return action.get(); + } finally { + scoped.detach(previous); + } + } + + private static T withoutPeer(Supplier action) { + Context previous = Context.ROOT.attach(); + try { + return action.get(); + } finally { + Context.ROOT.detach(previous); + } + } +}