diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fc1ecea704..024cb56a6b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -987,8 +987,19 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#lostAcknowledgementExactRetryReturnsSameOriginalOperationAndBytesWithoutMutation()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#rollbackLeavesNoAssociationClaimAndNewAttemptSucceeds()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#concurrentExactFirstWritersReturnSameImmutableReceipt()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#retainedKeyLookupReturnsHistoricalUuidOnlyForExactNamespaceAndKey()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#retainedKeyLookupRejectsMalformedAndContradictoryPersistedRows()' \ game-session-service + - name: Upload Game Session retained tenant UUID PostgreSQL proof results + if: ${{ always() && matrix.module == 'game-session-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-session-retained-tenant-uuid-postgresql-proof-${{ github.sha }} + path: services/game-session-service/build/test-results/integrationTest/TEST-integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Run Game Session management owner UUID PostgreSQL component proof if: ${{ matrix.module == 'game-session-service' }} run: | diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 1d69980802..5a6f92d8c3 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -18,6 +18,8 @@ The sections below define the target-state runtime contract. Current implementat - Game Session's Account carriers validate and preserve canonical non-nil UUIDs under the [Identifier Glossary](../../system-architecture-identifier-glossary.md#identifier-format-conventions), including sessions, Account-qualified client requests and presence. Unreadable older session/presence records fail closed without deleting their retained values. This is boundary validation, not Account authorization or an authenticated retained-row mapping. Tenant/catalog carriers, cross-owner UUID support and complete signed-context proof remain unfinished; the Account runtime RPC and first-party credential paths remain denied. Component and runtime proof are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). +- `PLAY` resolves a retained catalog tenant key only through Game Session's immutable, approved association under its exact configured workload namespace, then carries that canonical tenant UUID through Account entitlement, membership and grant requests and matching response predicates. Missing configuration, missing associations or contradictory retained evidence deny before admission; the resolver performs no registration or repair. This read-only consequence does not wire the audited association importer, fresh runtime catalog enrollment or complete Account authority. Those activation and proof gates remain open in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). + - The unwired Game Session tenant-source client and authored-world intake implementation are packaged in successor [#2923](https://github.com/benhook1013/FireMUD/pull/2923); the prerequisite producer remains in #2915. They consume the separate [Game Design tenant-source read](../game-design-service/api-contracts.md#runtime-tenant-identity-read-for-game-session), requiring file-backed workload mTLS and exact namespace, request and canonical UUID echoes before returning typed provenance. That source read proves neither a retained Game Session numeric-key association nor catalog enrollment, a realm/namespace, a runtime target or admission. Game Session remains the sole persister of its resolved catalog and pointer; canonical UUID intake and propagation into those current numeric carriers remain required before the denied first-party paths can activate. Exact proof and activation limits remain in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). - The current effective-settings HTTP read is admitted by the service-wide `PRIVILEGED` role requirement, whose shared classifier accepts any global privileged role or any tenant-scoped `tenantAdmin`/`moderator` claim. `EffectiveSettingsController` then trusts query tenant/game selectors and session ids: it can synthesize a requested tenant scope without binding it to the caller's scoped role, or resolve a persisted session without checking that its tenant is authorized by the caller. The current controller/integration tests do not prove denial of a tenant-A caller reading tenant-B settings. 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 7a02c609fe..281df34707 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The retained Game Session tenant-UUID consumer candidate normally incorporates Account password-reset source #2933 `aa22f67be628748205414b954041cd003570d84b`. `PLAY` resolves only the exact workload-namespace/private-key association from an immutable owner-approved receipt, cross-reads its operation, request, canonical UUID and retained key, then uses that UUID in Account entitlement, membership and realm-grant requests and response comparisons. Missing configuration, missing association, nil or contradictory evidence denies without importer, roster or admission mutation. The full composed Account/Common Platform/Game Session checks, both service JARs, formatting/static analysis, links and Markdown passed166tasks(55executed/25from-cache/86up-to-date). Game Session newly executed1,806unit,18non-PostgreSQL integration and1cross-service cases without failures/errors;17unit/137integration/33cross-service cases skipped. Its eleven retained-association PostgreSQL cases, including the two new lookup cases, compiled but skipped without Docker. Account526unit/167skipped PostgreSQL and Common Platform133unit results were reused from cache, not newly executed in this composed run. Normal ancestry preserves the complete Account/Common Platform parent subtree and all original Game Session candidate hunks byte-for-byte. This corrects the numeric tenant request boundary, not audited importer/source registration, fresh runtime catalog enrollment, complete typed entitlement/grant evidence, UUID-aware Game Logic/Social/moderation consumers, authenticated positive transport proof or runtime activation. The membership RPC, credential paths and Account ring mount remain denied. + The Account password-reset source candidate uses the closed `account-auth-password-reset-event/v1` codec and V41 immutable operation receipts. It locks and re-reads the provenance-backed Account/source identity before consuming the existing one-use token, then commits the password verifier, Account generation/source-version and local-fence advances, event/checkpoint and receipt together. Exact retry proves the unchanged verifier and submitted password against the original immutable receipt/event without a second mutation; changed caller input conflicts, while a superseded verifier fails closed. Missing source enrollment or contradictory history is denied rather than repaired. Local consolidated Account/Common Platform checks, Account JAR, Java formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed. Account executed526unit cases without skips/failures/errors; Common Platform executed133cases in the preceding same-code gate, including six shared codec/vector cases. The final dependency-only check reused the Account unit result from cache rather than executing it again. All167Account PostgreSQL cases compiled but skipped without Docker, including the six new producer cases; the two existing application cases now prove concurrent exact recovery and whole-operation rollback when executed. The real PostgreSQL token-hash primary key remains enforced, with only its unsupported binary-index declaration excluded from the jOOQ/H2 code-generation model. Test readback/null and username/index defects were corrected without suppressions or guard weakening; the integration analysis dependency now resolves its required annotation. Delivery, source and recipient authentication/readback, projections, active-binding revocation and live execution remain required pre-v1 work; this slice enables none of the denied membership RPC, credential, catalog or ring-mount paths. Authentication owns the event schema and source/recipient boundary; Account API Contracts owns reset identity and exact retry. The accepted issuer-projection contract allows exact issuer-scoped source/checkpoint evidence for projection bootstrap, advancement, and duplicate verification; this Account-local password-reset producer does not implement the issuer projection or recipient readback required for admission and rebind. The gameplay Account-UUID carrier is published as [#2932](https://github.com/benhook1013/FireMUD/pull/2932), based on #2929 `67dd8be6b3ef9d886e4b1dd26ec719cf9e29e4b3`. Exact-head [CI 36933819297](https://github.com/benhook1013/FireMUD/actions/runs/36933819297) on `05313dc921aafe4b09b9c2b2649b2097bdc9892d` passed the full Account job and executed 124 listed strict Account cases without skips, failures or errors. Six early Game Session PostgreSQL gates executed 24 cases cleanly; its wider job was canceled after 15 Communication WebSocket cross-service failures, and TCP cross-service logged 13 failures with its database verifier skipped. TCP artifacts show successful LOGIN followed by PLAY denial: Game Session supplies its numeric catalog tenant key where the Account client requires a canonical tenant UUID, so the call fails before the RPC. Resolving the owner-backed UUID association and carrying it through the complete request/response predicates remains required work; no inferred mapping or relaxed guard is permitted. These are component proofs, not complete gameplay admission or transport proof. The independent whole-carrier review accepted and corrected two retained-Redis defects: unreadable presence is preserved by removal, re-registration and index pruning, and unreadable first-party context produces controlled invalid-context denial without persisted-context fallback. All 172 focused presence/LOGIN/PLAY unit cases executed with zero skips, failures or errors; formatting, Checkstyle, SpotBugs and documentation checks passed. Corrected-head CI, retained-Redis runtime and complete transport proof remain open. Game Logic/Social numeric sender/storage, Entity actor ownership, moderation consumers, complete Account authority and authenticated admission remain required owner work; no numeric aliases are inferred. Runtime activation, the membership RPC and Account ring mount remain denied. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java index 3f25a3c89e..f077813304 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java @@ -337,7 +337,7 @@ private GetTenantMembershipForRuntimeResponse membershipAuthorityUnavailable() { public GetTenantEntitlementsForRuntimeResponse getTenantEntitlementsForRuntime( String tenantId, String requestId) { - if (stub() == null) { + if (!AccountIds.isCanonicalNonNilUuid(tenantId) || stub() == null) { return entitlementAuthorityUnavailable(); } GetTenantEntitlementsForRuntimeRequest request = @@ -370,7 +370,9 @@ public GetTenantEntitlementsForRuntimeResponse getTenantEntitlementsForRuntime( public GetRealmAccessGrantForRuntimeResponse getRealmAccessGrantForRuntime( String accountId, String tenantId, String worldSlug, String realmSlug, String requestId) { - if (stub() == null) { + if (!AccountIds.isCanonicalNonNilUuid(accountId) + || !AccountIds.isCanonicalNonNilUuid(tenantId) + || stub() == null) { return realmAccessGrantUnavailable(); } GetRealmAccessGrantForRuntimeRequest request = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index f348441885..b84f5e938c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -37,6 +37,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.PositiveLongParsing; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -73,6 +74,7 @@ public class PlayCommandHandler { private final GameplayWorldCatalog gameplayWorldCatalog; private final GameLogicProperties gameLogicProperties; private final AccountClient accountClient; + private final RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver; private final EntityManagementClient entityManagementClient; private final ModerationPolicyClient moderationPolicyClient; private final FirstPartyConnectContextRegistry firstPartyConnectContextRegistry; @@ -89,6 +91,7 @@ public PlayCommandHandler( GameplayWorldCatalog gameplayWorldCatalog, GameLogicProperties gameLogicProperties, AccountClient accountClient, + RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver, EntityManagementClient entityManagementClient, ModerationPolicyClient moderationPolicyClient, FirstPartyConnectContextRegistry firstPartyConnectContextRegistry, @@ -109,6 +112,10 @@ public PlayCommandHandler( this.gameLogicProperties = Objects.requireNonNull(gameLogicProperties, "gameLogicProperties must not be null"); this.accountClient = Objects.requireNonNull(accountClient, "accountClient must not be null"); + this.retainedRuntimeTenantUuidResolver = + Objects.requireNonNull( + retainedRuntimeTenantUuidResolver, + "retainedRuntimeTenantUuidResolver must not be null"); this.entityManagementClient = Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); this.moderationPolicyClient = @@ -232,13 +239,21 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { if (connectScopeFailure.isPresent()) { return connectScopeFailure.get(); } + Optional canonicalTenantId = + retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(selectedRealm.tenantId()); + if (canonicalTenantId.isEmpty() + || !AccountIds.isCanonicalNonNilUuid(canonicalTenantId.orElseThrow().toString())) { + return authorityUnavailableFailure( + selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), 0L); + } Optional authorityFailure = validateRuntimeAdmission( context, selectedWorld, selectedRealm, selectedTenantTag, - selection.characterSelector()); + selection.characterSelector(), + canonicalTenantId.orElseThrow()); if (authorityFailure.isPresent()) { return authorityFailure.get(); } @@ -635,7 +650,8 @@ private Optional validateRuntimeAdmission( GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm, String tenantTag, - String requestedCharacter) { + String requestedCharacter, + UUID canonicalTenantId) { String requestId = context.sessionId() + ":" + UUID.randomUUID(); // This is only a denial-cleanup hint for an already bound runtime, never actor admission. long requestedCharacterId = @@ -644,8 +660,7 @@ private Optional validateRuntimeAdmission( ? context.characterId() : 0L; GetTenantEntitlementsForRuntimeResponse entitlementResponse = - accountClient.getTenantEntitlementsForRuntime( - Long.toString(selectedRealm.tenantId()), requestId); + accountClient.getTenantEntitlementsForRuntime(canonicalTenantId.toString(), requestId); Optional entitlementFailure = validateEntitlementsResponse( entitlementResponse, @@ -653,14 +668,20 @@ private Optional validateRuntimeAdmission( tenantTag, selectedWorld, selectedRealm, - requestedCharacterId); + requestedCharacterId, + canonicalTenantId.toString()); if (entitlementFailure.isPresent()) { return entitlementFailure; } GetTenantMembershipForRuntimeResponse membershipResponse = accountClient.getTenantMembershipForRuntime( - membershipPlayerContext(context, selectedRealm, requestedCharacterId, requestId)); + membershipPlayerContext( + context, + selectedRealm, + requestedCharacterId, + requestId, + canonicalTenantId.toString())); return validateMembershipResponse( membershipResponse, context, @@ -669,7 +690,8 @@ private Optional validateRuntimeAdmission( selectedRealm, requestedCharacterId, entitlementResponse.getAllowPublicJoin(), - requestId); + requestId, + canonicalTenantId.toString()); } private long requireResolvedCharacterId(String characterId) { @@ -707,7 +729,8 @@ private Optional validateMembershipResponse( GameplayWorldCatalog.RealmView selectedRealm, long requestedCharacterId, boolean allowPublicJoin, - String requestId) { + String requestId, + String canonicalTenantId) { Optional maybeError = extractError(response.getError()); if (maybeError.isPresent()) { if (!isAuthorityUnavailable(maybeError.orElseThrow())) { @@ -719,7 +742,8 @@ private Optional validateMembershipResponse( authorityUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } - if (!isSafeMembershipAuthorityResponse(response, context, selectedRealm, requestId)) { + if (!isSafeMembershipAuthorityResponse( + response, context, selectedRealm, canonicalTenantId, requestId)) { return Optional.of( authorityUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); @@ -769,7 +793,7 @@ private Optional validateMembershipResponse( GetRealmAccessGrantForRuntimeResponse grantResponse = accountClient.getRealmAccessGrantForRuntime( context.accountId(), - Long.toString(selectedRealm.tenantId()), + canonicalTenantId, selectedWorld.slug(), selectedRealm.slug(), requestId); @@ -779,6 +803,13 @@ private Optional validateMembershipResponse( authorityUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } + if (grantError.isEmpty() + && !isSafeRealmAccessGrantResponse( + grantResponse, context, canonicalTenantId, selectedWorld, selectedRealm)) { + return Optional.of( + authorityUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } if (grantError.isPresent() || !grantResponse.getGranted()) { return Optional.of( realmAccessDeniedFailure( @@ -1057,10 +1088,11 @@ private static PlayerExecutionContext membershipPlayerContext( SessionContext caller, GameplayWorldCatalog.RealmView target, long characterId, - String requestId) { + String requestId, + String canonicalTenantId) { return PlayerExecutionContext.newBuilder() .setAccountId(caller.accountId()) - .setTenantId(Long.toString(target.tenantId())) + .setTenantId(canonicalTenantId) .setRealmId(Objects.toString(target.realmId(), "")) .setPlayableStateNamespaceId(Objects.toString(target.playableStateNamespaceId(), "")) .setPlayableStateScope(Objects.toString(target.stateScope(), "")) @@ -1155,7 +1187,8 @@ private Optional validateEntitlementsResponse( String tenantTag, GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm, - long requestedCharacterId) { + long requestedCharacterId, + String canonicalTenantId) { Optional maybeError = extractError(response.getError()); if (maybeError.isPresent()) { if (isEntitlementUnavailable(maybeError.get())) { @@ -1172,7 +1205,7 @@ private Optional validateEntitlementsResponse( tenantBillingBlockedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); } - if (!isSafeEntitlementAuthorityResponse(response, selectedRealm)) { + if (!isSafeEntitlementAuthorityResponse(response, canonicalTenantId)) { return Optional.of( entitlementUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); @@ -1301,6 +1334,7 @@ private boolean isSafeMembershipAuthorityResponse( GetTenantMembershipForRuntimeResponse response, SessionContext context, GameplayWorldCatalog.RealmView selectedRealm, + String canonicalTenantId, String requestId) { if (!"AVAILABLE".equals(response.getAuthorityAvailability()) || !StringUtils.hasText(response.getAccountId()) @@ -1308,8 +1342,9 @@ private boolean isSafeMembershipAuthorityResponse( || !StringUtils.hasText(response.getEvaluatedAt()) || !AccountIds.isCanonicalNonNilUuid(response.getAccountId()) || !isCanonicalUuid(response.getTenantId()) + || !response.getTenantId().equals(canonicalTenantId) || !response.getRequestAccountId().equals(context.accountId()) - || !response.getRequestTenantId().equals(Long.toString(selectedRealm.tenantId())) + || !response.getRequestTenantId().equals(canonicalTenantId) || !response.getRequestId().equals(requestId)) { return false; } @@ -1326,25 +1361,38 @@ private boolean isSafeMembershipAuthorityResponse( } private boolean isSafeEntitlementAuthorityResponse( - GetTenantEntitlementsForRuntimeResponse response, - GameplayWorldCatalog.RealmView selectedRealm) { + GetTenantEntitlementsForRuntimeResponse response, String canonicalTenantId) { if (!StringUtils.hasText(response.getTenantId()) || !StringUtils.hasText(response.getEvaluatedAt()) || response.getEntitlementVersion() <= 0L) { return false; } try { - long tenantId = Long.parseLong(response.getTenantId()); Instant evaluatedAt = Instant.parse(response.getEvaluatedAt()); Instant now = Instant.now(); - return tenantId == selectedRealm.tenantId() + return isCanonicalUuid(response.getTenantId()) + && response.getTenantId().equals(canonicalTenantId) && !evaluatedAt.isAfter(now) && evaluatedAt.isAfter(now.minus(15, ChronoUnit.SECONDS)); - } catch (DateTimeParseException | NumberFormatException ex) { + } catch (DateTimeParseException ex) { return false; } } + private boolean isSafeRealmAccessGrantResponse( + GetRealmAccessGrantForRuntimeResponse response, + SessionContext context, + String canonicalTenantId, + GameplayWorldCatalog.WorldView selectedWorld, + GameplayWorldCatalog.RealmView selectedRealm) { + return AccountIds.isCanonicalNonNilUuid(response.getAccountId()) + && response.getAccountId().equals(context.accountId()) + && isCanonicalUuid(response.getTenantId()) + && response.getTenantId().equals(canonicalTenantId) + && response.getWorldSlug().equals(selectedWorld.slug()) + && response.getRealmSlug().equals(selectedRealm.slug()); + } + private void maybeRecordFreshEntryFallback( SessionContext context, GameplayWorldCatalog.RealmView selectedRealm, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/RetainedRuntimeTenantUuidResolverConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/RetainedRuntimeTenantUuidResolverConfiguration.java new file mode 100644 index 0000000000..34a42f6687 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/RetainedRuntimeTenantUuidResolverConfiguration.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.gamesession.config; + +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepository; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; + +/** Wires the immutable retained-association store only for the read-only runtime UUID resolver. */ +@Configuration(proxyBeanMethods = false) +public class RetainedRuntimeTenantUuidResolverConfiguration { + @Bean + public RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver( + DSLContext dsl, + GameSessionRetainedTenantSnapshotRepository snapshotRepository, + PlatformTransactionManager transactionManager, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + return RetainedRuntimeTenantUuidResolver.denyOnly(workloadNamespace); + } + GameSessionRetainedTenantAssociationRepository associationRepository = + new GameSessionRetainedTenantAssociationRepository( + dsl, snapshotRepository, workloadNamespace); + return new RetainedRuntimeTenantUuidResolver( + associationRepository, workloadNamespace, transactionManager); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java index c68a76c97e..be214f1811 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java @@ -227,6 +227,62 @@ public Optional read( return Optional.empty(); } + /** + * Reads the canonical tenant UUID for one positive retained Game Session tenant key. + * + *

The lookup is committed-outcome read-only. It validates the complete immutable receipt and + * confirms that the operation, request, canonical UUID, and retained key all cross-read to the + * same association row before returning the UUID. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readCanonicalTenantIdByRetainedTenantKey( + long legacyGameSessionTenantId, String exactNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalStateException("Game Session workload namespace is invalid"); + } + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Retained-tenant association read requires a committed-outcome owner read"); + } + requirePositive(legacyGameSessionTenantId, "legacyGameSessionTenantId"); + requireNamespace(exactNamespace); + if (!workloadNamespace.equals(exactNamespace)) { + throw new IllegalArgumentException( + "exactNamespace must match the configured Game Session workload namespace"); + } + + Record row = findByLegacyKey(exactNamespace, legacyGameSessionTenantId); + if (row == null) { + return Optional.empty(); + } + + AssociationReceipt receipt = toValidatedReceipt(row); + UUID operationId = receipt.operationId(); + UUID associationRequestId = receipt.associationRequestId(); + UUID canonicalTenantId = receipt.approval().canonicalTenantId(); + if (receipt.approval().legacyGameSessionTenantIdValue() != legacyGameSessionTenantId + || !receipt.approval().targetNamespace().equals(exactNamespace)) { + throw new InvalidAssociationEvidenceException( + "Retained-tenant key lookup contradicts its exact namespace or key"); + } + + requireSameAssociationRow(findByOperationId(operationId), operationId, "operation"); + requireSameAssociationRow( + findByRequest(exactNamespace, associationRequestId), operationId, "request"); + requireSameAssociationRow( + findByCanonicalTenant(exactNamespace, canonicalTenantId), operationId, "canonical UUID"); + requireSameAssociationRow( + findByLegacyKey(exactNamespace, legacyGameSessionTenantId), operationId, "retained key"); + return Optional.of(canonicalTenantId); + } + + private void requireSameAssociationRow(Record row, UUID operationId, String identityLabel) { + if (row == null || !operationId.equals(row.get(OPERATION_ID))) { + throw new InvalidAssociationEvidenceException( + "Retained-tenant association " + identityLabel + " cross-read is contradictory"); + } + } + private AssociationReceipt requireExactRetry( Record row, UUID associationRequestId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RetainedRuntimeTenantUuidResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RetainedRuntimeTenantUuidResolver.java new file mode 100644 index 0000000000..f726b006ef --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RetainedRuntimeTenantUuidResolver.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Read-only resolver for approved UUID associations to retained Game Session tenant keys. */ +public final class RetainedRuntimeTenantUuidResolver { + private static final Logger LOG = + LoggerFactory.getLogger(RetainedRuntimeTenantUuidResolver.class); + + private final GameSessionRetainedTenantAssociationRepository associationRepository; + private final String workloadNamespace; + private final TransactionTemplate committedOutcomeRead; + + public RetainedRuntimeTenantUuidResolver( + GameSessionRetainedTenantAssociationRepository associationRepository, + String workloadNamespace, + PlatformTransactionManager transactionManager) { + this.workloadNamespace = Objects.requireNonNull(workloadNamespace, "workloadNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.associationRepository = + Objects.requireNonNull(associationRepository, "associationRepository"); + this.committedOutcomeRead = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + this.committedOutcomeRead.setPropagationBehavior( + TransactionDefinition.PROPAGATION_NOT_SUPPORTED); + this.committedOutcomeRead.setReadOnly(true); + } + + private RetainedRuntimeTenantUuidResolver(String workloadNamespace) { + this.associationRepository = null; + this.workloadNamespace = workloadNamespace; + this.committedOutcomeRead = null; + } + + /** Creates an unavailable resolver when the configured namespace is absent or malformed. */ + public static RetainedRuntimeTenantUuidResolver denyOnly(String workloadNamespace) { + if (workloadNamespace != null && GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("A valid namespace cannot use the deny-only resolver"); + } + return new RetainedRuntimeTenantUuidResolver(workloadNamespace); + } + + /** Resolves only the exact configured-namespace association; all uncertainty fails closed. */ + public Optional resolveCanonicalTenantId(long legacyGameSessionTenantId) { + if (legacyGameSessionTenantId <= 0L || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + return Optional.empty(); + } + if (associationRepository == null || committedOutcomeRead == null) { + return Optional.empty(); + } + try { + return Objects.requireNonNull( + committedOutcomeRead.execute( + status -> + associationRepository.readCanonicalTenantIdByRetainedTenantKey( + legacyGameSessionTenantId, workloadNamespace))); + } catch (RuntimeException exception) { + LOG.warn("Retained runtime tenant UUID association is unavailable", exception); + return Optional.empty(); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java index 244c1b387a..d9c7b1a3ec 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -135,6 +135,111 @@ void committedReadRejectsForeignNamespaceBeforeDatabaseAccess() { verifyNoInteractions(dsl, snapshots); } + @Test + void retainedKeyLookupReturnsHistoricalUuidOnlyForExactNamespaceAndKey() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-before-association"); + GameSessionRetainedTenantSnapshot snapshot = fixture.capture(42L); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(uuid(101), uuid(201), 42L, snapshot); + fixture.register(uuid(301), approval); + + assertThat(fixture.repository.readCanonicalTenantIdByRetainedTenantKey(42L, NAMESPACE)) + .contains(uuid(201)); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> + fixture.repository.readCanonicalTenantIdByRetainedTenantKey( + 42L, NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + assertThat(fixture.repository.readCanonicalTenantIdByRetainedTenantKey(999L, NAMESPACE)) + .isEmpty(); + + fixture.dsl.execute( + "UPDATE game_instances SET runtime_version = ? WHERE id = ?", + "runtime-after-association", + 420L); + assertThat(fixture.repository.readCanonicalTenantIdByRetainedTenantKey(42L, NAMESPACE)) + .contains(uuid(201)); + + GameSessionRetainedTenantAssociationRepository foreignNamespaceRepository = + new GameSessionRetainedTenantAssociationRepository( + fixture.dsl, fixture.snapshotRepository, "other-namespace"); + assertThat( + foreignNamespaceRepository.readCanonicalTenantIdByRetainedTenantKey( + 42L, "other-namespace")) + .isEmpty(); + assertThatThrownBy( + () -> + fixture.repository.readCanonicalTenantIdByRetainedTenantKey(42L, "other-namespace")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured Game Session workload namespace"); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void retainedKeyLookupRejectsMalformedAndContradictoryPersistedRows() { + Fixture malformedFixture = fixture(); + malformedFixture.seedInstance(42L, 420L, "runtime-malformed"); + malformedFixture.register( + uuid(301), + malformedFixture.approval(uuid(101), uuid(201), 42L, malformedFixture.capture(42L))); + disableAssociationImmutabilityTrigger(malformedFixture); + try { + malformedFixture.dsl.execute( + "UPDATE game_session_retained_tenant_association SET approved_by = ? " + + "WHERE target_namespace = ? AND legacy_game_session_tenant_id = ?", + "changed-reviewer", + NAMESPACE, + 42L); + } finally { + enableAssociationImmutabilityTrigger(malformedFixture); + } + assertThatThrownBy( + () -> + malformedFixture.repository.readCanonicalTenantIdByRetainedTenantKey( + 42L, NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class); + + Fixture contradictoryFixture = fixture(); + contradictoryFixture.seedInstance(43L, 430L, "runtime-contradictory"); + contradictoryFixture.register( + uuid(302), + contradictoryFixture.approval( + uuid(102), uuid(202), 43L, contradictoryFixture.capture(43L))); + disableAssociationImmutabilityTrigger(contradictoryFixture); + try { + contradictoryFixture.dsl.execute( + "UPDATE game_session_retained_tenant_association " + + "SET legacy_game_session_tenant_id = ? " + + "WHERE target_namespace = ? AND legacy_game_session_tenant_id = ?", + 44L, + NAMESPACE, + 43L); + } finally { + enableAssociationImmutabilityTrigger(contradictoryFixture); + } + assertThatThrownBy( + () -> + contradictoryFixture.repository.readCanonicalTenantIdByRetainedTenantKey( + 44L, NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class); + } + + private void disableAssociationImmutabilityTrigger(Fixture fixture) { + fixture.dsl.execute( + "ALTER TABLE game_session_retained_tenant_association " + + "DISABLE TRIGGER game_session_retained_tenant_association_immutable"); + } + + private void enableAssociationImmutabilityTrigger(Fixture fixture) { + fixture.dsl.execute( + "ALTER TABLE game_session_retained_tenant_association " + + "ENABLE TRIGGER game_session_retained_tenant_association_immutable"); + } + @Test void changedRequestAndOneToOneClaimConflictsLeaveNoPartialRows() { Fixture fixture = fixture(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java index 9cef9d2d76..794de471f0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java @@ -47,6 +47,8 @@ import org.mockito.ArgumentCaptor; class AccountClientTest { + private static final String ACCOUNT_UUID = "9b80a81b-7971-44af-bd6b-18079027f47a"; + private static final String TENANT_UUID = "cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1"; @Test void directTextScopeRequestCarriesTypedCallerAndCompleteServerResolvedTarget() throws Exception { @@ -413,7 +415,9 @@ void runtimeMembershipReturnsCanonicalUnavailableWhenStubIsMissing() throws Exce @Test void realmAccessGrantReturnsCanonicalUnavailableWhenStubIsMissing() throws Exception { GetRealmAccessGrantForRuntimeResponse response = - newClient(null).getRealmAccessGrantForRuntime("42", "7", "world", "realm", "request-1"); + newClient(null) + .getRealmAccessGrantForRuntime( + ACCOUNT_UUID, TENANT_UUID, "world", "realm", "request-1"); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Realm grant authority unavailable"); @@ -498,7 +502,7 @@ void runtimeMembershipNormalizesExhaustedUnavailableToCanonicalUnavailable() thr @Test void runtimeEntitlementsReturnsCanonicalUnavailableWhenStubIsMissing() throws Exception { GetTenantEntitlementsForRuntimeResponse response = - newClient(null).getTenantEntitlementsForRuntime("7", "request-1"); + newClient(null).getTenantEntitlementsForRuntime(TENANT_UUID, "request-1"); assertThat(response.getError().getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); assertThat(response.getError().getMessage()).isEqualTo("Entitlement authority unavailable"); @@ -517,7 +521,7 @@ void runtimeEntitlementsNormalizesExhaustedUnavailableToCanonicalUnavailable() t .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); GetTenantEntitlementsForRuntimeResponse response = - fixture.client().getTenantEntitlementsForRuntime("7", "request-1"); + fixture.client().getTenantEntitlementsForRuntime(TENANT_UUID, "request-1"); assertThat(response.getError().getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); assertThat(response.getError().getMessage()).isEqualTo("Entitlement authority unavailable"); @@ -528,6 +532,103 @@ void runtimeEntitlementsNormalizesExhaustedUnavailableToCanonicalUnavailable() t verify(fixture.channelFactory()).buildChannel(anyString(), anyInt(), any(), anyBoolean()); } + @Test + void runtimeEntitlementsForwardsExactCanonicalTenantUuid() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + GetTenantEntitlementsForRuntimeResponse expected = + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId(TENANT_UUID) + .setGameplayAvailable(true) + .build(); + when(stub.getTenantEntitlementsForRuntime(any(GetTenantEntitlementsForRuntimeRequest.class))) + .thenReturn(expected); + AccountClient client = newClient(stub); + + assertThat(client.getTenantEntitlementsForRuntime(TENANT_UUID, "request-1")) + .isEqualTo(expected); + + ArgumentCaptor captor = + ArgumentCaptor.forClass(GetTenantEntitlementsForRuntimeRequest.class); + verify(stub).getTenantEntitlementsForRuntime(captor.capture()); + assertThat(captor.getValue().getTenantId()).isEqualTo(TENANT_UUID); + } + + @ParameterizedTest + @ValueSource( + strings = { + "7", + "not-a-uuid", + "CC5E6D40-88C0-4F91-A6D3-A738F4F2F0A1", + "00000000-0000-0000-0000-000000000000", + "" + }) + void runtimeEntitlementsRejectsInvalidTenantUuidBeforeStubOrChannelUse(String tenantId) + throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AccountClient client = newClient(stub, channelFactory); + + GetTenantEntitlementsForRuntimeResponse response = + client.getTenantEntitlementsForRuntime(tenantId, "request-1"); + + assertThat(response.getError().getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(stub, channelFactory); + } + + @Test + void realmAccessGrantForwardsExactCanonicalAccountAndTenantUuids() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + GetRealmAccessGrantForRuntimeResponse expected = + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId(TENANT_UUID) + .setWorldSlug("world") + .setRealmSlug("realm") + .setGranted(true) + .build(); + when(stub.getRealmAccessGrantForRuntime(any(GetRealmAccessGrantForRuntimeRequest.class))) + .thenReturn(expected); + AccountClient client = newClient(stub); + + assertThat( + client.getRealmAccessGrantForRuntime( + ACCOUNT_UUID, TENANT_UUID, "world", "realm", "request-1")) + .isEqualTo(expected); + + ArgumentCaptor captor = + ArgumentCaptor.forClass(GetRealmAccessGrantForRuntimeRequest.class); + verify(stub).getRealmAccessGrantForRuntime(captor.capture()); + assertThat(captor.getValue().getAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(captor.getValue().getTenantId()).isEqualTo(TENANT_UUID); + } + + @ParameterizedTest + @CsvSource({ + "42, cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "not-a-uuid, cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "9b80a81b-7971-44af-bd6b-18079027f47a, 7", + "9B80A81B-7971-44AF-BD6B-18079027F47A, cc5e6d40-88c0-4f91-a6d3-a738f4f2f0a1", + "9b80a81b-7971-44af-bd6b-18079027f47a, 00000000-0000-0000-0000-000000000000" + }) + void realmAccessGrantRejectsInvalidUuidInputsBeforeStubOrChannelUse( + String accountId, String tenantId) throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AccountClient client = newClient(stub, channelFactory); + + GetRealmAccessGrantForRuntimeResponse response = + client.getRealmAccessGrantForRuntime(accountId, tenantId, "world", "realm", "request-1"); + + assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); + verifyNoInteractions(stub, channelFactory); + } + @Test void realmAccessGrantNormalizesExhaustedUnavailableToCanonicalUnavailable() throws Exception { RetryFixture fixture = newRetryFixture(); @@ -541,7 +642,10 @@ void realmAccessGrantNormalizesExhaustedUnavailableToCanonicalUnavailable() thro .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); GetRealmAccessGrantForRuntimeResponse response = - fixture.client().getRealmAccessGrantForRuntime("42", "7", "world", "realm", "request-1"); + fixture + .client() + .getRealmAccessGrantForRuntime( + ACCOUNT_UUID, TENANT_UUID, "world", "realm", "request-1"); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Realm grant authority unavailable"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index 363428efd6..62da95cdcc 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -16,6 +16,7 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateResponse; @@ -34,6 +35,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -55,12 +57,15 @@ class LoginCommandHandlerTest { private static final String ACCOUNT_77 = "774f987b-6650-4d04-8e0f-441867c17923"; private static final String ACCOUNT_99 = "998a7412-13c4-4dbc-86d9-8f40aee3c6f1"; private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static final String CANONICAL_TENANT_UUID = "7c958a3d-401e-47ee-8df8-351988b6ce26"; private final GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); private final SessionContextService sessionContextService = Mockito.mock(SessionContextService.class); private final AccountClient accountClient = Mockito.mock(AccountClient.class); + private final RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver = + Mockito.mock(RetainedRuntimeTenantUuidResolver.class); private final FirstPartyConnectContextRegistry firstPartyConnectContextRegistry = Mockito.mock(FirstPartyConnectContextRegistry.class); private final GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService = @@ -74,6 +79,8 @@ class LoginCommandHandlerTest { @BeforeEach void setUp() { + Mockito.when(retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(22L)) + .thenReturn(Optional.of(UUID.fromString(CANONICAL_TENANT_UUID))); meterRegistry.clear(); stubSessionContext(bootstrapShell(1L, 1L)); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) @@ -1740,6 +1747,7 @@ private PlayCommandHandler createPlayCommandHandler() { GameplayWorldCatalog.forWorldViews(List.of()), new GameLogicProperties(), accountClient, + retainedRuntimeTenantUuidResolver, Mockito.mock(EntityManagementClient.class), Mockito.mock(ModerationPolicyClient.class), firstPartyConnectContextRegistry, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 4b83c987f4..5be1829f27 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -11,9 +11,11 @@ import java.io.IOException; import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; @@ -35,6 +37,7 @@ import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -53,6 +56,8 @@ class PlayCommandHandlerTest { private static final String PLAY_COMMAND_NAME = "PLAY"; private static final String PLAYER_ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + private static final String CANONICAL_TENANT_UUID = "7c958a3d-401e-47ee-8df8-351988b6ce26"; + private static final String FIXTURE_LEGACY_TENANT_UUID = "00000000-0000-0000-0000-000000000022"; private static final ObjectMapper JSON = new ObjectMapper(); private final SessionAuthenticationService sessionAuthenticationService = Mockito.mock(SessionAuthenticationService.class); @@ -61,6 +66,8 @@ class PlayCommandHandlerTest { private final SessionRoutingNormalizationService sessionRoutingNormalizationService = Mockito.mock(SessionRoutingNormalizationService.class); private final AccountClient accountClient = Mockito.mock(AccountClient.class); + private final RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver = + Mockito.mock(RetainedRuntimeTenantUuidResolver.class); private final EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); private final ModerationPolicyClient moderationPolicyClient = @@ -101,12 +108,15 @@ void setUp() { worldCatalog, gameLogicProperties, accountClient, + retainedRuntimeTenantUuidResolver, entityManagementClient, moderationPolicyClient, firstPartyConnectContextRegistry, gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); + when(retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(22L)) + .thenReturn(Optional.of(UUID.fromString(CANONICAL_TENANT_UUID))); when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() @@ -125,7 +135,7 @@ void setUp() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setAllowPublicJoin(true) .setEntitlementVersion(1L) @@ -138,7 +148,7 @@ void setUp() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); + .thenReturn(grantResponse(true)); when(sessionRoutingNormalizationService.normalizeProjectedContext( Mockito.any(SessionContext.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -157,6 +167,100 @@ void setUp() { }); } + @Test + void playForwardsResolvedUuidAndKeepsCatalogKeyForLocalRosterLookup() { + SessionContext context = + new SessionContext( + 1L, 93L, PLAYER_ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("123", "demo", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + var membershipCaptor = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.shared.v1.PlayerExecutionContext.class); + Mockito.verify(accountClient).getTenantMembershipForRuntime(membershipCaptor.capture()); + assertThat(membershipCaptor.getValue().getTenantId()).isEqualTo(CANONICAL_TENANT_UUID); + Mockito.verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq(CANONICAL_TENANT_UUID), Mockito.anyString()); + Mockito.verify(retainedRuntimeTenantUuidResolver).resolveCanonicalTenantId(22L); + Mockito.verify(retainedRuntimeTenantUuidResolver, never()).resolveCanonicalTenantId(93L); + Mockito.verify(entityManagementClient) + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + Mockito.verify(sessionContextService).save(Mockito.argThat(saved -> saved.tenantId() == 22L)); + } + + @Test + void missingRetainedUuidAssociationDeniesBeforeAccountOrGameplayAccess() { + SessionContext context = unboundContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(22L)) + .thenReturn(Optional.empty()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, sessionContextService); + Mockito.verifyNoInteractions( + gameplayPresenceLifecycleService, moderationPolicyClient, scriptEventPublisher); + } + + @Test + void malformedRetainedUuidAssociationDeniesBeforeAccountOrGameplayAccess() { + SessionContext context = unboundContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(22L)) + .thenReturn(Optional.of(new UUID(0L, 0L))); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, sessionContextService); + Mockito.verifyNoInteractions( + gameplayPresenceLifecycleService, moderationPolicyClient, scriptEventPublisher); + } + + @ParameterizedTest + @ValueSource(strings = {"22", "6c118f15-ceda-4f7e-bf9f-1c342cb83962"}) + void numericOrWrongTenantEchoDeniesBeforeRosterOrBinding(String responseTenantId) { + SessionContext context = unboundContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> { + var response = + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(PLAYER_ACCOUNT_ID, 22L, "1")); + return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + response.toBuilder().setTenantId(responseTenantId).build(), + invocation.getArgument(0)); + }); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verifyNoInteractions(entityManagementClient, sessionContextService); + Mockito.verifyNoInteractions(gameplayPresenceLifecycleService, scriptEventPublisher); + } + @Test void playPromotesSessionIntoGameplay() { SessionContext context = @@ -619,7 +723,7 @@ void playReadsEntitlementMembershipAndGrantBeforeActorRoster() { org.mockito.InOrder order = Mockito.inOrder(accountClient, entityManagementClient); order .verify(accountClient) - .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + .getTenantEntitlementsForRuntime(Mockito.eq(CANONICAL_TENANT_UUID), Mockito.anyString()); order .verify(accountClient) .getTenantMembershipForRuntime( @@ -628,7 +732,7 @@ void playReadsEntitlementMembershipAndGrantBeforeActorRoster() { .verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq(PLAYER_ACCOUNT_ID), - Mockito.eq("22"), + Mockito.eq(CANONICAL_TENANT_UUID), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); @@ -1521,7 +1625,7 @@ void playInvisibleRealmWithGrantedAccessContinuesAdmission() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); + .thenReturn(grantResponse(true)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1529,7 +1633,7 @@ void playInvisibleRealmWithGrantedAccessContinuesAdmission() { Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq(PLAYER_ACCOUNT_ID), - Mockito.eq("22"), + Mockito.eq(CANONICAL_TENANT_UUID), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); @@ -1545,7 +1649,7 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(false).build()); + .thenReturn(grantResponse(false)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1569,7 +1673,7 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq(PLAYER_ACCOUNT_ID), - Mockito.eq("22"), + Mockito.eq(CANONICAL_TENANT_UUID), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); @@ -1582,7 +1686,7 @@ void playNonPublicRealmDoesNotConsumePublicJoinPolicy() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setAllowPublicJoin(false) .setEntitlementVersion(1L) @@ -1596,7 +1700,7 @@ void playNonPublicRealmDoesNotConsumePublicJoinPolicy() { Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq(PLAYER_ACCOUNT_ID), - Mockito.eq("22"), + Mockito.eq(CANONICAL_TENANT_UUID), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); @@ -1613,7 +1717,7 @@ void playInvisibleRealmWithDeniedGrantClearsBinding() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(false).build()); + .thenReturn(grantResponse(false)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -2028,7 +2132,7 @@ void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { ? GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE : GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); Mockito.verify(accountClient) - .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + .getTenantEntitlementsForRuntime(Mockito.eq(CANONICAL_TENANT_UUID), Mockito.anyString()); Mockito.verify(accountClient, never()) .getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); @@ -2062,7 +2166,7 @@ void playBillingDenialMasksMissingPublicMembership() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(false) .setAllowPublicJoin(true) .setEntitlementVersion(1L) @@ -2108,7 +2212,7 @@ void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setAllowPublicJoin(false) .setEntitlementVersion(1L) @@ -2150,7 +2254,7 @@ void playExistingPublicMemberCanEnterWhenNewPublicJoinsAreDisabled() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setAllowPublicJoin(false) .setEntitlementVersion(1L) @@ -2191,7 +2295,7 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setAllowPublicJoin(true) .setEntitlementVersion(1L) @@ -2205,7 +2309,7 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti assertThat(result.commandResult().errorCode()) .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); Mockito.verify(accountClient) - .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + .getTenantEntitlementsForRuntime(Mockito.eq(CANONICAL_TENANT_UUID), Mockito.anyString()); Mockito.verify(accountClient) .getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); @@ -2597,7 +2701,7 @@ void playBlockedByEntitlementsReturnsBillingBlocked() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(false) .setEntitlementVersion(5L) .setTenantBillingSequence(5L) @@ -3011,8 +3115,7 @@ private static String resealWithMembershipVersion( String canonicalJson, String membershipVersion) { try { ObjectNode event = (ObjectNode) JSON.readTree(canonicalJson); - ((ObjectNode) event.get("membershipVersion")) - .put("00000000-0000-0000-0000-000000000022", membershipVersion); + ((ObjectNode) event.get("membershipVersion")).put(CANONICAL_TENANT_UUID, membershipVersion); event.remove("eventDigest"); return MembershipAuthorityEventV1Codec.seal( JSON.convertValue(event, new TypeReference>() {})) @@ -3034,7 +3137,131 @@ private static String changeCanonicalEventWithoutResealing(String canonicalJson) private static GetTenantMembershipForRuntimeResponse freshMembership( GetTenantMembershipForRuntimeResponse response) { - return response.toBuilder().setEvaluatedAt(Instant.now().toString()).build(); + String originalTenantId = response.getTenantId(); + var builder = + response.toBuilder() + .setTenantId(CANONICAL_TENANT_UUID) + .setRequestTenantId(CANONICAL_TENANT_UUID) + .setEvaluatedAt(Instant.now().toString()); + if (response.getMembershipVersionCount() > 0) { + builder + .clearMembershipVersion() + .putAllMembershipVersion(rekeyMap(response.getMembershipVersionMap(), originalTenantId)); + } + if (response.hasMembershipBaseline()) { + builder.setMembershipBaseline( + response.getMembershipBaseline().toBuilder() + .clearMembershipVersion() + .putAllMembershipVersion( + rekeyMap( + response.getMembershipBaseline().getMembershipVersionMap(), originalTenantId)) + .build()); + } + if (response.hasAuthorityTuple()) { + var tuple = response.getAuthorityTuple().toBuilder(); + tuple + .clearTenantAuthorityGeneration() + .putAllTenantAuthorityGeneration( + rekeyMap( + response.getAuthorityTuple().getTenantAuthorityGenerationMap(), + originalTenantId)); + tuple + .clearMembershipAuthorityGeneration() + .putAllMembershipAuthorityGeneration( + rekeyMap( + response.getAuthorityTuple().getMembershipAuthorityGenerationMap(), + originalTenantId)); + for (int index = 0; + index < response.getAuthorityTuple().getPrivateRealmGrantVersionsCount(); + index++) { + var grant = response.getAuthorityTuple().getPrivateRealmGrantVersions(index); + if (originalTenantId.equals(grant.getTenantId())) { + tuple.setPrivateRealmGrantVersions( + index, grant.toBuilder().setTenantId(CANONICAL_TENANT_UUID).build()); + } + } + builder.setAuthorityTuple(tuple.build()); + } + builder.clearOutboxCheckpoints(); + response + .getOutboxCheckpointsList() + .forEach( + checkpoint -> + builder.addOutboxCheckpoints( + checkpoint.toBuilder() + .setOutboxStreamKey( + rekeyPathTenant(checkpoint.getOutboxStreamKey(), originalTenantId)) + .build())); + builder.clearOutboxSourceEvidence(); + response + .getOutboxSourceEvidenceList() + .forEach( + source -> { + String canonicalEventJson = + rekeyMembershipEvent( + source.getCanonicalEventJson(), response.getAccountId(), originalTenantId); + var event = MembershipAuthorityEventV1Codec.verify(canonicalEventJson); + builder.addOutboxSourceEvidence( + source.toBuilder() + .setOutboxStreamKey(event.outboxStreamKey()) + .setEventDigest(event.eventDigest()) + .setCanonicalEventJson(event.canonicalJson()) + .build()); + }); + return builder.build(); + } + + private static Map rekeyMap(Map values, String originalTenantId) { + Map result = new LinkedHashMap<>(); + values.forEach( + (key, value) -> { + String rekeyed = originalTenantId.equals(key) ? CANONICAL_TENANT_UUID : key; + if (result.putIfAbsent(rekeyed, value) != null) { + throw new IllegalArgumentException("Fixture tenant UUID rekey collides"); + } + }); + return result; + } + + private static String rekeyPathTenant(String value, String originalTenantId) { + return value.replace("/" + originalTenantId, "/" + CANONICAL_TENANT_UUID); + } + + private static String rekeyMembershipEvent( + String canonicalJson, String accountId, String originalTenantId) { + try { + ObjectNode event = (ObjectNode) JSON.readTree(canonicalJson); + event.put("tenantId", CANONICAL_TENANT_UUID); + event.put( + "outboxStreamKey", + rekeyPathTenant(event.path("outboxStreamKey").asText(), originalTenantId)); + event.put("sourceScope", "membership/" + accountId + "/" + CANONICAL_TENANT_UUID); + rekeyJsonMap((ObjectNode) event.get("membershipVersion"), originalTenantId); + ObjectNode tuple = (ObjectNode) event.get("authorityTuple"); + rekeyJsonMap((ObjectNode) tuple.get("tenantAuthorityGeneration"), originalTenantId); + rekeyJsonMap((ObjectNode) tuple.get("membershipAuthorityGeneration"), originalTenantId); + if (tuple.has("privateRealmGrantVersions")) { + for (var grant : tuple.withArray("privateRealmGrantVersions")) { + if (grant instanceof ObjectNode grantObject + && originalTenantId.equals(grantObject.path("tenantId").asText())) { + grantObject.put("tenantId", CANONICAL_TENANT_UUID); + } + } + } + event.remove("eventDigest"); + return MembershipAuthorityEventV1Codec.seal( + JSON.convertValue(event, new TypeReference>() {})) + .canonicalJson(); + } catch (IOException ex) { + throw new AssertionError("test event should be valid JSON", ex); + } + } + + private static void rekeyJsonMap(ObjectNode values, String originalTenantId) { + if (values != null && values.has(originalTenantId)) { + var value = values.remove(originalTenantId); + values.set(CANONICAL_TENANT_UUID, value); + } } private static GetTenantMembershipForRuntimeResponse leftMembershipWithDefect(String defect) { @@ -3113,6 +3340,16 @@ private static Character actor(String id, String name, PlayableStateScope scope) .build(); } + private static GetRealmAccessGrantForRuntimeResponse grantResponse(boolean granted) { + return GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setAccountId(PLAYER_ACCOUNT_ID) + .setTenantId(CANONICAL_TENANT_UUID) + .setWorldSlug("sandbox") + .setRealmSlug("preview") + .setGranted(granted) + .build(); + } + private void markPreviewRealmInvisible() { gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setVisible(false); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 1a629d3d89..d9b5e4b3a6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -13,6 +13,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateResponse; @@ -57,6 +58,7 @@ import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.PlayerCommandHistoryStorageService; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -74,6 +76,7 @@ @SuppressWarnings("unchecked") class SessionResumptionFlowTest { private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static final String CANONICAL_TENANT_UUID = "7c958a3d-401e-47ee-8df8-351988b6ce26"; private static final String LOGIN_PAYLOAD = "LOGIN demo@example.com swordfish"; private static final String PLAY_PAYLOAD = "PLAY demo"; private static final String LOOK_PAYLOAD = "LOOK"; @@ -82,6 +85,8 @@ class SessionResumptionFlowTest { private final GameInstanceRepository instanceRepository = Mockito.mock(GameInstanceRepository.class); private final AccountClient accountClient = Mockito.mock(AccountClient.class); + private final RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver = + Mockito.mock(RetainedRuntimeTenantUuidResolver.class); private final EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); private final ModerationPolicyClient moderationPolicyClient = @@ -141,6 +146,8 @@ class SessionResumptionFlowTest { @BeforeEach void setUp() { + when(retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(22L)) + .thenReturn(Optional.of(UUID.fromString(CANONICAL_TENANT_UUID))); sessionContextService.save(bootstrapShell(1L, 1L)); sessionContextService.save(bootstrapShell(2L, 1L)); gameplayCatalogProperties.setWorlds( @@ -173,7 +180,7 @@ void setUp() { invocation -> { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - "550e8400-e29b-41d4-a716-446655440000", 22L, "1") + "550e8400-e29b-41d4-a716-446655440000", 22L, CANONICAL_TENANT_UUID, "1") .toBuilder() .setEvaluatedAt(Instant.now().toString()) .build(); @@ -186,7 +193,15 @@ void setUp() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); + .thenAnswer( + invocation -> + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setGranted(true) + .setAccountId(invocation.getArgument(0)) + .setTenantId(invocation.getArgument(1)) + .setWorldSlug(invocation.getArgument(2)) + .setRealmSlug(invocation.getArgument(3)) + .build()); when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() @@ -195,7 +210,7 @@ void setUp() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setAllowPublicJoin(true) .setEntitlementVersion(1L) @@ -285,6 +300,7 @@ void setUp() { worldCatalog, gameLogicProperties, accountClient, + retainedRuntimeTenantUuidResolver, entityManagementClient, moderationPolicyClient, firstPartyConnectContextRegistry, @@ -465,21 +481,11 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { .thenAnswer( invocation -> { var response = - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - "550e8400-e29b-41d4-a716-446655440000", 22L, "2"); + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .activeWithoutPlayerRole( + "550e8400-e29b-41d4-a716-446655440000", 22L, CANONICAL_TENANT_UUID, "2"); var deniedResponse = - response.toBuilder() - .setGameplayAdmissionAllowed(false) - .setMembershipAuthorityGeneration("2") - .setMembershipBaseline( - response.getMembershipBaseline().toBuilder() - .setMembershipAuthorityGeneration("2")) - .setAuthorityTuple( - response.getAuthorityTuple().toBuilder() - .putMembershipAuthorityGeneration( - "00000000-0000-0000-0000-000000000022", "2")) - .setEvaluatedAt(Instant.now().toString()) - .build(); + response.toBuilder().setEvaluatedAt(Instant.now().toString()).build(); return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId(deniedResponse, invocation.getArgument(0)); }); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 5de6687712..93f1be3a34 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -16,6 +16,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; @@ -72,6 +73,7 @@ import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.PlayerCommandHistoryStorageService; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -89,6 +91,7 @@ class TextCommandInterpreterTest { private static final String ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; private static final String OWNER_ACCOUNT_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static final String CANONICAL_TENANT_UUID = "7c958a3d-401e-47ee-8df8-351988b6ce26"; private final CommandService commandService = Mockito.mock(CommandService.class); private final GameLogicClient gameLogicClient = Mockito.mock(GameLogicClient.class); private final EntityManagementClient entityManagementClient = @@ -106,6 +109,8 @@ class TextCommandInterpreterTest { private final SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); private final LookCacheService lookCacheService = Mockito.mock(LookCacheService.class); private final AccountClient accountClient = Mockito.mock(AccountClient.class); + private final RetainedRuntimeTenantUuidResolver retainedRuntimeTenantUuidResolver = + Mockito.mock(RetainedRuntimeTenantUuidResolver.class); private final ModerationPolicyClient moderationPolicyClient = Mockito.mock(ModerationPolicyClient.class); private final MoveCommandHandler moveHandler = Mockito.mock(MoveCommandHandler.class); @@ -157,6 +162,8 @@ class TextCommandInterpreterTest { @BeforeEach void setUp() { + when(retainedRuntimeTenantUuidResolver.resolveCanonicalTenantId(22L)) + .thenReturn(Optional.of(UUID.fromString(CANONICAL_TENANT_UUID))); sessionContextService.save(bootstrapShell(1L, 1L)); meterRegistry.clear(); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) @@ -171,7 +178,7 @@ void setUp() { invocation -> { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - ACCOUNT_ID, 22L, "1") + ACCOUNT_ID, 22L, CANONICAL_TENANT_UUID, "1") .toBuilder() .setEvaluatedAt(Instant.now().toString()) .build(); @@ -184,7 +191,15 @@ void setUp() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); + .thenAnswer( + invocation -> + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setGranted(true) + .setAccountId(invocation.getArgument(0)) + .setTenantId(invocation.getArgument(1)) + .setWorldSlug(invocation.getArgument(2)) + .setRealmSlug(invocation.getArgument(3)) + .build()); when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() @@ -193,7 +208,7 @@ void setUp() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) @@ -376,6 +391,7 @@ void setUp() { worldCatalog, gameLogicProperties, accountClient, + retainedRuntimeTenantUuidResolver, entityManagementClient, moderationPolicyClient, firstPartyConnectContextRegistry, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RetainedRuntimeTenantUuidResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RetainedRuntimeTenantUuidResolverTest.java new file mode 100644 index 0000000000..63bfe78e02 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RetainedRuntimeTenantUuidResolverTest.java @@ -0,0 +1,104 @@ +package unit.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.config.RetainedRuntimeTenantUuidResolverConfiguration; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import net.firedevops.firemud.gamesession.service.RetainedRuntimeTenantUuidResolver; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; + +class RetainedRuntimeTenantUuidResolverTest { + private static final String WORKLOAD_NAMESPACE = "gamesession-test"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("7c958a3d-401e-47ee-8df8-351988b6ce26"); + + private final GameSessionRetainedTenantAssociationRepository repository = + mock(GameSessionRetainedTenantAssociationRepository.class); + private final PlatformTransactionManager transactionManager = new ReadOnlyTransactionManager(); + + @Test + void resolvesOnlyTheConfiguredNamespaceAndExactPositiveRetainedKey() { + when(repository.readCanonicalTenantIdByRetainedTenantKey(42L, WORKLOAD_NAMESPACE)) + .thenReturn(Optional.of(CANONICAL_TENANT_ID)); + RetainedRuntimeTenantUuidResolver resolver = + new RetainedRuntimeTenantUuidResolver(repository, WORKLOAD_NAMESPACE, transactionManager); + + assertThat(resolver.resolveCanonicalTenantId(42L)).contains(CANONICAL_TENANT_ID); + + verify(repository).readCanonicalTenantIdByRetainedTenantKey(42L, WORKLOAD_NAMESPACE); + } + + @Test + void missingNamespaceOrNonPositiveRetainedKeyDoesNotQueryTheRepository() { + RetainedRuntimeTenantUuidResolver missingNamespace = + RetainedRuntimeTenantUuidResolver.denyOnly(""); + RetainedRuntimeTenantUuidResolver configured = + new RetainedRuntimeTenantUuidResolver(repository, WORKLOAD_NAMESPACE, transactionManager); + RetainedRuntimeTenantUuidResolver invalidNamespace = + RetainedRuntimeTenantUuidResolver.denyOnly("Bad.Namespace"); + + assertThat(missingNamespace.resolveCanonicalTenantId(42L)).isEmpty(); + assertThat(invalidNamespace.resolveCanonicalTenantId(42L)).isEmpty(); + assertThat(RetainedRuntimeTenantUuidResolver.denyOnly(null).resolveCanonicalTenantId(42L)) + .isEmpty(); + assertThat(configured.resolveCanonicalTenantId(0L)).isEmpty(); + assertThat(configured.resolveCanonicalTenantId(-1L)).isEmpty(); + + verifyNoInteractions(repository); + } + + @Test + void configurationWithMissingOrInvalidNamespaceConstructsOnlyDenyOnlyResolvers() { + RetainedRuntimeTenantUuidResolverConfiguration configuration = + new RetainedRuntimeTenantUuidResolverConfiguration(); + + RetainedRuntimeTenantUuidResolver missingNamespace = + configuration.retainedRuntimeTenantUuidResolver(null, null, null, ""); + RetainedRuntimeTenantUuidResolver invalidNamespace = + configuration.retainedRuntimeTenantUuidResolver(null, null, null, "Bad.Namespace"); + + assertThat(missingNamespace.resolveCanonicalTenantId(42L)).isEmpty(); + assertThat(invalidNamespace.resolveCanonicalTenantId(42L)).isEmpty(); + } + + @Test + void repositoryFailureAndMissingAssociationRemainUnavailable() { + RetainedRuntimeTenantUuidResolver resolver = + new RetainedRuntimeTenantUuidResolver(repository, WORKLOAD_NAMESPACE, transactionManager); + when(repository.readCanonicalTenantIdByRetainedTenantKey(42L, WORKLOAD_NAMESPACE)) + .thenThrow(new IllegalStateException("malformed retained receipt")); + when(repository.readCanonicalTenantIdByRetainedTenantKey(43L, WORKLOAD_NAMESPACE)) + .thenReturn(Optional.empty()); + + assertThat(resolver.resolveCanonicalTenantId(42L)).isEmpty(); + assertThat(resolver.resolveCanonicalTenantId(43L)).isEmpty(); + } + + private static final class ReadOnlyTransactionManager implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + TransactionDefinition effectiveDefinition = + definition == null ? TransactionDefinition.withDefaults() : definition; + assertThat(effectiveDefinition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_NOT_SUPPORTED); + assertThat(effectiveDefinition.isReadOnly()).isTrue(); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + } +} diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java index 3e33f9e3a4..0a75e0dc33 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.UUID; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.account.v1.RuntimeAuthorityTuple; import net.firedevops.firemud.account.v1.RuntimeMembershipBaseline; @@ -26,6 +27,52 @@ public static GetTenantMembershipForRuntimeResponse active( return complete(accountId, tenantId, true, "ACTIVE", true, membershipVersion); } + /** Builds a complete membership carrier for an explicitly supplied canonical tenant UUID. */ + public static GetTenantMembershipForRuntimeResponse active( + String accountId, + long retainedTenantKey, + String canonicalTenantId, + String membershipVersion) { + requireCanonicalTenantId(canonicalTenantId); + requirePositiveRetainedTenantKey(retainedTenantKey); + return completeWithTenant( + accountId, + canonicalTenantId, + canonicalTenantId, + true, + "ACTIVE", + true, + membershipVersion, + "1", + "1", + "1", + false, + List.of("player")); + } + + /** Builds complete active membership authority with no player role for denial-path tests. */ + public static GetTenantMembershipForRuntimeResponse activeWithoutPlayerRole( + String accountId, + long retainedTenantKey, + String canonicalTenantId, + String membershipVersion) { + requireCanonicalTenantId(canonicalTenantId); + requirePositiveRetainedTenantKey(retainedTenantKey); + return completeWithTenant( + accountId, + canonicalTenantId, + canonicalTenantId, + true, + "ACTIVE", + true, + membershipVersion, + "1", + "1", + "1", + false, + List.of("designer")); + } + public static GetTenantMembershipForRuntimeResponse missing(String accountId, long tenantId) { return complete(accountId, tenantId, false, "MISSING", false, "1"); } @@ -115,8 +162,36 @@ private static GetTenantMembershipForRuntimeResponse complete( String outboxSequence, boolean callerBoundAuthorityInvalidated, List roles) { - String accountUuid = accountId; String tenantUuid = uuid(tenantId); + return completeWithTenant( + accountId, + tenantUuid, + Long.toString(tenantId), + exists, + lifecycle, + admitted, + membershipVersion, + membershipAuthorityGeneration, + issuanceFence, + outboxSequence, + callerBoundAuthorityInvalidated, + roles); + } + + private static GetTenantMembershipForRuntimeResponse completeWithTenant( + String accountId, + String tenantUuid, + String requestTenantId, + boolean exists, + String lifecycle, + boolean admitted, + String membershipVersion, + String membershipAuthorityGeneration, + String issuanceFence, + String outboxSequence, + boolean callerBoundAuthorityInvalidated, + List roles) { + String accountUuid = accountId; String membershipStream = STREAM_PREFIX + "membership/" + accountUuid + "/" + tenantUuid; List checkpoints = new ArrayList<>( @@ -145,7 +220,7 @@ private static GetTenantMembershipForRuntimeResponse complete( .setAccountId(accountUuid) .setTenantId(tenantUuid) .setRequestAccountId(accountId) - .setRequestTenantId(Long.toString(tenantId)) + .setRequestTenantId(requestTenantId) .setAuthorityAvailability("AVAILABLE") .setMembershipExists(exists) .setMembershipLifecycleState(lifecycle) @@ -203,6 +278,21 @@ private static GetTenantMembershipForRuntimeResponse complete( return response.build(); } + private static void requireCanonicalTenantId(String tenantId) { + if (tenantId == null + || tenantId.isBlank() + || !UUID.fromString(tenantId).toString().equals(tenantId) + || new UUID(0L, 0L).toString().equals(tenantId)) { + throw new IllegalArgumentException("test canonical tenant ID must be a non-nil UUID"); + } + } + + private static void requirePositiveRetainedTenantKey(long retainedTenantKey) { + if (retainedTenantKey <= 0L) { + throw new IllegalArgumentException("test retained tenant key must be positive"); + } + } + private static RuntimeOutboxCheckpoint checkpoint(String streamKey, String sequence) { return RuntimeOutboxCheckpoint.newBuilder() .setOutboxStreamKey(streamKey)