From 95ce24dade9f47b23e3c3aa459347201ea7e94c4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 03:36:49 +1300 Subject: [PATCH 01/11] Converge Game Session Account UUID carriers and focused fixtures --- .../gamesession/client/AccountClient.java | 21 +- .../client/EntityManagementClient.java | 2 +- .../gamesession/client/GameLogicClient.java | 8 +- .../client/ModerationPolicyClient.java | 5 +- .../client/SocialGroupsClient.java | 51 +- .../command/text/FriendsCommandHandler.java | 40 +- .../command/text/LoginCommandHandler.java | 30 +- .../command/text/PlayCommandHandler.java | 16 +- .../command/text/WorldsCommandHandler.java | 6 +- ...EffectiveReconnectionSettingsResolver.java | 12 +- .../EffectiveSettingsController.java | 2 +- .../GameplayLocalPathReadinessProbe.java | 2 +- .../FriendMutationResultOutput.java | 6 +- .../FriendPresenceViewOutput.java | 2 +- .../gamesession/service/AccountIds.java | 22 + .../service/AccountPresenceQueryService.java | 2 +- .../service/AccountPresenceSnapshot.java | 6 +- .../service/AccountRecentPresenceService.java | 4 +- .../service/AccountRecentPresenceState.java | 4 +- .../DirectTextConnectScopeSessionStore.java | 14 +- .../service/FirstPartyConnectContext.java | 4 +- .../gamesession/service/GameplayPresence.java | 6 +- .../service/GameplayPresenceService.java | 4 +- .../service/SessionAuthenticationService.java | 2 +- .../gamesession/service/SessionContext.java | 30 +- .../impl/AccountPresenceQueryServiceImpl.java | 23 +- .../service/impl/CommandServiceImpl.java | 5 +- ...GameSessionCommandControlPlaneService.java | 4 +- .../service/impl/GameSessionGrpcService.java | 31 +- .../RedisAccountRecentPresenceService.java | 21 +- .../impl/RedisGameplayPresenceService.java | 49 +- .../impl/RedisSessionContextService.java | 18 +- .../GameSessionWebSocketHandler.java | 8 +- ...ommunicationWebSocketCrossServiceTest.java | 2 +- ...GameSessionApplicationIntegrationTest.java | 2 +- .../GameSessionLoginIntegrationTest.java | 5 +- ...essionWebSocketHandlerIntegrationTest.java | 15 +- .../impl/FakeGameplayPresenceService.java | 13 +- .../gamesession/client/AccountClientTest.java | 5 +- .../client/EntityManagementClientTest.java | 3 +- .../client/GameLogicClientTest.java | 20 +- .../text/ActionStateCommandHandlerTest.java | 22 +- .../AdmittedCommandDefinitionReaderTest.java | 12 +- .../command/text/AfkCommandHandlerTest.java | 48 +- .../AuthoredActionCommandHandlerTest.java | 11 +- ...dActionTextCommandDispatchHandlerTest.java | 10 +- .../text/CommunicationCommandHandlerTest.java | 18 +- .../text/ContainerCommandHandlerTest.java | 10 +- .../text/EquipmentCommandHandlerTest.java | 10 +- .../text/FriendsCommandHandlerTest.java | 212 +++--- .../command/text/HelpCommandHandlerTest.java | 50 +- .../HelpTextCommandDispatchHandlerTest.java | 10 +- .../text/HistoryCommandHandlerTest.java | 10 +- ...HistoryTextCommandDispatchHandlerTest.java | 11 +- .../text/InventoryCommandHandlerTest.java | 10 +- .../command/text/ItemCommandHandlerTest.java | 10 +- .../command/text/LoginCommandHandlerTest.java | 107 +-- .../text/LogoutCommandHandlerTest.java | 16 +- .../command/text/LookCommandHandlerTest.java | 13 +- .../command/text/MoveCommandHandlerTest.java | 10 +- .../command/text/PlayCommandHandlerTest.java | 662 +++++++++++++++--- .../text/PlayerCommandHistoryFlowTest.java | 4 +- .../PlayerCommandHistoryRecorderTest.java | 3 +- .../text/SessionResumptionFlowTest.java | 18 +- .../text/StatusCommandHandlerTest.java | 10 +- .../TextCommandInterpreterCapabilityTest.java | 20 +- ...extCommandInterpreterDispatchSeamTest.java | 12 +- .../text/TextCommandInterpreterTest.java | 24 +- .../command/text/WhoCommandHandlerTest.java | 167 ++++- .../text/WorldsCommandHandlerTest.java | 30 +- .../WorldsTextCommandDispatchHandlerTest.java | 46 +- ...iveCommandHistorySettingsResolverTest.java | 10 +- ...ctiveReconnectionSettingsResolverTest.java | 33 +- .../config/EffectiveSettingsResolverTest.java | 24 +- .../EffectiveSettingsControllerTest.java | 12 +- .../GameplayLocalPathReadinessProbeTest.java | 6 +- .../PromptBurstCoordinatorTest.java | 11 +- .../presentation/PromptComposerTest.java | 22 +- .../TextPlayerOutputRendererTest.java | 9 +- ...unicationRecipientDeliveryServiceTest.java | 125 +++- ...irectTextConnectScopeSessionStoreTest.java | 20 +- ...GameplayAdmissionPointerSnapshotsTest.java | 20 +- .../GameplayPresenceActivityResolverTest.java | 11 +- .../SessionAuthenticationServiceTest.java | 25 +- .../service/SessionContextTest.java | 69 +- ...essionRoutingNormalizationServiceTest.java | 6 +- .../AccountPresenceQueryServiceImplTest.java | 130 ++-- .../AutomationScriptEventPublisherTest.java | 2 +- .../service/impl/CommandServiceImplTest.java | 141 +++- ...leGameplayCommandExecutionServiceTest.java | 231 +++++- ...tGameplayPresenceLifecycleServiceTest.java | 74 +- .../impl/GameAuthoredHelpReaderImplTest.java | 10 +- .../impl/GameSessionGrpcServiceTest.java | 41 +- .../GameplayPresenceRoleClassifierTest.java | 116 ++- ...RedisAccountRecentPresenceServiceTest.java | 39 +- ...sFirstPartyConnectContextRegistryTest.java | 24 +- .../RedisGameplayPresenceServiceTest.java | 81 ++- ...sMovementEffectIdempotencyServiceTest.java | 10 +- .../impl/RedisSessionContextServiceTest.java | 31 +- .../impl/TickQueueControlServiceTest.java | 4 +- .../GameSessionWebSocketHandlerTest.java | 194 ++++- .../WebSocketOutputProjectorTest.java | 51 +- .../gamesession/CrossServiceAppHarness.java | 2 +- .../RuntimeMembershipTestFixtures.java | 24 +- .../gamesession/test/ChatTestFixtures.java | 6 +- .../GameplayCrossServiceStack.java | 4 +- .../testsupport/GameplayWebSocketDriver.java | 7 +- 107 files changed, 2863 insertions(+), 883 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountIds.java 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 3046e16ead..3f25a3c89e 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 @@ -4,7 +4,6 @@ import io.grpc.StatusRuntimeException; import jakarta.annotation.PostConstruct; import java.util.Objects; -import java.util.UUID; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; @@ -30,6 +29,7 @@ import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.slf4j.Logger; @@ -257,7 +257,8 @@ public JoinPublicProductionMembershipResponse joinPublicProductionMembership( } private boolean hasDirectTextCallerIdentity(PlayerExecutionContext context) { - return isPositiveLong(context.getAccountId()) && isPositiveLong(context.getSessionId()); + return AccountIds.isCanonicalNonNilUuid(context.getAccountId()) + && isPositiveLong(context.getSessionId()); } private boolean isPositiveLong(String value) { @@ -294,8 +295,8 @@ private JoinPublicProductionMembershipResponse joinError(String code, String mes public GetTenantMembershipForRuntimeResponse getTenantMembershipForRuntime( PlayerExecutionContext playerContext) { if (playerContext == null - || !isCanonicalNonNilUuid(playerContext.getAccountId()) - || !isCanonicalNonNilUuid(playerContext.getTenantId())) { + || !AccountIds.isCanonicalNonNilUuid(playerContext.getAccountId()) + || !AccountIds.isCanonicalNonNilUuid(playerContext.getTenantId())) { return membershipAuthorityUnavailable(); } if (stub() == null) { @@ -325,18 +326,6 @@ public GetTenantMembershipForRuntimeResponse getTenantMembershipForRuntime( return membershipAuthorityUnavailable(); } - private static boolean isCanonicalNonNilUuid(String value) { - if (value == null || value.isEmpty()) { - return false; - } - try { - UUID parsed = UUID.fromString(value); - return !parsed.equals(new UUID(0L, 0L)) && parsed.toString().equals(value); - } catch (IllegalArgumentException ex) { - return false; - } - } - private GetTenantMembershipForRuntimeResponse membershipAuthorityUnavailable() { return GetTenantMembershipForRuntimeResponse.newBuilder() .setError( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java index 17dcdc8914..820bcad714 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java @@ -223,7 +223,7 @@ private String sessionAttestation( return gameplaySessionAttestationService.issueGameplaySessionAttestation( Long.toString(context.tenantId()), Long.toString(context.sessionId()), - Long.toString(context.accountId()), + context.accountId(), Long.toString(context.characterId()), gameInstanceId, canonicalRoomId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java index 525f08b1ec..d5dc212732 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java @@ -160,7 +160,7 @@ public SendCommunicationResponse sendCommunication( String tenantId = Long.toString(context.tenantId()); String sessionId = Long.toString(context.sessionId()); String characterId = Long.toString(context.characterId()); - String accountId = Long.toString(context.accountId()); + String accountId = context.accountId(); String gameInstanceId = Long.toString(context.gameInstanceId()); SendCommunicationRequest request = SendCommunicationRequest.newBuilder() @@ -346,7 +346,7 @@ public PickupItemFromRoomResponse pickupVisibleRoomItem( SessionContext context, String itemReference, int quantity, String effectId) { String tenantId = Long.toString(context.tenantId()); String sessionId = Long.toString(context.sessionId()); - String accountId = Long.toString(context.accountId()); + String accountId = context.accountId(); String characterId = Long.toString(context.characterId()); String gameInstanceId = Long.toString(context.gameInstanceId()); String roomInstanceId = @@ -449,7 +449,7 @@ public DropItemToRoomResponse dropCarriedItem( SessionContext context, String itemReference, int quantity, String effectId) { String tenantId = Long.toString(context.tenantId()); String sessionId = Long.toString(context.sessionId()); - String accountId = Long.toString(context.accountId()); + String accountId = context.accountId(); String characterId = Long.toString(context.characterId()); String gameInstanceId = Long.toString(context.gameInstanceId()); String roomInstanceId = @@ -720,7 +720,7 @@ private String sessionAttestation(SessionContext context, String roomId) { return gameplaySessionAttestationService.issueGameplaySessionAttestation( Long.toString(context.tenantId()), Long.toString(context.sessionId()), - Long.toString(context.accountId()), + context.accountId(), Long.toString(context.characterId()), Long.toString(context.gameInstanceId()), canonicalRoomId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java index 3ad6c4b534..71ad8a65c5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java @@ -50,11 +50,12 @@ protected LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub buildStub( LoggingAdminServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - public EvaluateModerationPolicyResponse evaluateGameplayAdmission(long tenantId, long accountId) { + public EvaluateModerationPolicyResponse evaluateGameplayAdmission( + long tenantId, String accountId) { EvaluateModerationPolicyRequest request = EvaluateModerationPolicyRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setScope(SCOPE_GAMEPLAY_ADMISSION) .build(); return stub().evaluateModerationPolicy(request); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java index 050a9b781b..b0e0de1d6d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java @@ -67,107 +67,110 @@ protected SocialGroupsServiceGrpc.SocialGroupsServiceBlockingStub buildStub( SocialGroupsServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - public ListFriendPresenceResponse listFriendPresence(long tenantId, long accountId) { + public ListFriendPresenceResponse listFriendPresence(long tenantId, String accountId) { return callStub() .listFriendPresence( ListFriendPresenceRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .build()); } - public ListFriendsResponse listFriends(long tenantId, long accountId, FriendRosterFilter filter) { + public ListFriendsResponse listFriends( + long tenantId, String accountId, FriendRosterFilter filter) { return callStub() .listFriends( ListFriendsRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setFilter(filter) .build()); } - public ListFriendsResponse listFriends(long tenantId, long accountId) { + public ListFriendsResponse listFriends(long tenantId, String accountId) { return listFriends(tenantId, accountId, FriendRosterFilter.FRIEND_ROSTER_FILTER_ALL); } - public AddFriendResponse addFriend(long tenantId, long accountId, long friendAccountId) { + public AddFriendResponse addFriend(long tenantId, String accountId, String friendAccountId) { return callStub() .addFriend( AddFriendRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setFriendAccountId(Long.toString(friendAccountId)) + .setAccountId(accountId) + .setFriendAccountId(friendAccountId) .build()); } - public RemoveFriendResponse removeFriend(long tenantId, long accountId, long friendAccountId) { + public RemoveFriendResponse removeFriend( + long tenantId, String accountId, String friendAccountId) { return callStub() .removeFriend( RemoveFriendRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setFriendAccountId(Long.toString(friendAccountId)) + .setAccountId(accountId) + .setFriendAccountId(friendAccountId) .build()); } public RemoveFriendByOrdinalResponse removeFriendByOrdinal( - long tenantId, long accountId, int ordinal) { + long tenantId, String accountId, int ordinal) { return callStub() .removeFriendByOrdinal( RemoveFriendByOrdinalRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setOrdinal(ordinal) .build()); } - public GetFriendResponse getFriend(long tenantId, long accountId, long friendAccountId) { + public GetFriendResponse getFriend(long tenantId, String accountId, String friendAccountId) { return callStub() .getFriend( GetFriendRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setFriendAccountId(Long.toString(friendAccountId)) + .setAccountId(accountId) + .setFriendAccountId(friendAccountId) .build()); } - public GetFriendByOrdinalResponse getFriendByOrdinal(long tenantId, long accountId, int ordinal) { + public GetFriendByOrdinalResponse getFriendByOrdinal( + long tenantId, String accountId, int ordinal) { return callStub() .getFriendByOrdinal( GetFriendByOrdinalRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setOrdinal(ordinal) .build()); } - public GetFriendRosterSummaryResponse getFriendRosterSummary(long tenantId, long accountId) { + public GetFriendRosterSummaryResponse getFriendRosterSummary(long tenantId, String accountId) { return callStub() .getFriendRosterSummary( GetFriendRosterSummaryRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .build()); } - public GetFriendPresencePolicyResponse getFriendPresencePolicy(long tenantId, long accountId) { + public GetFriendPresencePolicyResponse getFriendPresencePolicy(long tenantId, String accountId) { return callStub() .getFriendPresencePolicy( GetFriendPresencePolicyRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .build()); } public UpdateFriendPresencePolicyResponse updateFriendPresencePolicy( long tenantId, - long accountId, + String accountId, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy visibilityPolicy) { return callStub() .updateFriendPresencePolicy( UpdateFriendPresencePolicyRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountId) .setVisibilityPolicy(visibilityPolicy) .build()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java index 40abc288e0..9dc3b72ce0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.gamesession.presentation.FriendPresenceViewOutput; import net.firedevops.firemud.gamesession.presentation.FriendRosterSummaryViewOutput; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -136,7 +137,7 @@ private TextCommandInterpretationResult handleList( private TextCommandInterpretationResult handleAdd( SessionContext context, ResolvedFriendTarget target, String rawCommandText) { - if (target.friendAccountId() == context.accountId()) { + if (Objects.equals(target.friendAccountId(), context.accountId())) { return friendTargetError( "FRIEND_SELF_LINK_FORBIDDEN", "Cannot add or remove your own account as a friend"); } @@ -160,7 +161,7 @@ private TextCommandInterpretationResult handleAdd( private TextCommandInterpretationResult handleRemove( SessionContext context, ResolvedFriendTarget target, String rawCommandText) { - if (target.friendAccountId() == context.accountId()) { + if (Objects.equals(target.friendAccountId(), context.accountId())) { return friendTargetError( "FRIEND_SELF_LINK_FORBIDDEN", "Cannot add or remove your own account as a friend"); } @@ -429,7 +430,7 @@ private FriendPresenceViewOutput toView(ListFriendsResponse response, FriendList private FriendPresenceViewOutput.Entry toEntry(int ordinal, FriendRosterEntry entry) { FriendPresenceEntry presence = entry.getPresence(); - long friendAccountId = requireFriendAccountId(entry.getFriendAccountId()); + String friendAccountId = requireFriendAccountId(entry.getFriendAccountId()); if (!isPlayerDisclosablePolicy(presence.getVisibilityPolicy())) { return redactedEntry(ordinal, entry, friendAccountId, "Friend #" + friendAccountId); } @@ -456,7 +457,7 @@ private FriendPresenceViewOutput.Entry toEntry(int ordinal, FriendRosterEntry en } private FriendPresenceViewOutput.Entry redactedEntry( - int ordinal, FriendRosterEntry entry, long friendAccountId, String displayName) { + int ordinal, FriendRosterEntry entry, String friendAccountId, String displayName) { return new FriendPresenceViewOutput.Entry( ordinal, parseOptionalLong(entry.getFriendLinkId()), @@ -496,14 +497,16 @@ private String activityState(FriendPresenceActivityState activityState) { }; } - private long requireFriendAccountId(String value) { + private String requireFriendAccountId(String value) { if (!StringUtils.hasText(value)) { throw new IllegalStateException( "Malformed friend roster friendAccountId: friendAccountId is required"); } try { - return PositiveLongParsing.requireOptionalText(value, "friendAccountId") - .orElseThrow(() -> new IllegalArgumentException("friendAccountId is required")); + if (!AccountIds.isCanonicalNonNilUuid(value)) { + throw new IllegalArgumentException("friendAccountId must be a canonical non-nil UUID"); + } + return value; } catch (IllegalArgumentException ex) { throw new IllegalStateException( "Malformed friend roster friendAccountId: " + ex.getMessage(), ex); @@ -593,13 +596,13 @@ private FriendAction parseAction(TextCommand command) { } private ResolvedFriendTarget resolveTarget(SessionContext context, FriendAction action) { - Long accountId = tryParseAccountId(action.targetToken()); + String accountId = tryParseAccountId(action.targetToken()); if (accountId != null) { return new ResolvedFriendTarget(accountId, null, null); } if (!StringUtils.hasText(action.targetToken())) { return new ResolvedFriendTarget( - 0L, + null, null, invalidUsage("FRIENDS " + action.keyword() + " ")); } @@ -608,17 +611,16 @@ private ResolvedFriendTarget resolveTarget(SessionContext context, FriendAction context, resolvePlayableStateScope(context), action.targetToken().trim()); if (character.isEmpty() || !StringUtils.hasText(character.get().getAccountId())) { return new ResolvedFriendTarget( - 0L, + null, null, friendTargetError("FRIEND_TARGET_NOT_FOUND", notFoundMessage(action.targetToken()))); } - PositiveLongParsing.ParsedPositiveLong parsedAccountId = - PositiveLongParsing.parseOptionalText(character.get().getAccountId(), "friendAccountId"); - if (!parsedAccountId.valid()) { + String resolvedAccountId = character.get().getAccountId(); + if (!AccountIds.isCanonicalNonNilUuid(resolvedAccountId)) { return new ResolvedFriendTarget( - 0L, null, malformedResolvedTargetError(action, character.get().getAccountId())); + null, null, malformedResolvedTargetError(action, resolvedAccountId)); } - return new ResolvedFriendTarget(parsedAccountId.value(), character.get().getName(), null); + return new ResolvedFriendTarget(resolvedAccountId, character.get().getName(), null); } private TextCommandInterpretationResult malformedResolvedTargetError( @@ -698,10 +700,8 @@ private FriendRosterFilter mapRosterFilter(FriendListFilter filter) { }; } - private Long tryParseAccountId(String value) { - return PositiveLongParsing.parseOptionalText(value, "friendAccountId") - .optionalValue() - .orElse(null); + private String tryParseAccountId(String value) { + return AccountIds.isCanonicalNonNilUuid(value) ? value : null; } private boolean isOrdinalToken(String value) { @@ -859,5 +859,5 @@ private record FriendAction( String invalidUsage) {} private record ResolvedFriendTarget( - long friendAccountId, String characterName, TextCommandInterpretationResult errorResult) {} + String friendAccountId, String characterName, TextCommandInterpretationResult errorResult) {} } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java index 965d812472..1f9ffdd64d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java @@ -15,13 +15,13 @@ import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolution; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; 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.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; @@ -139,8 +139,8 @@ public LoginCommandHandlingResult handle( return failure(errorCode, publicErrorMessage(error, errorCode)); } - Long authenticatedAccountId = parseAccountId(authResponse.getAccountId()); - if (authenticatedAccountId == null || authenticatedAccountId <= 0) { + String authenticatedAccountId = parseAccountId(authResponse.getAccountId()); + if (authenticatedAccountId == null) { clearFailedLoginSessionState( numericSessionId, instance.getTenantId(), bootstrapGameInstanceId, null, null, 0L); return invalidAccountFailure(); @@ -257,8 +257,8 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin( } if (existingSession != null - && existingSession.accountId() > 0L - && (existingSession.accountId() != verifiedContext.accountId() + && existingSession.hasAccountIdentity() + && (!Objects.equals(existingSession.accountId(), verifiedContext.accountId()) || existingSession.tenantId() != verifiedContext.tenantId())) { clearPreviousSessionForVerifiedContext(numericSessionId, existingSession, verifiedContext); } @@ -274,7 +274,7 @@ private void clearPreviousSessionForVerifiedContext( new SessionContext( sessionId, verifiedContext.tenantId(), - 0L, + null, null, 0L, null, @@ -294,7 +294,7 @@ private void clearPreviousSessionForVerifiedContext( private void persistSessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, String jwt, long bootstrapGameInstanceId) { @@ -309,9 +309,10 @@ private void persistSessionContext( projectedExisting != null && projectedExisting.tenantId() == tenantId ? projectedExisting : null; - boolean sameAuthenticatedAccount = existing != null && existing.accountId() == accountId; + boolean sameAuthenticatedAccount = + existing != null && Objects.equals(existing.accountId(), accountId); boolean unauthenticatedBootstrap = - existing != null && existing.accountId() == 0L && !existing.hasGameplayBinding(); + existing != null && !existing.hasAccountIdentity() && !existing.hasGameplayBinding(); long retainedBootstrapGameInstanceId = bootstrapGameInstanceId; String retainedWorldSlug = null; String retainedRealmSlug = null; @@ -455,7 +456,7 @@ private void clearFailedLoginSessionState( new SessionContext( sessionId, tenantId, - 0L, + null, null, 0L, null, @@ -515,13 +516,8 @@ private SessionIdParsing.ParsedSessionId parseSessionId(String sessionIdText) { return SessionIdParsing.parse(sessionIdText); } - private Long parseAccountId(String accountIdText) { - PositiveLongParsing.ParsedPositiveLong parsed = - PositiveLongParsing.parseOptionalText(accountIdText, "accountId"); - if (!parsed.valid()) { - return null; - } - return parsed.value(); + private String parseAccountId(String accountIdText) { + return AccountIds.isCanonicalNonNilUuid(accountIdText) ? accountIdText : null; } private LoginCommandHandlingResult invalidSessionFailure(String message) { 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 bccfebe7c0..622eeeb6d8 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 @@ -29,6 +29,7 @@ import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameplayCommand; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; @@ -485,7 +486,7 @@ private Character resolveCharacter( ListCharactersByAccountResponse response = entityManagementClient.listCharactersByAccount( Long.toString(selectedRealm.tenantId()), - Long.toString(context.accountId()), + context.accountId(), Long.toString(selectedRealm.gameInstanceId()), scope); if (response.hasError()) { @@ -493,7 +494,7 @@ private Character resolveCharacter( } for (Character candidate : response.getCharactersList()) { if (!Long.toString(selectedRealm.tenantId()).equals(candidate.getTenantId()) - || !Long.toString(context.accountId()).equals(candidate.getAccountId()) + || !context.accountId().equals(candidate.getAccountId()) || candidate.getPlayableStateScope() != scope || !StringUtils.hasText(candidate.getName())) { throw new IllegalStateException("Entity account roster contains an invalid actor"); @@ -767,7 +768,7 @@ private Optional validateMembershipResponse( if (!isPublicProductionRealm(selectedRealm)) { GetRealmAccessGrantForRuntimeResponse grantResponse = accountClient.getRealmAccessGrantForRuntime( - Long.toString(context.accountId()), + context.accountId(), Long.toString(selectedRealm.tenantId()), selectedWorld.slug(), selectedRealm.slug(), @@ -828,7 +829,8 @@ private static boolean hasCompleteMembershipAuthorityCarrier( if (!response.hasMembershipBaseline() || !response.hasAuthorityTuple()) { return false; } - if (!isCanonicalUuid(response.getAccountId()) || !isCanonicalUuid(response.getTenantId())) { + if (!AccountIds.isCanonicalNonNilUuid(response.getAccountId()) + || !isCanonicalUuid(response.getTenantId())) { return false; } if (!response @@ -1057,7 +1059,7 @@ private static PlayerExecutionContext membershipPlayerContext( long characterId, String requestId) { return PlayerExecutionContext.newBuilder() - .setAccountId(Long.toString(caller.accountId())) + .setAccountId(caller.accountId()) .setTenantId(Long.toString(target.tenantId())) .setRealmId(Objects.toString(target.realmId(), "")) .setPlayableStateNamespaceId(Objects.toString(target.playableStateNamespaceId(), "")) @@ -1303,9 +1305,9 @@ private boolean isSafeMembershipAuthorityResponse( if (!StringUtils.hasText(response.getAccountId()) || !StringUtils.hasText(response.getTenantId()) || !StringUtils.hasText(response.getEvaluatedAt()) - || !isCanonicalUuid(response.getAccountId()) + || !AccountIds.isCanonicalNonNilUuid(response.getAccountId()) || !isCanonicalUuid(response.getTenantId()) - || !response.getRequestAccountId().equals(Long.toString(context.accountId())) + || !response.getRequestAccountId().equals(context.accountId()) || !response.getRequestTenantId().equals(Long.toString(selectedRealm.tenantId())) || !response.getRequestId().equals(requestId)) { return false; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index ef398a8de7..82b3271ebc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -64,7 +64,7 @@ public java.util.Optional browseRealms(String worldSelect public RealmBrowseResult browseRealms(SessionContext sessionContext, String worldSelector) { Objects.requireNonNull(sessionContext, "sessionContext must not be null"); - if (sessionContext.accountId() <= 0 || sessionContext.sessionId() <= 0) { + if (!sessionContext.hasAccountIdentity() || sessionContext.sessionId() <= 0) { return RealmBrowseResult.failure("LOGIN_REQUIRED"); } if (connectScopeSessionStore != null) { @@ -125,7 +125,7 @@ public RealmBrowseResult browseRealms(SessionContext sessionContext, String worl public JoinMembershipResult joinPublicProductionMembership( SessionContext sessionContext, String worldSelector) { Objects.requireNonNull(sessionContext, "sessionContext must not be null"); - if (sessionContext.accountId() <= 0 || sessionContext.sessionId() <= 0) { + if (!sessionContext.hasAccountIdentity() || sessionContext.sessionId() <= 0) { return JoinMembershipResult.failure("LOGIN_REQUIRED"); } if (accountClient == null || connectScopeSessionStore == null) { @@ -173,7 +173,7 @@ private DirectTextConnectScopeTarget connectScopeTarget( private PlayerExecutionContext playerContext( SessionContext caller, GameplayWorldCatalog.RealmView realm) { return PlayerExecutionContext.newBuilder() - .setAccountId(Long.toString(caller.accountId())) + .setAccountId(caller.accountId()) .setSessionId(Long.toString(caller.sessionId())) .setTenantId(Long.toString(realm.tenantId())) .setRealmId(realm.realmId().toString()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java index 2923de43cc..4f6ecb40e0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java @@ -90,7 +90,17 @@ public ResolvedValue resolvedReconnection(Session public FiremudReconnectionProperties resolve(long tenantId, long gameInstanceId) { return resolvedReconnection( new SessionContext( - 0L, tenantId, 0L, null, 0L, null, gameInstanceId, null, null, null, gameInstanceId)) + 0L, + tenantId, + null, + null, + 0L, + null, + gameInstanceId, + null, + null, + null, + gameInstanceId)) .effective(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java index d98e06ebaa..2b6cd3b1ca 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java @@ -152,7 +152,7 @@ private SessionResolution resolveContext( new SessionContext( 0L, resolvedTenantId, - 0L, + null, null, 0L, null, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java index ed2a67c117..4fe28f54c6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java @@ -18,7 +18,7 @@ public final class GameplayLocalPathReadinessProbe { private static final long PROBE_TENANT_ID = 0L; private static final long PROBE_SESSION_ID = 9_223_372_036_854_770_000L; - private static final long PROBE_ACCOUNT_ID = 9_223_372_036_854_770_001L; + private static final String PROBE_ACCOUNT_ID = "ff36f51a-6cbd-4f26-8332-031535e2e3b4"; private static final long PROBE_CHARACTER_ID = 9_223_372_036_854_770_002L; private static final long PROBE_GAME_INSTANCE_ID = 0L; private static final String PROBE_ROOM_INSTANCE_ID_PREFIX = "readiness-room-"; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java index 0bd9a89cfd..c17bf5c6f9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java @@ -4,7 +4,11 @@ /** Structured payload for canonical friend add/remove mutation results. */ public record FriendMutationResultOutput( - String action, long friendAccountId, String displayName, String characterName, Integer ordinal) + String action, + String friendAccountId, + String displayName, + String characterName, + Integer ordinal) implements PlayerOutputPayload { public FriendMutationResultOutput { Objects.requireNonNull(action, "action must not be null"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java index 4700d9751d..37e5e4bf40 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java @@ -14,7 +14,7 @@ public record FriendPresenceViewOutput( public record Entry( int ordinal, Long friendLinkId, - long friendAccountId, + String friendAccountId, String status, Long linkedAtEpochMs, String displayName, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountIds.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountIds.java new file mode 100644 index 0000000000..a3a63d6f5a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountIds.java @@ -0,0 +1,22 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.UUID; + +/** Validation for canonical Account logical identifiers carried by Game Session. */ +public final class AccountIds { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AccountIds() {} + + public static boolean isCanonicalNonNilUuid(String value) { + if (value == null || value.isEmpty()) { + return false; + } + try { + UUID parsed = UUID.fromString(value); + return !NIL_UUID.equals(parsed) && parsed.toString().equals(value); + } catch (IllegalArgumentException ex) { + return false; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceQueryService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceQueryService.java index e2ab1978ce..1440bc2e9d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceQueryService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceQueryService.java @@ -5,5 +5,5 @@ /** Resolves account-scoped social presence from running sessions plus live gameplay presence. */ public interface AccountPresenceQueryService { List queryAccountPresence( - long tenantId, long viewerAccountId, List accountIds); + long tenantId, String viewerAccountId, List accountIds); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java index 244da44537..81627959d1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java @@ -6,7 +6,7 @@ * Canonical account-scoped social presence snapshot derived from current gameplay runtime state. */ public record AccountPresenceSnapshot( - long accountId, + String accountId, boolean online, Long gameInstanceId, String playableStateScope, @@ -21,7 +21,7 @@ public record AccountPresenceSnapshot( Instant lastSeenAt, AccountRecentPresenceDisposition recentDisposition) { public AccountPresenceSnapshot( - long accountId, + String accountId, boolean online, Long gameInstanceId, String worldSlug, @@ -50,7 +50,7 @@ public AccountPresenceSnapshot( } public AccountPresenceSnapshot( - long accountId, + String accountId, boolean online, Long gameInstanceId, String playableStateScope, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceService.java index 8fc44afeda..993d372864 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceService.java @@ -11,6 +11,6 @@ public interface AccountRecentPresenceService { void recordDisconnect(long sessionId, AccountRecentPresenceDisposition disposition); - Map findByAccountIds( - long tenantId, Collection accountIds); + Map findByAccountIds( + long tenantId, Collection accountIds); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java index c8ecc54aca..71db4e4192 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java @@ -5,7 +5,7 @@ /** Bounded recent-presence facts retained after a gameplay presence disconnects. */ public record AccountRecentPresenceState( long tenantId, - long accountId, + String accountId, Long gameInstanceId, String playableStateScope, String worldSlug, @@ -18,7 +18,7 @@ public record AccountRecentPresenceState( public AccountRecentPresenceState( long tenantId, - long accountId, + String accountId, long lastSeenAtEpochMs, AccountRecentPresenceDisposition disposition) { this(tenantId, accountId, null, null, null, null, null, lastSeenAtEpochMs, disposition); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java index e362bbc763..a25ba9f628 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java @@ -40,7 +40,7 @@ public void replaceWorldScopes( } safeScopes.forEach( scope -> { - if (!scope.playerContext().getAccountId().equals(Long.toString(caller.accountId())) + if (!scope.playerContext().getAccountId().equals(caller.accountId()) || !scope.playerContext().getSessionId().equals(Long.toString(caller.sessionId()))) { throw new IllegalArgumentException("scope caller identity did not match session"); } @@ -51,7 +51,7 @@ public void replaceWorldScopes( (sessionId, existing) -> { Map> byWorld = new HashMap<>(); Map worldBySelector = new HashMap<>(); - if (existing != null && existing.accountId() == caller.accountId()) { + if (existing != null && Objects.equals(existing.accountId(), caller.accountId())) { byWorld.putAll(existing.scopesByWorld()); worldBySelector.putAll(existing.worldBySelector()); } @@ -72,7 +72,7 @@ public void clearWorldScopes(SessionContext caller, String worldSelector) { scopesBySessionId.computeIfPresent( caller.sessionId(), (sessionId, existing) -> { - if (existing.accountId() != caller.accountId()) { + if (!Objects.equals(existing.accountId(), caller.accountId())) { return null; } String worldSlug = existing.worldBySelector().get(selector); @@ -101,7 +101,7 @@ public Optional publicProductionScope( return Optional.empty(); } SessionScopes sessionScopes = scopesBySessionId.get(caller.sessionId()); - if (sessionScopes == null || sessionScopes.accountId() != caller.accountId()) { + if (sessionScopes == null || !Objects.equals(sessionScopes.accountId(), caller.accountId())) { if (sessionScopes != null) { scopesBySessionId.remove(caller.sessionId(), sessionScopes); } @@ -138,7 +138,7 @@ public Optional publicProductionScopeForJoin( scopesBySessionId.computeIfPresent( caller.sessionId(), (sessionId, sessionScopes) -> { - if (sessionScopes.accountId() != caller.accountId()) { + if (!Objects.equals(sessionScopes.accountId(), caller.accountId())) { return sessionScopes; } String worldSlug = sessionScopes.worldBySelector().get(selector); @@ -226,7 +226,7 @@ void removeExpiredScopes() { } private void requireCallerIdentity(SessionContext caller) { - if (caller.accountId() <= 0 || caller.sessionId() <= 0) { + if (!caller.hasAccountIdentity() || caller.sessionId() <= 0) { throw new IllegalArgumentException( "authenticated account and transport session are required"); } @@ -286,7 +286,7 @@ public record JoinScope(ScopedRealm scope, String requestId) { } private record SessionScopes( - long accountId, + String accountId, Map> scopesByWorld, Map worldBySelector) { private SessionScopes { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java index 3a33918103..d70bcc3463 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java @@ -4,7 +4,7 @@ import org.springframework.util.StringUtils; public record FirstPartyConnectContext( - long accountId, + String accountId, long tenantId, String worldSlug, String realmSlug, @@ -18,7 +18,7 @@ public record FirstPartyConnectContext( private static final long serialVersionUID = 1L; public boolean hasCompleteRoutingScope() { - return accountId > 0L + return AccountIds.isCanonicalNonNilUuid(accountId) && tenantId > 0L && gameInstanceId > 0L && pointerVersion > 0L diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java index 7f7938aa62..ef919528b9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java @@ -11,7 +11,7 @@ public record GameplayPresence( String worldSlug, String realmSlug, long pointerVersion, - long accountId, + String accountId, long characterId, String characterName, GameplayPresenceRole role, @@ -28,7 +28,7 @@ public GameplayPresence( long gameInstanceId, String worldSlug, String realmSlug, - long accountId, + String accountId, long characterId, String characterName, GameplayPresenceRole role, @@ -60,7 +60,7 @@ public GameplayPresence( String playableStateScope, String worldSlug, String realmSlug, - long accountId, + String accountId, long characterId, String characterName, GameplayPresenceRole role, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceService.java index 58f54f8c91..7ec56bd602 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceService.java @@ -17,8 +17,8 @@ public interface GameplayPresenceService { List listConnectedByGameInstance(long tenantId, long gameInstanceId); - Map> listConnectedByAccountIds( - long tenantId, Collection accountIds); + Map> listConnectedByAccountIds( + long tenantId, Collection accountIds); Optional findConnectedBySessionId(long sessionId); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java index 1956ffbf95..0ebff77e98 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java @@ -103,7 +103,7 @@ public SessionContext normalizeResolvedContext(SessionContext context) { } private boolean isAuthenticatedContext(SessionContext context) { - return context.accountId() > 0; + return context.hasAccountIdentity(); } private Optional parseSessionId(String text) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java index 01cf34ef35..dd47f6fb32 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java @@ -2,13 +2,14 @@ import java.io.Serializable; import java.util.Locale; +import java.util.Objects; import java.util.Optional; /** Represents persisted login context stored in Redis for a session. */ public record SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -27,6 +28,9 @@ public record SessionContext( private static final long serialVersionUID = 1L; public SessionContext { + if (accountId != null && !AccountIds.isCanonicalNonNilUuid(accountId)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } loginName = loginName == null ? null : loginName.trim(); characterName = characterName == null ? null : characterName.trim(); roomInstanceId = normalizeText(roomInstanceId); @@ -41,7 +45,7 @@ public record SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -77,7 +81,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -108,7 +112,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -140,7 +144,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, long characterId, long gameInstanceId, String roomInstanceId, @@ -168,7 +172,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, long characterId, long gameInstanceId, String jwt) { @@ -195,7 +199,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -224,7 +228,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -281,6 +285,10 @@ public boolean hasGameplayIdentity() { return gameInstanceId > 0 && characterId > 0; } + public boolean hasAccountIdentity() { + return AccountIds.isCanonicalNonNilUuid(accountId); + } + public SessionContext withoutJwt() { if (jwt == null) { return this; @@ -328,13 +336,13 @@ public boolean sameGameplayIdentity(SessionContext that) { } return sessionId == that.sessionId() && tenantId == that.tenantId() - && accountId == that.accountId() + && Objects.equals(accountId, that.accountId()) && characterId == that.characterId() && gameInstanceId == that.gameInstanceId(); } public Optional persistedFirstPartyConnectContext() { - if (accountId <= 0 || tenantId <= 0) { + if (!hasAccountIdentity() || tenantId <= 0) { return Optional.empty(); } FirstPartyConnectContext connectContext = @@ -355,7 +363,7 @@ public Optional persistedFirstPartyConnectContext() { } public boolean hasPartialPersistedFirstPartyConnectContext() { - if (accountId <= 0 || tenantId <= 0) { + if (!hasAccountIdentity() || tenantId <= 0) { return false; } boolean hasAnyPersistedSelectorField = connectScopeId != null || connectRequestId != null; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java index df33088477..1315348909 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java @@ -11,6 +11,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.AccountPresenceSnapshot; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceService; @@ -57,11 +58,11 @@ public AccountPresenceQueryServiceImpl( @Override public List queryAccountPresence( - long tenantId, long viewerAccountId, List accountIds) { + long tenantId, String viewerAccountId, List accountIds) { Objects.requireNonNull(accountIds, "accountIds"); - LinkedHashSet requestedIds = new LinkedHashSet<>(); - for (Long accountId : accountIds) { - if (accountId != null && accountId > 0) { + LinkedHashSet requestedIds = new LinkedHashSet<>(); + for (String accountId : accountIds) { + if (AccountIds.isCanonicalNonNilUuid(accountId)) { requestedIds.add(accountId); } } @@ -69,20 +70,20 @@ public List queryAccountPresence( return List.of(); } - Map results = new LinkedHashMap<>(); + Map results = new LinkedHashMap<>(); Map currentRuntimePointers = new HashMap<>(); - Map recentStates = + Map recentStates = accountRecentPresenceService.findByAccountIds(tenantId, requestedIds); - for (Long accountId : requestedIds) { + for (String accountId : requestedIds) { results.put( accountId, offline(tenantId, accountId, recentStates.get(accountId), currentRuntimePointers)); } - Map> activePresences = + Map> activePresences = gameplayPresenceService.listConnectedByAccountIds(tenantId, requestedIds); - for (Map.Entry> entry : activePresences.entrySet()) { - Long accountId = entry.getKey(); + for (Map.Entry> entry : activePresences.entrySet()) { + String accountId = entry.getKey(); GameplayPresence presence = selectCurrentPresence(tenantId, entry.getValue(), currentRuntimePointers); if (presence == null) { @@ -170,7 +171,7 @@ private boolean isCurrentPresence( private AccountPresenceSnapshot offline( long tenantId, - long accountId, + String accountId, AccountRecentPresenceState recentState, Map currentRuntimePointers) { GameplayAdmissionPointerSnapshot pointer = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java index f24de8b5ad..a1db851740 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java @@ -198,9 +198,10 @@ private GameplayCommand persistAcceptedCommand( gameplayCommand.setGameInstanceId(queueTarget.queueTargetId()); gameplayCommand.setSessionId(sessionId); sessionContext + .filter(SessionContext::hasAccountIdentity) .map(SessionContext::accountId) - .filter(id -> id > 0) - .ifPresent(gameplayCommand::setAccountId); + .map(UUID::fromString) + .ifPresent(gameplayCommand::setAccountUuid); sessionContext .map(SessionContext::characterId) .filter(id -> id > 0) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java index ebe26f48aa..cf08a4386e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java @@ -1545,8 +1545,8 @@ private GameplayCommandStatus toStatus(GameplayCommand command) { .setLastAttemptAtMs(toEpochMillis(command.getLastAttemptAt())) .setAttemptCount(command.getAttemptCount()) .setPlayableStateScope(toPlayableStateScopeStatus(command.getPlayableStateScope())); - if (command.getAccountId() != null) { - builder.setAccountId(command.getAccountId().toString()); + if (command.getAccountUuid() != null) { + builder.setAccountId(command.getAccountUuid().toString()); } if (command.getCharacterId() != null) { builder.setCharacterId(command.getCharacterId().toString()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 896ca96837..a193a00861 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.gamesession.dto.StartSessionRequest; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.FeatureFlagService; import net.firedevops.firemud.gamesession.service.GameInstanceService; @@ -232,9 +233,15 @@ private long parseOwnerAccountId(String ownerAccountIdText) { return ControlPlaneRequestParser.parsePositiveLong(ownerAccountIdText, "ownerAccountId"); } - private List parseAccountIds(List accountIds) { + private List parseAccountIds(List accountIds) { return accountIds.stream() - .map(accountId -> ControlPlaneRequestParser.parsePositiveLong(accountId, "accountId")) + .map( + accountId -> { + if (!AccountIds.isCanonicalNonNilUuid(accountId)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + return accountId; + }) .toList(); } @@ -437,18 +444,18 @@ public void queryAccountPresence( try { long tenantId = ControlPlaneRequestParser.parsePositiveLong(request.getTenantId(), "tenantId"); - long viewerAccountId = parseOwnerAccountId(request.getViewerAccountId()); + String viewerAccountId = parseCanonicalAccountId(request.getViewerAccountId()); requireTenantOrCurrentAccountAccess(tenantId, viewerAccountId); if (request.getAccountIdsCount() > 100) { throw new IllegalArgumentException("accountIds must contain at most 100 entries"); } - List accountIds = parseAccountIds(request.getAccountIdsList()); + List accountIds = parseAccountIds(request.getAccountIdsList()); QueryAccountPresenceResponse.Builder builder = QueryAccountPresenceResponse.newBuilder(); for (var snapshot : accountPresenceQueryService.queryAccountPresence(tenantId, viewerAccountId, accountIds)) { AccountPresenceEntry.Builder entry = AccountPresenceEntry.newBuilder() - .setAccountId(Long.toString(snapshot.accountId())) + .setAccountId(snapshot.accountId()) .setOnline(snapshot.online()); if (snapshot.gameInstanceId() != null) { entry.setGameInstanceId(Long.toString(snapshot.gameInstanceId())); @@ -753,8 +760,18 @@ private void requireTenantAccess(long tenantId) { throw new AuthorizationException("Tenant access required"); } - private void requireTenantOrCurrentAccountAccess(long tenantId, long accountId) { - if (SessionContext.hasTenantAccess(tenantId) || isCurrentAccount(accountId)) { + private String parseCanonicalAccountId(String accountId) { + if (!AccountIds.isCanonicalNonNilUuid(accountId)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + return accountId; + } + + private void requireTenantOrCurrentAccountAccess(long tenantId, String accountId) { + if (SessionContext.hasTenantAccess(tenantId)) { + return; + } + if (accountId.equals(SessionContext.getAccountId())) { return; } throw new AuthorizationException("Account access required"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java index baaec064eb..1d86e2248f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java @@ -6,6 +6,7 @@ import java.util.Map; import java.util.function.LongSupplier; import net.firedevops.firemud.gamesession.config.PresenceProperties; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceService; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceState; @@ -21,7 +22,7 @@ @Service public final class RedisAccountRecentPresenceService implements AccountRecentPresenceService { - private static final String RECENT_PRESENCE_KEY_TEMPLATE = "accountrecentpresence:%d:%d"; + private static final String RECENT_PRESENCE_KEY_TEMPLATE = "accountrecentpresence:%d:%s"; private final RedisTemplate redisTemplate; private final SessionRoutingNormalizationService sessionRoutingNormalizationService; @@ -58,7 +59,7 @@ public RedisAccountRecentPresenceService( @Override public void recordConnected(SessionContext context) { - if (context == null || context.tenantId() <= 0 || context.accountId() <= 0) { + if (context == null || context.tenantId() <= 0 || !context.hasAccountIdentity()) { return; } GameplayPresence presence = @@ -99,12 +100,12 @@ public void recordDisconnect(long sessionId, AccountRecentPresenceDisposition di } @Override - public Map findByAccountIds( - long tenantId, Collection accountIds) { + public Map findByAccountIds( + long tenantId, Collection accountIds) { ValueOperations valueOps = redisTemplate.opsForValue(); - LinkedHashMap results = new LinkedHashMap<>(); - for (Long accountId : accountIds) { - if (accountId == null || accountId <= 0 || valueOps == null) { + LinkedHashMap results = new LinkedHashMap<>(); + for (String accountId : accountIds) { + if (!AccountIds.isCanonicalNonNilUuid(accountId) || valueOps == null) { continue; } AccountRecentPresenceState state = @@ -138,7 +139,7 @@ private void write( } private RoutingSnapshot routingSnapshot(SessionContext context, GameplayPresence presence) { - if (context == null || context.tenantId() <= 0 || context.accountId() <= 0) { + if (context == null || context.tenantId() <= 0 || !context.hasAccountIdentity()) { return null; } GameplayPresence effectivePresence = @@ -180,13 +181,13 @@ private String blankToNull(String value) { return null; } - private String key(long tenantId, long accountId) { + private String key(long tenantId, String accountId) { return String.format(RECENT_PRESENCE_KEY_TEMPLATE, tenantId, accountId); } private record RoutingSnapshot( long tenantId, - long accountId, + String accountId, Long gameInstanceId, String playableStateScope, String worldSlug, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java index 47dcad6f62..b336d298f6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java @@ -13,6 +13,7 @@ import java.util.function.LongSupplier; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.GameplayPresence; import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; @@ -33,7 +34,7 @@ public final class RedisGameplayPresenceService implements GameplayPresenceServi private static final Logger logger = LoggingUtil.getLogger(RedisGameplayPresenceService.class); private static final String PRESENCE_KEY_TEMPLATE = "gameplaypresence:session:%d"; private static final String GAME_INSTANCE_SET_TEMPLATE = "gameplaypresence:%d:%d:sessions"; - private static final String ACCOUNT_SET_TEMPLATE = "gameplaypresence:%d:account:%d:sessions"; + private static final String ACCOUNT_SET_TEMPLATE = "gameplaypresence:%d:account:%s:sessions"; private static final Comparator ACCOUNT_PRESENCE_PREFERENCE = Comparator.comparing( GameplayPresence::lastMeaningfulActivityAtEpochMs, @@ -70,7 +71,10 @@ public RedisGameplayPresenceService( @Override public void registerConnected(SessionContext context) { - if (context == null || context.tenantId() <= 0 || context.gameInstanceId() <= 0) { + if (context == null + || !context.hasAccountIdentity() + || context.tenantId() <= 0 + || context.gameInstanceId() <= 0) { return; } ValueOperations valueOps = redisTemplate.opsForValue(); @@ -108,8 +112,7 @@ public void registerConnected(SessionContext context) { @Override public void removeBySessionId(long sessionId) { - ValueOperations valueOps = redisTemplate.opsForValue(); - GameplayPresence existing = (GameplayPresence) valueOps.get(presenceKey(sessionId)); + GameplayPresence existing = readPresence(presenceKey(sessionId)); redisTemplate.delete(presenceKey(sessionId)); if (existing != null) { String gameInstanceKey = gameInstanceKey(existing.tenantId(), existing.gameInstanceId()); @@ -123,7 +126,7 @@ public void removeBySessionId(long sessionId) { @Override public void setExplicitAfk(long sessionId, boolean explicitAfk) { ValueOperations valueOps = redisTemplate.opsForValue(); - GameplayPresence existing = (GameplayPresence) valueOps.get(presenceKey(sessionId)); + GameplayPresence existing = readPresence(presenceKey(sessionId)); if (existing == null) { return; } @@ -153,7 +156,7 @@ public void setExplicitAfk(long sessionId, boolean explicitAfk) { @Override public void recordCommandActivity(long sessionId, boolean meaningfulGameplayActivity) { ValueOperations valueOps = redisTemplate.opsForValue(); - GameplayPresence existing = (GameplayPresence) valueOps.get(presenceKey(sessionId)); + GameplayPresence existing = readPresence(presenceKey(sessionId)); if (existing == null) { return; } @@ -192,7 +195,6 @@ public List listConnectedByGameInstance(long tenantId, long ga return List.of(); } - ValueOperations valueOps = redisTemplate.opsForValue(); ArrayList matches = new ArrayList<>(); for (Object member : members) { String sessionIdText = String.valueOf(member); @@ -201,7 +203,7 @@ public List listConnectedByGameInstance(long tenantId, long ga setOps.remove(gameInstanceKey, sessionIdText); continue; } - GameplayPresence presence = (GameplayPresence) valueOps.get(presenceKey); + GameplayPresence presence = readPresence(presenceKey); if (presence == null) { setOps.remove(gameInstanceKey, sessionIdText); continue; @@ -221,17 +223,15 @@ public List listConnectedByGameInstance(long tenantId, long ga } @Override - public Map> listConnectedByAccountIds( - long tenantId, Collection accountIds) { + public Map> listConnectedByAccountIds( + long tenantId, Collection accountIds) { if (accountIds == null || accountIds.isEmpty()) { return Map.of(); } SetOperations setOps = redisTemplate.opsForSet(); - ValueOperations valueOps = redisTemplate.opsForValue(); - - LinkedHashMap> matches = new LinkedHashMap<>(); - for (Long accountId : accountIds) { - if (accountId == null || accountId <= 0) { + LinkedHashMap> matches = new LinkedHashMap<>(); + for (String accountId : accountIds) { + if (!AccountIds.isCanonicalNonNilUuid(accountId)) { continue; } String accountKey = accountKey(tenantId, accountId); @@ -247,12 +247,12 @@ public Map> listConnectedByAccountIds( setOps.remove(accountKey, sessionIdText); continue; } - GameplayPresence presence = (GameplayPresence) valueOps.get(presenceKey); + GameplayPresence presence = readPresence(presenceKey); if (presence == null) { setOps.remove(accountKey, sessionIdText); continue; } - if (presence.tenantId() != tenantId || presence.accountId() != accountId) { + if (presence.tenantId() != tenantId || !accountId.equals(presence.accountId())) { setOps.remove(accountKey, sessionIdText); continue; } @@ -268,8 +268,19 @@ public Map> listConnectedByAccountIds( @Override public Optional findConnectedBySessionId(long sessionId) { + return Optional.ofNullable(readPresence(presenceKey(sessionId))); + } + + private GameplayPresence readPresence(String key) { ValueOperations valueOps = redisTemplate.opsForValue(); - return Optional.ofNullable((GameplayPresence) valueOps.get(presenceKey(sessionId))); + try { + return (GameplayPresence) valueOps.get(key); + } catch (org.springframework.data.redis.serializer.SerializationException + | ClassCastException ex) { + // An older numeric Account carrier cannot be mapped to a UUID. Fail closed without + // mutating the retained record; the session must authenticate through its context path. + return null; + } } private String presenceKey(long sessionId) { @@ -289,7 +300,7 @@ private String gameInstanceKey(long tenantId, long gameInstanceId) { return String.format(GAME_INSTANCE_SET_TEMPLATE, tenantId, gameInstanceId); } - private String accountKey(long tenantId, long accountId) { + private String accountKey(long tenantId, String accountId) { return String.format(ACCOUNT_SET_TEMPLATE, tenantId, accountId); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java index ef48bccc22..fd6e49ca66 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java @@ -162,7 +162,15 @@ private String contextKey(long tenantId, long sessionId) { } private Optional readSessionContext(String key) { - SessionContext context = (SessionContext) redisTemplate.opsForValue().get(key); + SessionContext context; + try { + context = (SessionContext) redisTemplate.opsForValue().get(key); + } catch (org.springframework.data.redis.serializer.SerializationException + | ClassCastException ex) { + // Numeric Account identities from the old record shape are not convertible to UUIDs. + // Keep the retained value intact and require a fresh LOGIN before gameplay can resume. + return Optional.empty(); + } return Optional.ofNullable(context).map(SessionContext::withoutJwt); } @@ -193,7 +201,13 @@ private List watchKeys(SessionContext context) { private SessionContext readContext( org.springframework.data.redis.core.RedisOperations operations, String key) { - return (SessionContext) operations.opsForValue().get(key); + try { + return (SessionContext) operations.opsForValue().get(key); + } catch (org.springframework.data.redis.serializer.SerializationException + | ClassCastException ex) { + // The caller cannot authorize from an unreadable legacy identity; do not mutate it here. + return null; + } } private void addWatchKeys(Set watchKeys, SessionContext context) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java index 865e154509..22d6e6b24d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java @@ -796,7 +796,7 @@ private void maybeRefreshBootstrapShell(SessionContext existing, SessionContext new SessionContext( existing.sessionId(), existing.tenantId(), - 0L, + null, null, 0L, null, @@ -843,7 +843,7 @@ private void maybeRefreshBootstrapShell(SessionContext existing, SessionContext new SessionContext( incomingShell.sessionId(), incomingShell.tenantId(), - 0L, + null, null, 0L, null, @@ -861,7 +861,7 @@ private void maybeRefreshBootstrapShell(SessionContext existing, SessionContext } private boolean hasAuthenticatedOrGameplayBinding(SessionContext context) { - return context.accountId() > 0 + return context.hasAccountIdentity() || context.characterId() > 0 || context.gameInstanceId() > 0 || StringUtils.hasText(context.roomInstanceId()) @@ -882,7 +882,7 @@ private SessionContext bootstrapShell( return new SessionContext( sessionId, tenantId, - 0L, + null, null, 0L, null, diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index 8cf95022ce..e44dc7b3c0 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -701,7 +701,7 @@ private void seedLiveTargetSession() { STACK.seedLiveSession( 90210L, TENANT_ID, - Long.parseLong(ChatTestFixtures.PLAYER_SORA), + ChatTestFixtures.characterByName("Sora").getAccountId(), "sora@example.com", Long.parseLong(ChatTestFixtures.PLAYER_SORA), "Sora", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java index 5d27ddca8a..bf459e0a5f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java @@ -296,7 +296,7 @@ void effectiveSettingsEndpointMergesScopedOverridesForPersistedSession() { new SessionContext( 999L, 42L, - 100L, + "d3a8c26e-8253-4836-b01b-63c9b7fb1f75", "player@example.com", 55L, "Player", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java index 39b104b419..b643720f4b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java @@ -98,7 +98,10 @@ void setUp() { .delete(anyString()); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken("stub-token").setAccountId("7").build()); + AuthenticateResponse.newBuilder() + .setAuthToken("stub-token") + .setAccountId("c91fb96e-5ad8-4e4e-a12d-2838640093b2") + .build()); when(sharedSettingsAuthorityReader.readOverrides(anyLong(), org.mockito.ArgumentMatchers.any())) .thenReturn(ScopedSettingsSnapshot.empty()); when(commandService.enqueue(anyString(), anyString(), anyBoolean())) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 8c49a8113f..b6645e6705 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -243,7 +243,7 @@ void setUp() { return members == null ? java.util.Set.of() : new java.util.LinkedHashSet<>(members); }); when(moderationPolicyClient.evaluateGameplayAdmission( - org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())) + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -260,14 +260,14 @@ void setUp() { .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken("stub-token") - .setAccountId("123") + .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") .build()); org.mockito.Mockito.doAnswer( invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1"), + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1"), invocation.getArgument(0))) .when(accountClient) .getTenantMembershipForRuntime( @@ -297,7 +297,7 @@ void setUp() { net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("123") .setTenantId("22") - .setAccountId("123") + .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") .setName("Emberline") .setLevel(12) .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) @@ -655,7 +655,10 @@ void unexpectedDisconnectKeepsReplayEligibleForFreshReconnect() throws Exception GameplayAsyncAssertions.assertPresenceCountEventually( gameplayPresenceService, 22L, 1L, 0, java.time.Duration.ofSeconds(5)); assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isPresent(); - assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of(123L))).containsKey(123L); + assertThat( + accountRecentPresenceService.findByAccountIds( + 22L, List.of("f2ed193b-12c1-4c96-bcad-c162229af440"))) + .containsKey("f2ed193b-12c1-4c96-bcad-c162229af440"); List secondPayloads; try (GameplayWebSocketDriver client = openAdmittedGameplayDriver("42")) { @@ -971,7 +974,7 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)) .hasValueSatisfying( context -> { - assertThat(context.accountId()).isEqualTo(123L); + assertThat(context.accountId()).isEqualTo("f2ed193b-12c1-4c96-bcad-c162229af440"); assertThat(context.gameInstanceId()).isZero(); assertThat(context.characterId()).isZero(); assertThat(context.bootstrapGameInstanceId()).isEqualTo(2L); diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java index a425f43d3c..359ff46878 100644 --- a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java +++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java @@ -100,20 +100,21 @@ public List listConnectedByGameInstance(long tenantId, long ga } @Override - public Map> listConnectedByAccountIds( - long tenantId, Collection accountIds) { + public Map> listConnectedByAccountIds( + long tenantId, Collection accountIds) { if (accountIds == null || accountIds.isEmpty()) { return Map.of(); } - Map> results = new LinkedHashMap<>(); - for (Long accountId : accountIds) { - if (accountId == null || accountId <= 0) { + Map> results = new LinkedHashMap<>(); + for (String accountId : accountIds) { + if (accountId == null) { continue; } List matches = presences.values().stream() .filter( - presence -> presence.tenantId() == tenantId && presence.accountId() == accountId) + presence -> + presence.tenantId() == tenantId && accountId.equals(presence.accountId())) .sorted(ordering()) .toList(); if (!matches.isEmpty()) { 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 6ff042ab8c..9cef9d2d76 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 @@ -81,7 +81,8 @@ void directTextScopeRequestCarriesTypedCallerAndCompleteServerResolvedTarget() t ArgumentCaptor captor = ArgumentCaptor.forClass(IssueDirectTextConnectScopeRequest.class); verify(stub).issueDirectTextConnectScope(captor.capture()); - assertThat(captor.getValue().getPlayerContext().getAccountId()).isEqualTo("41"); + assertThat(captor.getValue().getPlayerContext().getAccountId()) + .isEqualTo("d0c68a37-5126-42d2-9506-8df13e97699e"); assertThat(captor.getValue().getPlayerContext().getSessionId()).isEqualTo("7"); assertThat(captor.getValue().getTenantId()).isEqualTo("22"); assertThat(captor.getValue().getWorldSlug()).isEqualTo("demo-world"); @@ -133,7 +134,7 @@ void directTextJoinRetryReusesExactContextScopeAndRequestId() throws Exception { private static PlayerExecutionContext directTextContext(String requestId) { return PlayerExecutionContext.newBuilder() - .setAccountId("41") + .setAccountId("d0c68a37-5126-42d2-9506-8df13e97699e") .setSessionId("7") .setTenantId("22") .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java index 370c36e59c..529c755b6a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java @@ -15,7 +15,8 @@ class EntityManagementClientTest { private static final SessionContext SESSION_CONTEXT = new SessionContext( - 41L, 22L, 0L, "", 123L, "", 1L, "R-1021", "", null, 1L, "world", "realm", 17L, "SHARED"); + 41L, 22L, null, "", 123L, "", 1L, "R-1021", "", null, 1L, "world", "realm", 17L, + "SHARED"); @Test void listRoomEntitiesFailsClosedWhenSessionContextDropsPartOfAdmittedRoutingBundle() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java index 49f6284c6b..159d4a4586 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java @@ -41,7 +41,21 @@ class GameLogicClientTest { private static final SessionContext SESSION_CONTEXT = new SessionContext( - 41L, 22L, 0L, "", 123L, "", 1L, "R-1021", "", null, 1L, "world", "realm", 17L, "SHARED"); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "", + 123L, + "", + 1L, + "R-1021", + "", + null, + 1L, + "world", + "realm", + 17L, + "SHARED"); @Test void resolveLookForwardsGameInstanceIdIntoRoomInstance() throws Exception { @@ -317,7 +331,7 @@ void pickupVisibleRoomItemForwardsRawReferenceAndSessionContextThroughGameLogic( PickupVisibleRoomItemRequest.newBuilder() .setTenantId("22") .setSessionId("41") - .setAccountId("0") + .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") .setCharacterId("123") .setGameInstanceId("1") .setRoomInstanceId("R-1021") @@ -422,7 +436,7 @@ void dropCarriedItemForwardsRawReferenceAndSessionContextThroughGameLogic() thro DropCarriedItemRequest.newBuilder() .setTenantId("22") .setSessionId("41") - .setAccountId("0") + .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") .setCharacterId("123") .setGameInstanceId("1") .setRoomInstanceId("R-1021") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java index 2db4c405ba..3386891ce7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java @@ -22,7 +22,16 @@ class ActionStateCommandHandlerTest { private final ActionStateCommandHandler handler = new ActionStateCommandHandler(gameLogicClient, Clock.fixed(NOW, ZoneOffset.UTC)); private final SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); @Test void blockAppliesShortLivedBlockingState() { @@ -106,7 +115,16 @@ void applyUsesTheProvidedEffectPayload() { @Test void blockRejectsPartialGameplayIdentityShell() { SessionContext partialContext = - new SessionContext(42L, 22L, 7L, "demo@example.com", 0L, null, 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 0L, + null, + 5L, + "R-1", + "jwt-token"); var result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java index 35c17c0645..cd01f82b63 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java @@ -266,7 +266,17 @@ void rejectsUnregisteredCommandEffectsFromTheAdmittedBundle() { } private SessionContext context() { - return new SessionContext(1L, 7L, 2L, "player", 3L, "hero", 44L, "room", "jwt", 0L); + return new SessionContext( + 1L, + 7L, + "5f7624ca-8aee-4d34-9cd8-3ba3a1815f30", + "player", + 3L, + "hero", + 44L, + "room", + "jwt", + 0L); } private GameInstance admittedInstance() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AfkCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AfkCommandHandlerTest.java index 8340547b0a..95e9418b08 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AfkCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AfkCommandHandlerTest.java @@ -25,7 +25,17 @@ class AfkCommandHandlerTest { void afkOnSetsExplicitAfkOnPresence() { SessionContext context = new SessionContext( - 7L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1021", null, "en-NZ", 1L); + 7L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1021", + null, + "en-NZ", + 1L); when(sessionAuthenticationService.resolveSessionContext("7")).thenReturn(Optional.of(context)); AfkCommandHandlingResult result = @@ -40,7 +50,17 @@ void afkOnSetsExplicitAfkOnPresence() { void afkOffClearsExplicitAfkOnPresence() { SessionContext context = new SessionContext( - 7L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1021", null, "en-NZ", 1L); + 7L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1021", + null, + "en-NZ", + 1L); when(sessionAuthenticationService.resolveSessionContext("7")).thenReturn(Optional.of(context)); AfkCommandHandlingResult result = @@ -72,7 +92,17 @@ void afkRequiresGameplayContext() { void afkRejectsPartialGameplayIdentityShellFromResolvedSession() { SessionContext context = new SessionContext( - 7L, 22L, 123L, "demo@example.com", 0L, null, 1L, "R-1021", null, "en-NZ", 1L); + 7L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 1L, + "R-1021", + null, + "en-NZ", + 1L); when(sessionAuthenticationService.resolveSessionContext("7")).thenReturn(Optional.of(context)); AfkCommandHandlingResult result = @@ -87,7 +117,17 @@ void afkRejectsPartialGameplayIdentityShellFromResolvedSession() { void directAfkRejectsPartialGameplayIdentityShell() { SessionContext context = new SessionContext( - 7L, 22L, 123L, "demo@example.com", 0L, null, 1L, "R-1021", null, "en-NZ", 1L); + 7L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 1L, + "R-1021", + null, + "en-NZ", + 1L); AfkCommandHandlingResult result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java index e065a0e8dd..52840feeee 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java @@ -43,7 +43,16 @@ void admittedAuthoredActionFailsClosedUntilItsDeclaredEffectHasARuntimeHandler() TextCommandInterpretationResult result = handler.handle( - new SessionContext(1L, 1L, 2L, "player@example.com", 3L, "Player", 4L, "room", "jwt"), + new SessionContext( + 1L, + 1L, + "11111111-1111-4111-8111-111111111111", + "player@example.com", + 3L, + "Player", + 4L, + "room", + "jwt"), command); assertFalse(result.commandResult().accepted()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java index 13063bac47..1a999bea77 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java @@ -87,7 +87,15 @@ void rejectsAuthoredActionsWithoutGameplayContext() { private static SessionContext context() { return new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, + 22L, + "d0c68a37-5126-42d2-9506-8df13e97699e", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); } private static TextCommand authoredAction(String commandId, String rawLine, List args) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java index 930b9ec39c..e7a3a8ac22 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java @@ -43,7 +43,7 @@ class CommunicationCommandHandlerTest { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "emberline@example.com", 911L, "Emberline", @@ -144,7 +144,7 @@ void tellRequiresOnlineTarget() { Character.newBuilder() .setId("300") .setTenantId("22") - .setAccountId("700") + .setAccountId("b96201c6-8894-49ea-8f60-3f0b4ee72f5d") .setName("Sora") .build())); when(sessionAuthenticationService.resolveByGameplayName(22L, 1L, "Sora")) @@ -164,7 +164,17 @@ void tellRequiresOnlineTarget() { void tellFailsClosedWhenTargetGameplayBindingNormalizesAway() { SessionContext normalizedTarget = new SessionContext( - 77L, 22L, 700L, "sora@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 77L, + 22L, + "b96201c6-8894-49ea-8f60-3f0b4ee72f5d", + "sora@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); when(entityManagementClient.findCharacterByName( sessionContext, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "Sora")) .thenReturn( @@ -172,7 +182,7 @@ void tellFailsClosedWhenTargetGameplayBindingNormalizesAway() { Character.newBuilder() .setId("300") .setTenantId("22") - .setAccountId("700") + .setAccountId("b96201c6-8894-49ea-8f60-3f0b4ee72f5d") .setName("Sora") .build())); when(sessionAuthenticationService.resolveByGameplayName(22L, 1L, "Sora")) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ContainerCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ContainerCommandHandlerTest.java index 7624a3e4fc..8abb5e0546 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ContainerCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ContainerCommandHandlerTest.java @@ -26,7 +26,15 @@ class ContainerCommandHandlerTest { private final ContainerCommandHandler handler = new ContainerCommandHandler(gameLogicClient); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 911L, + "Emberline", + 77L, + "R-7", + "jwt-token"); @Test void containerViewReturnsStructuredContents() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java index 211de4cf9c..9113c00828 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java @@ -24,7 +24,15 @@ class EquipmentCommandHandlerTest { private final EquipmentCommandHandler handler = new EquipmentCommandHandler(gameLogicClient); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 911L, + "Emberline", + 77L, + "R-7", + "jwt-token"); @Test void wearWithoutItemReferenceFailsFast() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java index 0e83bed47b..feac69aeb4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java @@ -37,11 +37,15 @@ import org.mockito.Mockito; class FriendsCommandHandlerTest { + private static final String CALLER_ACCOUNT_ID = "d0c68a37-5126-42d2-9506-8df13e97699e"; + private static final String FRIEND_ACCOUNT_ID = "550e8400-e29b-41d4-a716-446655440000"; + private static final String SECOND_FRIEND_ACCOUNT_ID = "6ba7b810-9dad-41d1-80b4-00c04fd430c8"; + private static final SessionContext GAMEPLAY_CONTEXT = new SessionContext( 7L, 1L, - 41L, + "d0c68a37-5126-42d2-9506-8df13e97699e", "demo@example.com", 99L, "Emberline", @@ -70,16 +74,16 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); FriendsCommandHandler handler = newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterId("99") .setCharacterName("Sora") @@ -117,7 +121,7 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { .satisfies( entry -> { assertThat(entry.friendLinkId()).isNull(); - assertThat(entry.friendAccountId()).isEqualTo(77L); + assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(entry.status()).isEqualTo("active"); assertThat(entry.linkedAtEpochMs()).isNull(); assertThat(entry.displayName()).isEqualTo("Sora"); @@ -127,7 +131,8 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Sora [acct #77] - online in Demo World / Live Realm (idle)"); + .contains( + "Sora [acct #" + FRIEND_ACCOUNT_ID + "] - online in Demo World / Live Realm (idle)"); Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.any(), @@ -146,16 +151,16 @@ void friendsFallsBackToBoundedOfflineLabelWhenDetailsAreSuppressed() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(false) .setLastSeenAtMs( Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) @@ -183,7 +188,7 @@ void friendsFallsBackToBoundedOfflineLabelWhenDetailsAreSuppressed() { entry -> { assertThat(entry.friendLinkId()).isNull(); assertThat(entry.status()).isEqualTo("active"); - assertThat(entry.displayName()).isEqualTo("Friend #77"); + assertThat(entry.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + ""); assertThat(entry.lastSeenAtEpochMs()) .isEqualTo(Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()); }); @@ -202,15 +207,15 @@ void friendsOnlyPresenceDoesNotExposeDisconnectDispositionInText() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(false) .setLastSeenAtMs( Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) @@ -244,13 +249,15 @@ void friendsAddLinksAccountScopedFriendAndReturnsNotice() { ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); FriendsCommandHandler handler = newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); - when(socialGroupsClient.addFriend(1L, 41L, 77L)) + when(socialGroupsClient.addFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(AddFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("ADD", "77"), "friends add 77"), + TextCommandType.FRIENDS, + java.util.List.of("ADD", FRIEND_ACCOUNT_ID), + "friends add " + FRIEND_ACCOUNT_ID), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isTrue(); @@ -258,12 +265,12 @@ void friendsAddLinksAccountScopedFriendAndReturnsNotice() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Friend #77 added."); + assertThat(output.text()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + " added."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("ADD"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); - assertThat(mutation.displayName()).isEqualTo("Friend #77"); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(mutation.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + ""); assertThat(mutation.characterName()).isNull(); assertThat(mutation.ordinal()).isNull(); }); @@ -273,7 +280,8 @@ void friendsAddLinksAccountScopedFriendAndReturnsNotice() { Mockito.argThat( gameplayCommand -> "FRIENDS".equals(gameplayCommand.getCommandName()) - && "friends add 77".equals(gameplayCommand.getCommandText()))); + && ("friends add " + FRIEND_ACCOUNT_ID) + .equals(gameplayCommand.getCommandText()))); } @Test @@ -283,7 +291,8 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE) @@ -292,10 +301,10 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterName("Sora") .setVisibilityPolicy( @@ -323,9 +332,9 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) .contains("Friends ONLINE [1/2]:") - .contains("1) Sora [acct #77] - online"); + .contains("1) Sora [acct #" + FRIEND_ACCOUNT_ID + "] - online"); Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); + .listFriends(1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); } @Test @@ -335,7 +344,8 @@ void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE) @@ -344,10 +354,10 @@ void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(2) - .setFriendAccountId("88") + .setFriendAccountId(SECOND_FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("88") + .setFriendAccountId(SECOND_FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterName("Secret") .setVisibilityPolicy( @@ -374,10 +384,10 @@ void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { .satisfies( entry -> { assertThat(entry.ordinal()).isEqualTo(2); - assertThat(entry.friendAccountId()).isEqualTo(88L); + assertThat(entry.friendAccountId()).isEqualTo(SECOND_FRIEND_ACCOUNT_ID); assertThat(entry.online()).isNull(); assertThat(entry.characterName()).isNull(); - assertThat(entry.displayName()).isEqualTo("Friend #88"); + assertThat(entry.displayName()).isEqualTo("Friend #" + SECOND_FRIEND_ACCOUNT_ID + ""); assertThat(entry.visibilityPolicy()).isNull(); }); assertThat( @@ -388,7 +398,7 @@ void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { .contains("presence unavailable") .doesNotContain("Secret"); Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE); + .listFriends(1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE); } @Test @@ -398,19 +408,19 @@ void friendsRedactsLegacyHiddenStaffEntryButPreservesRelationshipRow() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(4) .setFriendLinkId("12") - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setCreatedAtMs(1_744_336_000_000L) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterId("99") .setCharacterName("Sora") @@ -445,10 +455,10 @@ void friendsRedactsLegacyHiddenStaffEntryButPreservesRelationshipRow() { ((FriendPresenceViewOutput) result.outputs().getFirst().payload()).friends().getFirst(); assertThat(entry.ordinal()).isEqualTo(4); assertThat(entry.friendLinkId()).isEqualTo(12L); - assertThat(entry.friendAccountId()).isEqualTo(77L); + assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(entry.status()).isEqualTo("active"); assertThat(entry.linkedAtEpochMs()).isEqualTo(1_744_336_000_000L); - assertThat(entry.displayName()).isEqualTo("Friend #77"); + assertThat(entry.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + ""); assertThat(entry.online()).isNull(); assertThat(entry.worldSlug()).isNull(); assertThat(entry.worldDisplayName()).isNull(); @@ -464,7 +474,7 @@ void friendsRedactsLegacyHiddenStaffEntryButPreservesRelationshipRow() { new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Friend #77") + .contains("Friend #" + FRIEND_ACCOUNT_ID + "") .contains("presence unavailable") .doesNotContain("Sora") .doesNotContain("Demo World") @@ -478,7 +488,8 @@ void friendsSharedFiltersCanonicalRosterByPlayableStateScope() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED) @@ -487,10 +498,10 @@ void friendsSharedFiltersCanonicalRosterByPlayableStateScope() { .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterName("Sora") .setPlayableStateScope( @@ -517,7 +528,7 @@ void friendsSharedFiltersCanonicalRosterByPlayableStateScope() { .satisfies( entry -> { assertThat(entry.ordinal()).isEqualTo(1); - assertThat(entry.friendAccountId()).isEqualTo(77L); + assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(entry.playableStateScope()).isEqualTo("SHARED"); }); assertThat( @@ -526,7 +537,7 @@ void friendsSharedFiltersCanonicalRosterByPlayableStateScope() { .render(result.outputs().getFirst())) .contains("Friends SHARED [1/2]:"); Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED); + .listFriends(1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED); } @Test @@ -536,7 +547,8 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT) @@ -545,10 +557,10 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(false) .setLastSeenAtMs( Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) @@ -571,7 +583,7 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { assertThat(view.matchCount()).isEqualTo(1); assertThat(view.friends()) .singleElement() - .satisfies(entry -> assertThat(entry.friendAccountId()).isEqualTo(77L)); + .satisfies(entry -> assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID)); } @Test @@ -581,7 +593,7 @@ void friendsSummaryUsesCanonicalRosterSummarySurface() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendRosterSummary(1L, 41L)) + when(socialGroupsClient.getFriendRosterSummary(1L, CALLER_ACCOUNT_ID)) .thenReturn( GetFriendRosterSummaryResponse.newBuilder() .setSummary( @@ -640,7 +652,7 @@ void friendsSummaryUsesCanonicalRosterSummarySurface() { .doesNotContain("Visibility unspecified") .contains("Scope shared: 2") .contains("Scope isolated: 1"); - Mockito.verify(socialGroupsClient).getFriendRosterSummary(1L, 41L); + Mockito.verify(socialGroupsClient).getFriendRosterSummary(1L, CALLER_ACCOUNT_ID); } @Test @@ -656,8 +668,12 @@ void friendsAddResolvesCharacterNameToCanonicalAccountId() { Mockito.eq("Sora"))) .thenReturn( Optional.of( - Character.newBuilder().setId("99").setAccountId("77").setName("Sora").build())); - when(socialGroupsClient.addFriend(1L, 41L, 77L)) + Character.newBuilder() + .setId("99") + .setAccountId(FRIEND_ACCOUNT_ID) + .setName("Sora") + .build())); + when(socialGroupsClient.addFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(AddFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = @@ -671,15 +687,15 @@ void friendsAddResolvesCharacterNameToCanonicalAccountId() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Sora [acct #77] added."); + assertThat(output.text()).isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] added."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("ADD"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(mutation.displayName()).isEqualTo("Sora"); assertThat(mutation.characterName()).isEqualTo("Sora"); }); - Mockito.verify(socialGroupsClient).addFriend(1L, 41L, 77L); + Mockito.verify(socialGroupsClient).addFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID); } @Test @@ -689,13 +705,15 @@ void friendsRemoveUnlinksAccountScopedFriendAndReturnsNotice() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriend(1L, 41L, 77L)) + when(socialGroupsClient.removeFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(RemoveFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("REMOVE", "77"), "FRIENDS REMOVE 77"), + TextCommandType.FRIENDS, + java.util.List.of("REMOVE", FRIEND_ACCOUNT_ID), + "FRIENDS REMOVE " + FRIEND_ACCOUNT_ID), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isTrue(); @@ -703,12 +721,12 @@ void friendsRemoveUnlinksAccountScopedFriendAndReturnsNotice() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Friend #77 removed."); + assertThat(output.text()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + " removed."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); - assertThat(mutation.displayName()).isEqualTo("Friend #77"); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(mutation.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + ""); assertThat(mutation.characterName()).isNull(); assertThat(mutation.ordinal()).isNull(); }); @@ -727,8 +745,12 @@ void friendsRemoveResolvesCharacterNameToCanonicalAccountId() { Mockito.eq("Sora"))) .thenReturn( Optional.of( - Character.newBuilder().setId("99").setAccountId("77").setName("Sora").build())); - when(socialGroupsClient.removeFriend(1L, 41L, 77L)) + Character.newBuilder() + .setId("99") + .setAccountId(FRIEND_ACCOUNT_ID) + .setName("Sora") + .build())); + when(socialGroupsClient.removeFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(RemoveFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = @@ -744,15 +766,16 @@ void friendsRemoveResolvesCharacterNameToCanonicalAccountId() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Sora [acct #77] removed."); + assertThat(output.text()) + .isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] removed."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(mutation.displayName()).isEqualTo("Sora"); assertThat(mutation.characterName()).isEqualTo("Sora"); }); - Mockito.verify(socialGroupsClient).removeFriend(1L, 41L, 77L); + Mockito.verify(socialGroupsClient).removeFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID); } @Test @@ -762,17 +785,17 @@ void friendsRemoveByOrdinalUsesCanonicalRemoveSurface() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( RemoveFriendByOrdinalResponse.newBuilder() .setSuccess(true) .setRemovedFriend( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setCharacterName("Sora") .setVisibilityPolicy( FriendPresenceVisibilityPolicy @@ -792,16 +815,17 @@ void friendsRemoveByOrdinalUsesCanonicalRemoveSurface() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Sora [acct #77] removed."); + assertThat(output.text()) + .isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] removed."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(mutation.displayName()).isEqualTo("Sora"); assertThat(mutation.characterName()).isEqualTo("Sora"); assertThat(mutation.ordinal()).isEqualTo(1); }); - Mockito.verify(socialGroupsClient).removeFriendByOrdinal(1L, 41L, 1); + Mockito.verify(socialGroupsClient).removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1); } @Test @@ -811,7 +835,7 @@ void friendsRemoveByOrdinalRejectsMalformedReturnedFriendAccountId() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( RemoveFriendByOrdinalResponse.newBuilder() .setSuccess(true) @@ -845,18 +869,18 @@ void friendsShowReturnsCanonicalFriendDetailView() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriend(1L, 41L, 77L)) + when(socialGroupsClient.getFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn( GetFriendResponse.newBuilder() .setFriend( FriendRosterEntry.newBuilder() .setFriendLinkId("11") - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setCreatedAtMs(Instant.parse("2026-04-10T01:02:03Z").toEpochMilli()) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterName("Sora") .setWorldDisplayName("Demo World") @@ -877,7 +901,9 @@ void friendsShowReturnsCanonicalFriendDetailView() { TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("SHOW", "77"), "FRIENDS SHOW 77"), + TextCommandType.FRIENDS, + java.util.List.of("SHOW", FRIEND_ACCOUNT_ID), + "FRIENDS SHOW " + FRIEND_ACCOUNT_ID), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isTrue(); @@ -886,7 +912,7 @@ void friendsShowReturnsCanonicalFriendDetailView() { .extracting(PlayerOutput::payload) .isInstanceOf(FriendDetailViewOutput.class); FriendDetailViewOutput detail = (FriendDetailViewOutput) result.outputs().getFirst().payload(); - assertThat(detail.friend().friendAccountId()).isEqualTo(77L); + assertThat(detail.friend().friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(detail.friend().friendLinkId()).isEqualTo(11L); assertThat(detail.friend().characterName()).isEqualTo("Sora"); assertThat(detail.friend().playableStateScope()).isEqualTo("SHARED"); @@ -895,7 +921,7 @@ void friendsShowReturnsCanonicalFriendDetailView() { new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Friend Sora [acct #77]") + .contains("Friend Sora [acct #" + FRIEND_ACCOUNT_ID + "]") .contains("Presence: online in Demo World / Live Realm (idle)") .contains("State scope: shared") .contains("Pointer version: 17"); @@ -908,16 +934,16 @@ void friendsShowByOrdinalRedactsMissingPolicyAndRendersDetail() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.getFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( GetFriendByOrdinalResponse.newBuilder() .setFriend( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterName("Sora") .setWorldDisplayName("Demo World") @@ -937,7 +963,7 @@ void friendsShowByOrdinalRedactsMissingPolicyAndRendersDetail() { assertThat(result.commandResult().accepted()).isTrue(); FriendDetailViewOutput detail = (FriendDetailViewOutput) result.outputs().getFirst().payload(); assertThat(detail.friend().ordinal()).isEqualTo(1); - assertThat(detail.friend().displayName()).isEqualTo("Friend #77"); + assertThat(detail.friend().displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + ""); assertThat(detail.friend().online()).isNull(); assertThat(detail.friend().characterName()).isNull(); assertThat(detail.friend().worldDisplayName()).isNull(); @@ -949,7 +975,7 @@ void friendsShowByOrdinalRedactsMissingPolicyAndRendersDetail() { .contains("Presence: presence unavailable") .contains("Roster entry: #1") .doesNotContain("Sora", "Demo World", "online", "idle"); - Mockito.verify(socialGroupsClient).getFriendByOrdinal(1L, 41L, 1); + Mockito.verify(socialGroupsClient).getFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1); } @Test @@ -1003,7 +1029,7 @@ void friendsRemoveRejectsUnknownRosterOrdinal() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( RemoveFriendByOrdinalResponse.newBuilder() .setSuccess(false) @@ -1093,16 +1119,18 @@ void friendsListTreatsMalformedFriendLinkIdAsAbsent() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() .setFriendLinkId("abc") - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setPresence( - FriendPresenceEntry.newBuilder().setFriendAccountId("77").build()) + FriendPresenceEntry.newBuilder() + .setFriendAccountId(FRIEND_ACCOUNT_ID) + .build()) .build()) .build()); @@ -1126,7 +1154,7 @@ void friendsListRejectsMalformedFriendAccountIdPayload() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( @@ -1155,7 +1183,7 @@ void friendsVisibilityShowsCurrentCanonicalPolicy() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendPresencePolicy(1L, 41L)) + when(socialGroupsClient.getFriendPresencePolicy(1L, CALLER_ACCOUNT_ID)) .thenReturn( GetFriendPresencePolicyResponse.newBuilder() .setCurrentPolicy( @@ -1191,7 +1219,7 @@ void friendsVisibilityShowsCurrentCanonicalPolicy() { .render(result.outputs().getFirst())) .contains("Friend presence visibility: FRIENDS_ONLY") .contains("Use FRIENDS VISIBILITY ."); - Mockito.verify(socialGroupsClient).getFriendPresencePolicy(1L, 41L); + Mockito.verify(socialGroupsClient).getFriendPresencePolicy(1L, CALLER_ACCOUNT_ID); } @Test @@ -1201,7 +1229,7 @@ void friendsVisibilityViewFailsClosedWhenCanonicalPolicyReadIsUnavailable() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendPresencePolicy(1L, 41L)) + when(socialGroupsClient.getFriendPresencePolicy(1L, CALLER_ACCOUNT_ID)) .thenReturn( GetFriendPresencePolicyResponse.newBuilder() .setError( @@ -1234,7 +1262,7 @@ void friendsVisibilityUpdatesCanonicalPolicy() { newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); when(socialGroupsClient.updateFriendPresencePolicy( 1L, - 41L, + CALLER_ACCOUNT_ID, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE)) .thenReturn( @@ -1271,7 +1299,7 @@ void friendsVisibilityUpdatesCanonicalPolicy() { Mockito.verify(socialGroupsClient) .updateFriendPresencePolicy( 1L, - 41L, + CALLER_ACCOUNT_ID, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); Mockito.verify(scriptEventPublisher) @@ -1289,7 +1317,7 @@ void friendsVisibilityUpdateFailsClosedWhenCanonicalPolicyUpdateIsUnavailable() socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); when(socialGroupsClient.updateFriendPresencePolicy( 1L, - 41L, + CALLER_ACCOUNT_ID, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE)) .thenReturn( @@ -1342,7 +1370,7 @@ void friendsVisibilityRejectsReservedHiddenStaffPolicy() { .isEqualTo("ERROR INVALID_ARGUMENT FRIENDS VISIBILITY "); assertThat(result.outputs().getFirst().text()).doesNotContain("HIDDEN_STAFF"); Mockito.verify(socialGroupsClient, Mockito.never()) - .updateFriendPresencePolicy(Mockito.anyLong(), Mockito.anyLong(), Mockito.any()); + .updateFriendPresencePolicy(Mockito.anyLong(), Mockito.anyString(), Mockito.any()); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java index 0e9dd6a666..b004fdd3e5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java @@ -241,7 +241,15 @@ void helpIndexHidesHistoryWhenFeatureDisabled() { (context, topic) -> Optional.empty(), null, capabilitiesResolver(false)); SessionContext context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 42L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = disabledHandler.handle( @@ -260,7 +268,15 @@ void helpIndexHidesEveryDisabledStandardCapabilityFamily() { CommandCapabilitiesTestSupport.resolver(false, false, false, true)); SessionContext context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 42L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = disabledHandler.handle( @@ -280,7 +296,15 @@ void helpHistoryTopicUnavailableWhenFeatureDisabled() { (context, topic) -> Optional.empty(), null, capabilitiesResolver(false)); SessionContext context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 42L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = disabledHandler.handle( @@ -298,7 +322,15 @@ void helpHistoryTopicAvailableWhenFeatureEnabled() { (context, topic) -> Optional.empty(), null, capabilitiesResolver(true)); SessionContext context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 42L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = enabledHandler.handle( @@ -321,7 +353,15 @@ void publishedGameAuthoredTopicOverridesPlatformTopicForAdmittedSession() { HelpCommandHandler authoredHelpHandler = new HelpCommandHandler(reader, null, null); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt"); TextCommandInterpretationResult result = authoredHelpHandler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java index 2d20e1651b..75bee23eb2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java @@ -20,7 +20,15 @@ class HelpTextCommandDispatchHandlerTest { void publishesCommandEventForGameplayScopedHelp() { SessionContext context = new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, + 22L, + "d0c68a37-5126-42d2-9506-8df13e97699e", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryCommandHandlerTest.java index d69cd7549a..79c8676d9b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryCommandHandlerTest.java @@ -193,7 +193,15 @@ void rejectsNonPositiveHistoryCountWithoutReadingStorage() { private SessionContext standardContext() { return new SessionContext( - 22L, 7L, 99L, "demo@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 22L, + 7L, + "a3be406d-718c-419a-afcf-0afbc2e8e451", + "demo@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); } private HistoryCommandHandler handler( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java index 4859f2ae05..0977252b70 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java @@ -31,7 +31,16 @@ void dispatchesToHistoryHandler() { Mockito.when(historyStorageService.findRecent(7L, 9L, 7001L, 2)) .thenReturn(List.of("LOOK", "SAY hi")); SessionContext context = - new SessionContext(22L, 7L, 99L, "demo@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + new SessionContext( + 22L, + 7L, + "a3be406d-718c-419a-afcf-0afbc2e8e451", + "demo@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/InventoryCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/InventoryCommandHandlerTest.java index 8e29601ed9..66e3f2f904 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/InventoryCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/InventoryCommandHandlerTest.java @@ -26,7 +26,15 @@ class InventoryCommandHandlerTest { private final InventoryCommandHandler handler = new InventoryCommandHandler(gameLogicClient); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 911L, + "Emberline", + 77L, + "R-7", + "jwt-token"); @Test void inventoryReturnsStructuredViewFromRuntimeContract() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java index b716bebb5c..292dc42846 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java @@ -30,7 +30,15 @@ class ItemCommandHandlerTest { scriptEventPublisher); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 911L, + "Emberline", + 77L, + "R-7", + "jwt-token"); @Test void recordsInvocationForSuccessfulItemCommand() { 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 e837236084..2f7247492e 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 @@ -49,6 +49,8 @@ @SuppressWarnings("unchecked") class LoginCommandHandlerTest { private static final String AUTH_TOKEN = "mock-jwt"; + private static final String ACCOUNT_77 = "774f987b-6650-4d04-8e0f-441867c17923"; + private static final String ACCOUNT_99 = "998a7412-13c4-4dbc-86d9-8f40aee3c6f1"; private final GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); @@ -72,7 +74,10 @@ void setUp() { stubSessionContext(bootstrapShell(1L, 1L)); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("77").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_77) + .build()); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 1L)) .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 1L))); sessionRoutingNormalizationService = @@ -373,7 +378,7 @@ void bareLoginDoesNotPromoteVerifiedFirstPartyContextWithoutAccountExchange() { new SessionContext( 1L, 22L, - 0L, + null, null, 0L, null, @@ -393,7 +398,7 @@ void bareLoginDoesNotPromoteVerifiedFirstPartyContextWithoutAccountExchange() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 99L, + ACCOUNT_99, 22L, "demo", "production", @@ -419,7 +424,7 @@ void bareLoginDoesNotPromoteVerifiedFirstPartyContextWithoutAccountExchange() { verify(accountClient, never()).requestEmailLoginOtp(anyString()); verify(sessionContextService, never()).save(any(SessionContext.class)); verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); - assertEquals(0L, shell.accountId()); + assertNull(shell.accountId()); assertNull(shell.jwt()); assertEquals(1L, shell.bootstrapGameInstanceId()); assertEquals("shell-world", shell.worldSlug()); @@ -443,7 +448,7 @@ void bareLoginForDifferentVerifiedSubjectClearsOldAccountBeforeReturningUnavaila stubMutableSessionContext(accountA); FirstPartyConnectContext verifiedAccountBContext = new FirstPartyConnectContext( - 99L, + ACCOUNT_99, 33L, "demo", "production", @@ -468,7 +473,7 @@ void bareLoginForDifferentVerifiedSubjectClearsOldAccountBeforeReturningUnavaila verify(sessionContextService).save(savedContext.capture()); SessionContext accountBShell = savedContext.getValue(); assertEquals(33L, accountBShell.tenantId()); - assertEquals(0L, accountBShell.accountId()); + assertNull(accountBShell.accountId()); assertNull(accountBShell.loginName()); assertNull(accountBShell.jwt()); assertFalse(accountBShell.hasGameplayBinding()); @@ -521,7 +526,7 @@ void bareLoginForSameVerifiedSubjectPreservesRetryableSessionState() { verify(gameplayPresenceLifecycleService, never()) .clearGameplayBinding(any(SessionContext.class), anyString()); verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); - assertEquals(77L, existing.accountId()); + assertEquals(ACCOUNT_77, existing.accountId()); assertEquals(AUTH_TOKEN, existing.jwt()); assertTrue(existing.hasGameplayBinding()); assertEquals("scope-stale", existing.connectScopeId()); @@ -546,8 +551,7 @@ void bareLoginForSameAccountInDifferentTenantClearsOldTenantBeforeReturningUnava "request-tenant-b", "gateway-tenant-b"); when(firstPartyConnectContextRegistry.find(1L)).thenReturn(Optional.of(verifiedTenantBContext)); - when(gameInstanceRepository.findById(2L)) - .thenReturn(Optional.of(buildInstance(2L, 33L, accountA.accountId()))); + when(gameInstanceRepository.findById(2L)).thenReturn(Optional.of(buildInstance(2L, 33L, 77L))); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(33L, 2L)) .thenReturn(List.of(pointer("demo", "production", 33L, 2L, 1L))); @@ -559,7 +563,7 @@ void bareLoginForSameAccountInDifferentTenantClearsOldTenantBeforeReturningUnava verify(sessionContextService).save(savedContext.capture()); SessionContext tenantBShell = savedContext.getValue(); assertEquals(33L, tenantBShell.tenantId()); - assertEquals(0L, tenantBShell.accountId()); + assertNull(tenantBShell.accountId()); assertNull(tenantBShell.jwt()); assertFalse(tenantBShell.hasGameplayBinding()); assertEquals(2L, tenantBShell.bootstrapGameInstanceId()); @@ -589,7 +593,7 @@ void credentialLoginPreservesBootstrapTargetButDropsSubjectBoundConnectScope() { new SessionContext( 1L, 22L, - 0L, + null, null, 0L, null, @@ -607,7 +611,10 @@ void credentialLoginPreservesBootstrapTargetButDropsSubjectBoundConnectScope() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate("other@example.com", "swordfish")) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_99) + .build()); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -615,7 +622,7 @@ void credentialLoginPreservesBootstrapTargetButDropsSubjectBoundConnectScope() { ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); SessionContext saved = captor.getValue(); - assertEquals(99L, saved.accountId()); + assertEquals(ACCOUNT_99, saved.accountId()); assertEquals(1L, saved.bootstrapGameInstanceId()); assertEquals("demo", saved.worldSlug()); assertEquals("production", saved.realmSlug()); @@ -635,7 +642,7 @@ void bareLoginFailsUnavailableForPersistedFirstPartyContextFallback() { new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, null, 0L, null, @@ -670,7 +677,7 @@ void bareLoginRejectsIncompletePersistedFirstPartyContextWhenRegistryEntryIsMiss new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, null, 0L, null, @@ -706,7 +713,7 @@ void bareLoginDoesNotFallBackToRawPersistedFirstPartyContextWhenTenantScopedSess new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, null, 0L, null, @@ -739,7 +746,7 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerTenantIsInvalid() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, + ACCOUNT_77, 0L, "demo", "production", @@ -764,7 +771,7 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerGameInstanceIdIsInvalid() .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, + ACCOUNT_77, 22L, "demo", "production", @@ -791,7 +798,7 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerWorldOrRealmIsMissing() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, + ACCOUNT_77, 22L, " ", "production", @@ -816,7 +823,16 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerRealmIsMissing() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, 22L, "demo", " ", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"))); + ACCOUNT_77, + 22L, + "demo", + " ", + 1L, + 1L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"))); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -834,7 +850,7 @@ void bareLoginRejectsStalePointerVersion() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, + ACCOUNT_77, 22L, "demo", "production", @@ -874,7 +890,7 @@ void successfulLoginStoresSessionContext() { net.firedevops.firemud.gamesession.service.SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals(77L, context.accountId()); + assertEquals(ACCOUNT_77, context.accountId()); assertEquals(0L, context.characterId()); assertEquals(0L, context.gameInstanceId()); assertNull(context.roomInstanceId()); @@ -891,7 +907,7 @@ void loginUsesBootstrappedGameInstanceInsteadOfTransportSessionId() { GameInstance instance = buildInstance(99L, 22L, 77L); SessionContext bootstrapContext = - new SessionContext(12345L, 22L, 0L, null, 0L, null, 99L, null, null); + new SessionContext(12345L, 22L, null, null, 0L, null, 99L, null, null); when(sessionContextService.findBySessionId(12345L)).thenReturn(Optional.of(bootstrapContext)); when(sessionContextService.findByTenantAndSessionId(22L, 12345L)) .thenReturn(Optional.of(bootstrapContext)); @@ -939,7 +955,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, "demo@example.com", 88L, "Sora", @@ -960,7 +976,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, "demo@example.com", 88L, "Sora", @@ -983,7 +999,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals(77L, context.accountId()); + assertEquals(ACCOUNT_77, context.accountId()); assertEquals(88L, context.characterId()); assertEquals(1L, context.gameInstanceId()); assertEquals("R-2045", context.roomInstanceId()); @@ -1003,12 +1019,15 @@ void reloginAsDifferentAccountClearsExistingGameplayBinding() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_99) + .build()); SessionContext existing = new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, "demo@example.com", 88L, "Sora", @@ -1034,7 +1053,7 @@ void reloginAsDifferentAccountClearsExistingGameplayBinding() { .clearGameplayBinding(existing, "LOGIN_ACCOUNT_CHANGED"); inOrder.verify(sessionContextService).save(captor.capture()); SessionContext context = captor.getValue(); - assertEquals(99L, context.accountId()); + assertEquals(ACCOUNT_99, context.accountId()); assertEquals("other@example.com", context.loginName()); assertEquals(0L, context.characterId()); assertNull(context.characterName()); @@ -1057,7 +1076,7 @@ void verifiedConnectForDifferentTenantClearsPriorGameplayBindingWithoutPromoting new SessionContext( 1L, 33L, - 77L, + ACCOUNT_77, "old@example.com", 88L, "Sora", @@ -1079,7 +1098,7 @@ void verifiedConnectForDifferentTenantClearsPriorGameplayBindingWithoutPromoting .thenReturn( Optional.of( new FirstPartyConnectContext( - 99L, + ACCOUNT_99, 22L, "demo", "production", @@ -1101,7 +1120,7 @@ void verifiedConnectForDifferentTenantClearsPriorGameplayBindingWithoutPromoting inOrder.verify(gameplayPresenceLifecycleService).clearGameplayBinding(prior, "LOGIN_FAILED"); inOrder.verify(sessionContextService).save(saved.capture()); assertEquals(22L, saved.getValue().tenantId()); - assertEquals(0L, saved.getValue().accountId()); + assertNull(saved.getValue().accountId()); assertEquals(0L, saved.getValue().characterId()); assertEquals(0L, saved.getValue().gameInstanceId()); assertEquals("demo", saved.getValue().worldSlug()); @@ -1127,7 +1146,10 @@ void reloginAsDifferentAccountDoesNotReplaceContextWhenPresenceClearFails() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_99) + .build()); SessionContext existing = staleGameplayContext(1L); stubSessionContext(existing); Mockito.doThrow(new IllegalStateException("presence clear unavailable")) @@ -1164,7 +1186,7 @@ void reloginClearsStaleGameplayBindingBeforeRefreshingLoginContext() { SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals(77L, context.accountId()); + assertEquals(ACCOUNT_77, context.accountId()); assertEquals(0L, context.characterId()); assertNull(context.characterName()); assertEquals(0L, context.gameInstanceId()); @@ -1233,7 +1255,7 @@ void invalidCredentialsDropPartialProjectedRoutingBundleDuringFailedLoginCleanup new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, "demo@example.com", 88L, "Sora", @@ -1272,7 +1294,10 @@ void authenticatedNonOwnerAccountIsAcceptedAndStored() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_99) + .build()); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -1280,7 +1305,7 @@ void authenticatedNonOwnerAccountIsAcceptedAndStored() { assertEquals("Logged in as demo@example.com", joinedOutputText(result.outputs())); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); - assertEquals(99L, captor.getValue().accountId()); + assertEquals(ACCOUNT_99, captor.getValue().accountId()); assertEquals("demo@example.com", captor.getValue().loginName()); assertEquals(77L, instance.getOwnerAccountId()); } @@ -1698,7 +1723,7 @@ private static SessionContext bootstrapShell(long sessionId, long bootstrapGameI return new SessionContext( sessionId, 22L, - 0L, + null, null, 0L, null, @@ -1717,7 +1742,7 @@ private static SessionContext staleGameplayContext(long pointerVersion) { return new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, "demo@example.com", 88L, "Sora", @@ -1738,7 +1763,7 @@ private static SessionContext staleGameplayContextWithoutSelector(long pointerVe return new SessionContext( 1L, 22L, - 77L, + ACCOUNT_77, "demo@example.com", 88L, "Sora", @@ -1764,7 +1789,7 @@ private static void assertClearedSessionContext( String expectedConnectRequestId) { assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals(0L, context.accountId()); + assertNull(context.accountId()); assertNull(context.loginName()); assertEquals(0L, context.characterId()); assertNull(context.characterName()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java index a2175fe179..155e4ff6bb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java @@ -51,7 +51,7 @@ void logoutPreservesDurableReplayContextWithoutStoppingSharedRuntime() { new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "demo", @@ -88,7 +88,7 @@ void logoutStopsIsolatedRuntime() { new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "demo", @@ -115,7 +115,7 @@ void logoutDoesNotStopSharedRuntimeWhenCurrentRuntimeAuthorityIsShared() { new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "demo", @@ -158,7 +158,7 @@ void logoutDoesNotStopSharedRuntimeWhenNormalizationClearsProjectedBinding() { new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "demo", @@ -186,7 +186,7 @@ void logoutDoesNotStopRuntimeWhenPointerAuthorityIsUnknown() { new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "demo", @@ -215,7 +215,7 @@ void logoutDoesNotStopRuntimeWhenCurrentRuntimeAuthorityIsAmbiguous() { new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "demo", @@ -271,7 +271,7 @@ void logoutDoesNotStopRuntimeWhenSingularRuntimeAuthorityIsIncomplete() { new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "demo", @@ -314,7 +314,7 @@ void logoutSkipsGameplayCleanupForPartialGameplayShell() { new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "demo", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookCommandHandlerTest.java index 180d6e8d3b..3939ca10ce 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookCommandHandlerTest.java @@ -54,7 +54,7 @@ class LookCommandHandlerTest { lookCacheService, outputRenderer); private final SessionContext sessionContext = - new SessionContext(1L, 22L, 123L, 911L, 0L, "R-42", "jwt"); + new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 911L, 0L, "R-42", "jwt"); private final LookResult lookResult = LookResult.newBuilder() .setRoomInstance(RoomInstanceRef.newBuilder().setRoomInstanceId("R-1021").build()) @@ -217,7 +217,16 @@ void quickLookUsesSharedLookupButShorterRenderVariant() { @Test void cachesRenderedLookByGameplayInstanceWhenAvailable() { SessionContext playedContext = - new SessionContext(17L, 22L, 123L, "demo", 911L, "demo", 77L, "R-42", "jwt"); + new SessionContext( + 17L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo", + 911L, + "demo", + 77L, + "R-42", + "jwt"); when(sessionAuthenticationService.resolveSessionContext("played")) .thenReturn(Optional.of(playedContext)); when(gameLogicClient.resolveLook(playedContext, "R-42", "")).thenReturn(lookResult); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java index a69f16082f..d0fa1bcf18 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java @@ -58,7 +58,15 @@ void setUp() { meterRegistry); context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 7L, "R-1021", "jwt-token"); + 42L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 911L, + "Emberline", + 7L, + "R-1021", + "jwt-token"); } @Test 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 5d6212b61a..16dd3baa3a 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 @@ -50,6 +50,7 @@ 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 ObjectMapper JSON = new ObjectMapper(); private final SessionAuthenticationService sessionAuthenticationService = Mockito.mock(SessionAuthenticationService.class); @@ -104,7 +105,7 @@ void setUp() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); - when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong())) + when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -117,7 +118,7 @@ void setUp() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1")), + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -157,7 +158,15 @@ void setUp() { @Test void playPromotesSessionIntoGameplay() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "1", @@ -176,7 +185,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -194,7 +203,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -212,7 +221,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -231,7 +240,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -251,13 +260,21 @@ void playPromotesSessionIntoGameplay() { @Test void playRejectsModerationPolicyDeniedAdmission() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, actor("7001", "demo", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); - when(moderationPolicyClient.evaluateGameplayAdmission(22L, 123L)) + when(moderationPolicyClient.evaluateGameplayAdmission(22L, PLAYER_ACCOUNT_ID)) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(false) @@ -277,7 +294,15 @@ void playRejectsModerationPolicyDeniedAdmission() { @Test void playUsesResolvedEntityManagementCharacterIdWhenNameExists() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "2", @@ -300,7 +325,7 @@ void playUsesResolvedEntityManagementCharacterIdWhenNameExists() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 9007L, "Emberline", @@ -318,7 +343,7 @@ void playUsesResolvedEntityManagementCharacterIdWhenNameExists() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 9007L, "Emberline", @@ -338,7 +363,7 @@ void playUsesResolvedEntityManagementCharacterIdWhenNameExists() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 9007L, "Emberline", @@ -358,7 +383,15 @@ void playUsesResolvedEntityManagementCharacterIdWhenNameExists() { @Test void playRejectsMalformedResolvedCharacterId() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "2", @@ -389,7 +422,15 @@ void playRejectsMalformedResolvedCharacterId() { @Test void playRejectsMissingOwnedActorWithoutSynthesizingIdentity() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster("1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); @@ -405,7 +446,15 @@ void playRejectsMissingOwnedActorWithoutSynthesizingIdentity() { @Test void playRejectsAmbiguousOwnedRosterWhenActorIsNotSelected() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "1", @@ -422,11 +471,19 @@ void playRejectsAmbiguousOwnedRosterWhenActorIsNotSelected() { @Test void playRejectsAnotherAccountsActorEvenWhenNameMatches() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); Character foreign = actor("7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED).toBuilder() - .setAccountId("999") + .setAccountId("6ba7b810-9dad-41d1-80b4-00c04fd430c8") .build(); stubOwnedRoster("2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, foreign); @@ -445,7 +502,15 @@ void playRejectsAnotherAccountsActorEvenWhenNameMatches() { @ValueSource(strings = {"tenant", "scope"}) void playRejectsRosterRowsOutsideSelectedTenantOrScope(String mismatch) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); Character valid = actor("7001", "demo", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Character mismatched = @@ -468,7 +533,7 @@ void playRejectsStaleRetainedActorWhenSelectedRosterNoLongerContainsIt() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "Emberline", @@ -498,7 +563,15 @@ void playRejectsStaleRetainedActorWhenSelectedRosterNoLongerContainsIt() { @Test void playRejectsEntityRosterErrorWithoutBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); Mockito.doReturn( ListCharactersByAccountResponse.newBuilder() @@ -516,7 +589,15 @@ void playRejectsEntityRosterErrorWithoutBinding() { @Test void playReadsEntitlementMembershipAndGrantBeforeActorRoster() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "41", @@ -559,7 +640,7 @@ void playResumeDoesNotPublishSpawnEvent() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -595,9 +676,27 @@ void playResumeDoesNotPublishSpawnEvent() { @Test void playIgnoresStaleExistingBindingAfterNormalization() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); SessionContext clearedExisting = - new SessionContext(9L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "old-jwt", 1L); + new SessionContext( + 9L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + null, + "old-jwt", + 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "1", @@ -616,7 +715,7 @@ void playIgnoresStaleExistingBindingAfterNormalization() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -638,12 +737,20 @@ void playIgnoresStaleExistingBindingAfterNormalization() { @Test void playIgnoresExistingBindingWithoutRoomRegion() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); SessionContext existingWithoutRoom = new SessionContext( 9L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -674,7 +781,7 @@ void playIgnoresExistingBindingWithoutRoomRegion() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -695,13 +802,23 @@ void playIgnoresExistingBindingWithoutRoomRegion() { @Test void firstPartyPlayRejectsMismatchedConnectScope() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 41L); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "first-party:123", + 0L, + null, + 0L, + null, + null, + 41L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, + PLAYER_ACCOUNT_ID, 22L, "demo", "production", @@ -727,13 +844,23 @@ void firstPartyPlayRejectsMismatchedConnectScope() { @Test void firstPartyPlayRejectsMismatchedWorldSlug() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "first-party:123", + 0L, + null, + 0L, + null, + null, + 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, + PLAYER_ACCOUNT_ID, 22L, "sandbox", "production", @@ -755,13 +882,32 @@ void firstPartyPlayRejectsMismatchedWorldSlug() { void firstPartyPlayRejectsStalePointerVersion() { gameplayCatalogProperties.getWorlds().get(0).getRealms().get(0).setPointerVersion(9L); SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "first-party:123", + 0L, + null, + 0L, + null, + null, + 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 8L, "scope-1", "jti-1", "req-1", "gw-1"))); + PLAYER_ACCOUNT_ID, + 22L, + "demo", + "production", + 1L, + 8L, + "scope-1", + "jti-1", + "req-1", + "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -773,13 +919,32 @@ void firstPartyPlayRejectsStalePointerVersion() { @Test void firstPartyPlayRejectsConnectContextMissingRealmSlug() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "first-party:123", + 0L, + null, + 0L, + null, + null, + 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "demo", null, 1L, 1L, "scope-1", "jti-1", "req-1", "gw-1"))); + PLAYER_ACCOUNT_ID, + 22L, + "demo", + null, + 1L, + 1L, + "scope-1", + "jti-1", + "req-1", + "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -793,13 +958,32 @@ void firstPartyPlayRejectsConnectContextMissingRealmSlug() { @Test void firstPartyPlayRejectsConnectContextMissingConnectScope() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "first-party:123", + 0L, + null, + 0L, + null, + null, + 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 1L, "", "jti-1", "req-1", "gw-1"))); + PLAYER_ACCOUNT_ID, + 22L, + "demo", + "production", + 1L, + 1L, + "", + "jti-1", + "req-1", + "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -811,13 +995,32 @@ void firstPartyPlayRejectsConnectContextMissingConnectScope() { @Test void firstPartyPlayRejectsConnectContextMissingConnectRequest() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "first-party:123", + 0L, + null, + 0L, + null, + null, + 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 1L, "scope-1", "jti-1", "", "gw-1"))); + PLAYER_ACCOUNT_ID, + 22L, + "demo", + "production", + 1L, + 1L, + "scope-1", + "jti-1", + "", + "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -839,7 +1042,8 @@ void playWithoutSessionReturnsLoginRequired() { @Test void playWithoutArgumentsReturnsInvalidArgument() { - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = + new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -851,7 +1055,8 @@ void playWithoutArgumentsReturnsInvalidArgument() { @Test void unknownWorldReturnsSelectionGuidance() { - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = + new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -864,7 +1069,8 @@ void unknownWorldReturnsSelectionGuidance() { @Test void sandboxWithoutCharacterReturnsSelectionRequired() { - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = + new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -885,7 +1091,8 @@ void sandboxWithoutCharacterReturnsSelectionRequired() { @Test void explicitRealmWithoutCharacterReturnsCharacterSelectionGuidance() { - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = + new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -915,7 +1122,8 @@ void playRejectsIsolatedStateRealm() { .getRealms() .get(1) .setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = + new SessionContext(1L, 22L, "f2ed193b-12c1-4c96-bcad-c162229af440", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -938,13 +1146,31 @@ void firstPartyPlayAcceptsNonProductionRealmWhenScopeMatches() { .get(1) .setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 41L); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "first-party:123", + 0L, + null, + 0L, + null, + null, + 41L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "sandbox", "preview", 41L, 1L, "scope-1", "jti-1", "req-1", + PLAYER_ACCOUNT_ID, + 22L, + "sandbox", + "preview", + 41L, + 1L, + "scope-1", + "jti-1", + "req-1", "gw-1"))); stubOwnedRoster( "41", @@ -976,7 +1202,7 @@ void firstPartyPlayFallsBackToPersistedSelectorWhenRegistryEntryIsMissing() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "first-party:123", 0L, null, @@ -1019,7 +1245,7 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "first-party:123", 0L, null, @@ -1054,7 +1280,15 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( @Test void activePublicMembershipDeniedByPolicyReturnsWorldAccessDeniedWithoutBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1064,7 +1298,8 @@ void activePublicMembershipDeniedByPolicyReturnsWorldAccessDeniedWithoutBinding( .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support - .RuntimeMembershipTestFixtures.active(123L, 22L, "2")) + .RuntimeMembershipTestFixtures.active( + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "2")) .toBuilder() .setGameplayAdmissionAllowed(false) .build(), @@ -1084,7 +1319,16 @@ void activePublicMembershipDeniedByPolicyReturnsWorldAccessDeniedWithoutBinding( @Test void playNonPublicRealmRequiresExistingAdmissibleMembership() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1094,7 +1338,7 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)), + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)), invocation.getArgument(0))); PlayCommandHandlingResult result = @@ -1127,7 +1371,7 @@ void playNonPublicLeftMembershipRequiresEnrollment() { var leftMembership = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - 123L, 22L, List.of("designer", "player"))); + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player"))); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) .thenAnswer( @@ -1165,7 +1409,7 @@ void playBoundNonPublicLeftMembershipRequiresEnrollmentAndClearsBinding() { var leftMembership = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - 123L, 22L, List.of("designer", "player"))); + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player"))); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) .thenAnswer( @@ -1377,7 +1621,16 @@ void playInvisibleRealmWithUnavailableGrantFailsClosed(String errorCode) { @ValueSource(strings = {"NOT_FOUND", "PERMISSION_DENIED"}) void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String errorCode) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1403,7 +1656,16 @@ void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String e @Test void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1413,7 +1675,7 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)), + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)), invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1432,7 +1694,15 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { @ValueSource(strings = {"", "ACTIVE", "UNKNOWN"}) void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleState) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1441,7 +1711,7 @@ void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleSta var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)); + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)); var malformedLifecycle = response.toBuilder() .setMembershipLifecycleState(lifecycleState) @@ -1467,7 +1737,15 @@ void malformedMembershipLifecycleCannotBecomeJoinOpportunity(String lifecycleSta @ValueSource(strings = {"MISSING", "INACTIVE"}) void nonAdmittingMembershipLifecycleWithAdmissionFlagIsDenied(String lifecycleState) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1477,10 +1755,10 @@ void nonAdmittingMembershipLifecycleWithAdmissionFlagIsDenied(String lifecycleSt "INACTIVE".equals(lifecycleState) ? freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive(123L, 22L, "3")) + .inactive("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "3")) : freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)); + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)); return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures .echoRequestId( response.toBuilder().setGameplayAdmissionAllowed(true).build(), @@ -1501,7 +1779,7 @@ void playLeftMembershipRequiresJoinForPublicProduction() { var leftMembership = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - 123L, 22L, List.of("designer", "player"))); + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player"))); var leftEvent = MembershipAuthorityEventV1Codec.verify( leftMembership.getOutboxSourceEvidence(0).getCanonicalEventJson()); @@ -1563,11 +1841,20 @@ void playLeftMembershipRequiresJoinForPublicProduction() { @Test void playBoundLeftMembershipRequiresJoinAndClearsBindingForPublicProduction() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); var leftMembership = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - 123L, 22L, List.of("designer", "player"))); + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player"))); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1642,7 +1929,15 @@ void contradictoryLeftEventEvidenceCannotAdmitGameplay(String defect) { @ValueSource(strings = {"ENTITLEMENT_UNAVAILABLE", "AUTH_UNAVAILABLE"}) void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1652,7 +1947,7 @@ void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)), + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1680,7 +1975,15 @@ void playEntitlementFailureMasksMissingPublicMembership(String errorCode) { @Test void playBillingDenialMasksMissingPublicMembership() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1690,7 +1993,7 @@ void playBillingDenialMasksMissingPublicMembership() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)), + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1718,7 +2021,15 @@ void playBillingDenialMasksMissingPublicMembership() { @Test void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1728,7 +2039,7 @@ void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)), + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1758,7 +2069,15 @@ void playPublicPolicyDenialMasksMissingMembershipWithoutBindingOrEntityCalls() { @Test void playExistingPublicMemberCanEnterWhenNewPublicJoinsAreDisabled() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "1", @@ -1785,7 +2104,15 @@ void playExistingPublicMemberCanEnterWhenNewPublicJoinsAreDisabled() { @Test void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEntityCalls() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1795,7 +2122,7 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L)), + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L)), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1826,7 +2153,16 @@ void playReturnsJoinRequiredAfterFreshPublicPolicyAllowsJoinWithoutBindingOrEnti @ValueSource(strings = {"malformed", "future", "stale"}) void playWhenMembershipAuthorityTimestampIsUnsafeFailsClosed(String defect) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1835,7 +2171,7 @@ void playWhenMembershipAuthorityTimestampIsUnsafeFailsClosed(String defect) { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1")) + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")) .toBuilder() .setEvaluatedAt( switch (defect) { @@ -1867,7 +2203,16 @@ void playWhenMembershipAuthorityTimestampIsUnsafeFailsClosed(String defect) { @Test void playWhenMembershipRequestIdEchoDoesNotMatchFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1878,7 +2223,8 @@ void playWhenMembershipRequestIdEchoDoesNotMatchFailsClosed() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support - .RuntimeMembershipTestFixtures.active(123L, 22L, "1")), + .RuntimeMembershipTestFixtures.active( + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")), invocation.getArgument(0)); return response.toBuilder().setRequestId("wrong-request-id").build(); }); @@ -1899,7 +2245,16 @@ void playWhenMembershipRequestIdEchoDoesNotMatchFailsClosed() { @Test void playWhenMembershipAuthorityGenerationIsMissingFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1910,7 +2265,8 @@ void playWhenMembershipAuthorityGenerationIsMissingFailsClosed() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support - .RuntimeMembershipTestFixtures.active(123L, 22L, "1")), + .RuntimeMembershipTestFixtures.active( + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")), invocation.getArgument(0)); return response.toBuilder().clearMembershipAuthorityGeneration().build(); }); @@ -1930,7 +2286,16 @@ void playWhenMembershipAuthorityGenerationIsMissingFailsClosed() { @Test void playWhenMembershipCanonicalEventChangesWithValidDigestFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1939,7 +2304,7 @@ void playWhenMembershipCanonicalEventChangesWithValidDigestFailsClosed() { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1")); + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")); String changedCanonicalJson = resealWithMembershipVersion( response.getOutboxSourceEvidence(0).getCanonicalEventJson(), "2"); @@ -1967,7 +2332,16 @@ void playWhenMembershipCanonicalEventChangesWithValidDigestFailsClosed() { @Test void playWhenMembershipCanonicalEventDigestDoesNotMatchFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -1976,7 +2350,7 @@ void playWhenMembershipCanonicalEventDigestDoesNotMatchFailsClosed() { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1")); + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")); String changedCanonicalJson = changeCanonicalEventWithoutResealing( response.getOutboxSourceEvidence(0).getCanonicalEventJson()); @@ -2004,7 +2378,16 @@ void playWhenMembershipCanonicalEventDigestDoesNotMatchFailsClosed() { @Test void playWhenMembershipCanonicalEventContentIsAbsentFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -2013,7 +2396,7 @@ void playWhenMembershipCanonicalEventContentIsAbsentFailsClosed() { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1")); + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")); var source = response.getOutboxSourceEvidence(0).toBuilder().clearCanonicalEventJson(); return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures @@ -2043,7 +2426,16 @@ void playWhenMembershipCanonicalEventContentIsAbsentFailsClosed() { @Test void playWhenMembershipResponseDiffersFromCanonicalEventFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -2052,7 +2444,7 @@ void playWhenMembershipResponseDiffersFromCanonicalEventFailsClosed() { var response = freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1")); + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")); var mismatchedResponse = response.toBuilder() .putMembershipVersion("00000000-0000-0000-0000-000000000022", "2") @@ -2083,7 +2475,15 @@ void playWhenMembershipResponseDiffersFromCanonicalEventFailsClosed() { @ValueSource(strings = {"target", "version", "stale", "future", "malformed"}) void unsafeEntitlementSnapshotFailsClosed(String defect) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); String tenantId = "target".equals(defect) ? "23" : "22"; long entitlementVersion = "version".equals(defect) ? 0L : 1L; @@ -2119,7 +2519,16 @@ void unsafeEntitlementSnapshotFailsClosed(String defect) { @Test void playBlockedByEntitlementsReturnsBillingBlocked() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -2148,7 +2557,16 @@ void playBlockedByEntitlementsReturnsBillingBlocked() { @Test void playMapsNonAuthorityEntitlementFailureToBillingBlocked() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -2180,7 +2598,16 @@ void playMapsNonAuthorityEntitlementFailureToBillingBlocked() { @ValueSource(strings = {"AUTH_UNAVAILABLE", "FAILED_PRECONDITION"}) void playWhenMembershipAuthorityUnavailableFailsClosed(String errorCode) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -2211,7 +2638,16 @@ void playWhenMembershipAuthorityUnavailableFailsClosed(String errorCode) { @Test void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -2241,7 +2677,16 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { @Test void playWhenEntitlementRuntimeReadIsDisabledPreservesExistingBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -2268,7 +2713,16 @@ void playWhenEntitlementRuntimeReadIsDisabledPreservesExistingBinding() { @Test void staleRoomContextFallsBackToFreshEntry() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, null, "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + null, + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 123L)) .thenReturn(Optional.empty()); @@ -2283,7 +2737,7 @@ void staleRoomContextFallsBackToFreshEntry() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "demo", @@ -2309,7 +2763,7 @@ void staleRoomContextFallsBackToFreshEntry() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "demo", @@ -2328,7 +2782,7 @@ void staleRoomContextFallsBackToFreshEntry() { new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "demo", @@ -2403,7 +2857,7 @@ private static GetTenantMembershipForRuntimeResponse freshMembership( private static GetTenantMembershipForRuntimeResponse leftMembershipWithDefect(String defect) { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( - 123L, 22L, List.of("designer", "player")); + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, List.of("designer", "player")); var builder = response.toBuilder(); switch (defect) { case "membership-generation" -> { @@ -2470,7 +2924,7 @@ private static Character actor(String id, String name, PlayableStateScope scope) return Character.newBuilder() .setId(id) .setTenantId("22") - .setAccountId("123") + .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") .setName(name) .setPlayableStateScope(scope) .build(); @@ -2484,7 +2938,7 @@ private SessionContext previewRealmContext() { return new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "Emberline", @@ -2503,7 +2957,7 @@ private SessionContext unboundContext() { return new SessionContext( 1L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 0L, null, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java index d70f74a2b9..0da523d2c8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java @@ -27,7 +27,9 @@ void doesNotRecordHistoryDisplayCommands() { Mockito.mock(PlayerCommandHistoryStorageService.class); SessionAuthenticationService sessionAuthenticationService = Mockito.mock(SessionAuthenticationService.class); - SessionContext context = new SessionContext(1L, 7L, 9L, 17L, 11L, "R-1", "token"); + SessionContext context = + new SessionContext( + 1L, 7L, "3a16e242-3467-4d98-906f-71d47b888b5e", 17L, 11L, "R-1", "token"); List storedCommands = new ArrayList<>(List.of("LOOK")); when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); when(storage.findRecent(7L, 11L, 17L, 10)) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java index 5b76eb52ba..d542c3d86d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java @@ -239,6 +239,7 @@ void quarantinesCapabilityResolutionFailure() { } private SessionContext gameplayContext(long characterId) { - return new SessionContext(1L, 7L, 9L, characterId, 11L, "R-1", "token"); + return new SessionContext( + 1L, 7L, "11111111-1111-4111-8111-111111111111", characterId, 11L, "R-1", "token"); } } 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 6bd5db2d25..4e48829cd7 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 @@ -162,14 +162,17 @@ void setUp() { .thenReturn(CommandEnqueueResult.success()); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken("jwt").setAccountId("77").build()); + AuthenticateResponse.newBuilder() + .setAuthToken("jwt") + .setAccountId("550e8400-e29b-41d4-a716-446655440000") + .build()); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) .thenAnswer( invocation -> { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - 77L, 22L, "1") + "550e8400-e29b-41d4-a716-446655440000", 22L, "1") .toBuilder() .setEvaluatedAt(Instant.now().toString()) .build(); @@ -183,7 +186,7 @@ void setUp() { Mockito.anyString(), Mockito.anyString())) .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); - when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong())) + when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -209,7 +212,7 @@ void setUp() { net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") .setTenantId("22") - .setAccountId("77") + .setAccountId("550e8400-e29b-41d4-a716-446655440000") .setName("Emberline") .setLevel(12) .setPlayableStateScope( @@ -462,7 +465,7 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { invocation -> { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - 77L, 22L, "2"); + "550e8400-e29b-41d4-a716-446655440000", 22L, "2"); var deniedResponse = response.toBuilder() .setGameplayAdmissionAllowed(false) @@ -492,7 +495,8 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { assertEquals("PLAY_REQUIRED", lookAfterDeniedReconnect.commandResult().errorCode()); assertTrue(sessionAuthenticationService.isAuthenticated("1")); assertEquals( - 77L, sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow().accountId()); + "550e8400-e29b-41d4-a716-446655440000", + sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow().accountId()); TextCommandInterpretationResult joinAfterDeniedPlay = interpreter.interpret("1", "JOIN demo", false); assertEquals("AUTH_UNAVAILABLE", joinAfterDeniedPlay.commandResult().errorCode()); @@ -620,7 +624,7 @@ private static SessionContext bootstrapShell(long sessionId, long bootstrapGameI return new SessionContext( sessionId, 22L, - 0L, + null, null, 0L, null, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/StatusCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/StatusCommandHandlerTest.java index 2cc4258542..37d1bc8d9f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/StatusCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/StatusCommandHandlerTest.java @@ -23,7 +23,15 @@ class StatusCommandHandlerTest { new StatusCommandHandler(gameLogicClient, scriptEventPublisher); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 911L, + "Emberline", + 77L, + "R-7", + "jwt-token"); @Test void statusProjectsEvaluatedResourcesAndVisibleConditionsInStableOrder() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java index 66cd161139..f525dac286 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java @@ -29,7 +29,15 @@ void rejectsDisabledStandardOptionalCommandsBeforeDispatch( TextCommandDispatcher dispatcher = Mockito.mock(TextCommandDispatcher.class); SessionContext gameplayContext = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt"); when(sessionAuthenticationService.resolveSessionContext("41")) .thenReturn(Optional.of(gameplayContext)); TextCommandInterpreter interpreter = @@ -62,7 +70,15 @@ void failsClosedWhenCapabilityResolutionIsUnavailable() { Mockito.mock(EffectiveCommandCapabilitiesSettingsResolver.class); SessionContext gameplayContext = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt"); when(sessionAuthenticationService.resolveSessionContext("41")) .thenReturn(Optional.of(gameplayContext)); when(capabilitiesResolver.isEnabled(PlayerCommandCapability.SOCIAL, 22L, 7L)) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java index c227399313..26db5eb219 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java @@ -23,7 +23,17 @@ void interpretUsesRegistryAndDispatcherInsteadOfCommandTypeBranches() { Mockito.mock(SessionAuthenticationService.class); SessionContext gameplayContext = new SessionContext( - 1L, 7L, 8L, "player@example.com", 9L, "Demo", 10L, "R-1", "token", "en-NZ", 10L); + 1L, + 7L, + "e87d27af-9f41-4575-915d-d76d1a5359c9", + "player@example.com", + 9L, + "Demo", + 10L, + "R-1", + "token", + "en-NZ", + 10L); Mockito.when(authenticationService.resolveSessionContext("1")) .thenReturn(Optional.of(gameplayContext)); 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 6b58e72501..68783f263b 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 @@ -161,7 +161,7 @@ void setUp() { .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken("auth-token") - .setAccountId("123") + .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") .build()); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -169,7 +169,7 @@ void setUp() { invocation -> { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - 123L, 22L, "1") + "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1") .toBuilder() .setEvaluatedAt(Instant.now().toString()) .build(); @@ -183,7 +183,7 @@ void setUp() { Mockito.anyString(), Mockito.anyString())) .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); - when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong())) + when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -409,7 +409,7 @@ void setUp() { net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") .setTenantId("22") - .setAccountId("123") + .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") .setName("Emberline") .setLevel(12) .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) @@ -815,7 +815,7 @@ void takeAfterPlayEnqueuesDurableMutation() { @Test void bootstrapContextWithoutAuthenticatedAccountStillRequiresLogin() { ((InMemorySessionContextService) sessionContextService) - .save(new SessionContext(55L, 22L, 0L, null, 0L, null, 77L, null, null)); + .save(new SessionContext(55L, 22L, null, null, 0L, null, 77L, null, null)); TextCommandInterpretationResult interpretation = interpreter.interpret("55", "LOOK", false); @@ -852,7 +852,17 @@ void gameplayAfterLoginBeforePlayReturnsPlayRequired() { @Test void gameplayWithRoomOnlyPartialShellStillReturnsPlayRequired() { ((InMemorySessionContextService) sessionContextService) - .save(new SessionContext(56L, 22L, 123L, "demo@example.com", 0L, null, 0L, "R-7", null)); + .save( + new SessionContext( + 56L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "R-7", + null)); TextCommandInterpretationResult interpretation = interpreter.interpret("56", "LOOK", false); @@ -1078,7 +1088,7 @@ private static SessionContext bootstrapShell(long sessionId, long bootstrapGameI return new SessionContext( sessionId, 22L, - 0L, + null, null, 0L, null, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java index f41613d0c4..6be059a452 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java @@ -33,7 +33,16 @@ void whoShowsBoundedEmptyStateWhenNobodyIsConnected() { TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.WHO, java.util.List.of(), "who"), - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext( + 2L, + 22L, + "22222222-2222-4222-8222-222222222222", + "second@example.com", + 102L, + "Ben", + 7L, + "R-1", + null)); assertThat(result.commandResult().accepted()).isTrue(); assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [0]: "); @@ -55,32 +64,79 @@ void whoGroupsElevatedPlayersFirstAndPlayersAfterward() { new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); String godJwt = jwtUtil.generateToken( - "1", + "11111111-1111-4111-8111-111111111111", java.util.Map.of( - "accountId", "1", "scopedRoles", java.util.Map.of("22", java.util.List.of("god")))); + "accountId", + "11111111-1111-4111-8111-111111111111", + "scopedRoles", + java.util.Map.of("22", java.util.List.of("god")))); gameplayPresenceService.registerConnected( - new SessionContext(1L, 22L, 1L, "god@example.com", 101L, "Aster", 7L, "R-1", godJwt)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "god@example.com", + 101L, + "Aster", + 7L, + "R-1", + godJwt)); String moderatorJwt = jwtUtil.generateToken( - "4", + "89ce29d0-212d-4769-892a-67299d123e17", java.util.Map.of( "accountId", - "4", + "89ce29d0-212d-4769-892a-67299d123e17", "scopedRoles", java.util.Map.of("22", java.util.List.of("moderator")))); gameplayPresenceService.registerConnected( new SessionContext( - 4L, 22L, 4L, "moderator@example.com", 104L, "Dara", 7L, "R-1", moderatorJwt)); + 4L, + 22L, + "89ce29d0-212d-4769-892a-67299d123e17", + "moderator@example.com", + 104L, + "Dara", + 7L, + "R-1", + moderatorJwt)); gameplayPresenceService.registerConnected( - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext( + 2L, + 22L, + "22222222-2222-4222-8222-222222222222", + "second@example.com", + 102L, + "Ben", + 7L, + "R-1", + null)); gameplayPresenceService.registerConnected( - new SessionContext(3L, 22L, 3L, "third@example.com", 103L, "Cara", 7L, "R-1", null)); + new SessionContext( + 3L, + 22L, + "33333333-3333-4333-8333-333333333333", + "third@example.com", + 103L, + "Cara", + 7L, + "R-1", + null)); TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.WHO, java.util.List.of(), "WHO"), - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext( + 2L, + 22L, + "22222222-2222-4222-8222-222222222222", + "second@example.com", + 102L, + "Ben", + 7L, + "R-1", + null)); assertThat(result.commandResult().accepted()).isTrue(); assertThat(render(result)).isEqualTo("Gods [2]: Aster, Dara\nPlayers [2]: Ben, Cara"); @@ -93,21 +149,38 @@ void whoShowsGlobalOnlyRolesAsPlayers() { new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); String globalOnlyJwt = jwtUtil.generateToken( - "1", + "c91fb96e-5ad8-4e4e-a12d-2838640093b2", java.util.Map.of( "accountId", - "1", + "c91fb96e-5ad8-4e4e-a12d-2838640093b2", "globalRoles", java.util.List.of("platformAdmin", "support", "billingAdmin", "god", "moderator"))); gameplayPresenceService.registerConnected( new SessionContext( - 1L, 22L, 1L, "staff@example.com", 101L, "Aster", 7L, "R-1", globalOnlyJwt)); + 1L, + 22L, + "c91fb96e-5ad8-4e4e-a12d-2838640093b2", + "staff@example.com", + 101L, + "Aster", + 7L, + "R-1", + globalOnlyJwt)); TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.WHO, java.util.List.of(), "WHO"), - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext( + 2L, + 22L, + "5f7624ca-8aee-4d34-9cd8-3ba3a1815f30", + "second@example.com", + 102L, + "Ben", + 7L, + "R-1", + null)); assertThat(result.commandResult().accepted()).isTrue(); assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [1]: Aster"); @@ -120,15 +193,42 @@ void whoOmitsRemovedPresenceAfterLogoutLikeCleanup() { new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); gameplayPresenceService.registerConnected( - new SessionContext(1L, 22L, 1L, "first@example.com", 101L, "Aster", 7L, "R-1", null)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "first@example.com", + 101L, + "Aster", + 7L, + "R-1", + null)); gameplayPresenceService.registerConnected( - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext( + 2L, + 22L, + "22222222-2222-4222-8222-222222222222", + "second@example.com", + 102L, + "Ben", + 7L, + "R-1", + null)); gameplayPresenceService.removeBySessionId(1L); TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.WHO, java.util.List.of(), "WHO"), - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext( + 2L, + 22L, + "22222222-2222-4222-8222-222222222222", + "second@example.com", + 102L, + "Ben", + 7L, + "R-1", + null)); assertThat(result.commandResult().accepted()).isTrue(); assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [1]: Ben"); @@ -143,9 +243,27 @@ void whoAnnotatesExplicitAndAutoAfkPlayers() { new WhoCommandHandler(gameplayPresenceService, resolver, scriptEventPublisher); gameplayPresenceService.registerConnected( - new SessionContext(1L, 22L, 1L, "active@example.com", 101L, "Aster", 7L, "R-1", null)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "active@example.com", + 101L, + "Aster", + 7L, + "R-1", + null)); gameplayPresenceService.registerConnected( - new SessionContext(2L, 22L, 2L, "idle@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext( + 2L, + 22L, + "22222222-2222-4222-8222-222222222222", + "idle@example.com", + 102L, + "Ben", + 7L, + "R-1", + null)); when(resolver.resolve(gameplayPresenceService.findConnectedBySessionId(1L).orElseThrow())) .thenReturn(GameplayPresenceActivityState.ACTIVE); when(resolver.resolve(gameplayPresenceService.findConnectedBySessionId(2L).orElseThrow())) @@ -154,7 +272,16 @@ void whoAnnotatesExplicitAndAutoAfkPlayers() { TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.WHO, java.util.List.of(), "WHO"), - new SessionContext(1L, 22L, 1L, "active@example.com", 101L, "Aster", 7L, "R-1", null)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "active@example.com", + 101L, + "Aster", + 7L, + "R-1", + null)); assertThat(result.commandResult().accepted()).isTrue(); assertThat(result.outputs()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index c915ba3c4d..fd89b6f285 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -145,7 +145,15 @@ void charsPrivateOnlyWorldFailsBeforeEntityRead() { WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt"), "private-world", null); @@ -186,7 +194,15 @@ void charsDoesNotDistinguishPrivateRealmFromAnInvalidRealm() { "ALLOW_NEW"))))); WorldsCommandHandler localHandler = new WorldsCommandHandler(catalog, entityManagementClient); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt"); assertThat(localHandler.browseCharacters(context, "mixed-world", "secret")) .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidRealm.class); @@ -203,7 +219,15 @@ void browseCharactersFailsClosedForValidSelectorBeforeEntityRosterRead() { WorldsCommandHandler.CharacterBrowseResult result = handler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + "jwt"), "demo", null); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 4dabae9d9f..fd1faddd3b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -40,7 +40,15 @@ class WorldsTextCommandDispatchHandlerTest { void publishesCommandEventForGameplayScopedWorldsBrowse() { SessionContext context = new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, + 22L, + "d0c68a37-5126-42d2-9506-8df13e97699e", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = handler.handle( @@ -71,7 +79,15 @@ void realmsBrowseFailsClosedWhenAccountScopeIssuerIsUnavailable() { gameplayCatalogProperties.setWorlds(List.of(world("sandbox", 1L, 2L, false))); SessionContext context = new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, + 22L, + "d0c68a37-5126-42d2-9506-8df13e97699e", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = handler.handle( @@ -91,7 +107,15 @@ void unavailableCharsDoesNotReadRosterOrPublishGameplayEvent() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); SessionContext context = new SessionContext( - 7L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); TextCommandInterpretationResult result = handler.handle( @@ -168,7 +192,15 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { .setOutcomeCode("CREATED") .build()); SessionContext context = - new SessionContext(7L, 22L, 41L, "emberline@example.com", 0L, null, 0L, "jwt"); + new SessionContext( + 7L, + 22L, + "11111111-1111-4111-8111-111111111111", + "emberline@example.com", + 0L, + null, + 0L, + "jwt"); TextCommandInterpretationResult realmsResult = scopedHandler.handle( @@ -216,7 +248,8 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { org.mockito.ArgumentCaptor.forClass(DirectTextConnectScopeTarget.class); Mockito.verify(accountClient) .issueDirectTextConnectScope(callerCaptor.capture(), targetCaptor.capture()); - assertThat(callerCaptor.getValue().getAccountId()).isEqualTo("41"); + assertThat(callerCaptor.getValue().getAccountId()) + .isEqualTo("d0c68a37-5126-42d2-9506-8df13e97699e"); assertThat(callerCaptor.getValue().getSessionId()).isEqualTo("7"); assertThat(targetCaptor.getValue().realmId()).isEqualTo(realmId.toString()); assertThat(targetCaptor.getValue().catalogRevision()).isEqualTo(7L); @@ -242,7 +275,8 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { assertThat(requestIds.getLast()).isEqualTo(requestIds.getFirst()); assertThat(scopeIds.getLast()).isEqualTo(scopeIds.getFirst()); assertThat(joinContexts.getFirst().getRequestId()).isEqualTo(requestIds.getFirst()); - assertThat(joinContexts.getFirst().getAccountId()).isEqualTo("41"); + assertThat(joinContexts.getFirst().getAccountId()) + .isEqualTo("d0c68a37-5126-42d2-9506-8df13e97699e"); assertThat(joinContexts.getFirst().getSessionId()).isEqualTo("7"); assertThat(joinContexts.getFirst().getRealmId()).isEqualTo(realmId.toString()); assertThat(joinContexts.getLast()).isEqualTo(joinContexts.getFirst()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveCommandHistorySettingsResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveCommandHistorySettingsResolverTest.java index e4fa99b3a4..ffe8353637 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveCommandHistorySettingsResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveCommandHistorySettingsResolverTest.java @@ -42,7 +42,15 @@ void resolvesTenantThenGameInstanceCommandHistoryOverrides() { resolved = resolver.resolvedCommandHistory( new SessionContext( - 1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 911L, + "Ember", + 7L, + "R-1", + null)); assertThat(resolved.effective()).isEqualTo(new FiremudCommandHistoryProperties(20)); assertThat(resolved.sources()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java index 758e1a504e..5e5aab3238 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java @@ -53,7 +53,16 @@ void absentPersistedReconnectionOverrideFallsBackToOperatorDefaults() { FiremudReconnectionProperties effective = resolver.reconnection( - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 911L, + "Ember", + 7L, + "R-1", + null)); assertThat(effective.policy().resumeWindowMs()).isEqualTo(45_000L); assertThat(effective.policy().staleResumeFallsThroughToFreshEntry()).isTrue(); @@ -114,7 +123,16 @@ void disregardsInvalidSparseOverrideAndFallsBackToOperatorDefaultsWithDiagnostic EffectiveReconnectionSettingsResolver.ResolvedValue resolved = resolver.resolvedReconnection( - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 911L, + "Ember", + 7L, + "R-1", + null)); assertThat(resolved.effective().buffer().softMaxBytes()).isEqualTo(16_384); assertThat(resolved.effective().buffer().hardMaxBytes()).isEqualTo(65_536); @@ -159,7 +177,16 @@ void invalidGameInstanceOverrideFallsBackToValidTenantLayer() { EffectiveReconnectionSettingsResolver.ResolvedValue resolved = resolver.resolvedReconnection( - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 911L, + "Ember", + 7L, + "R-1", + null)); assertThat(resolved.effective().buffer().softMaxBytes()).isEqualTo(16_384); assertThat(resolved.effective().buffer().hardMaxBytes()).isEqualTo(80_000); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveSettingsResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveSettingsResolverTest.java index 47f6751780..49519354bf 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveSettingsResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveSettingsResolverTest.java @@ -53,7 +53,16 @@ void presentationOverridesMergeTenantThenGameInstance() { PresentationProperties effective = resolver.presentation( - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 911L, + "Ember", + 7L, + "R-1", + null)); assertThat(effective.defaultLocaleTag()).isEqualTo("fr"); assertThat(effective.defaultColorMode()).isEqualTo(PresentationProperties.ColorMode.BASIC); @@ -87,7 +96,18 @@ void movementAndTopologyOverridesResolveAgainstBootstrapGameInstanceBeforePlay() authorityReader); SessionContext prePlay = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, null, null, 41L); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 0L, + null, + 0L, + null, + null, + null, + 41L); assertThat(resolver.movement(prePlay).postMoveLookEnabled()).isFalse(); assertThat(resolver.worldTopology(prePlay).scopeModel()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerTest.java index 6f9b8aa094..beab8b217c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerTest.java @@ -55,7 +55,17 @@ void setUp() { void effectiveSettingsUsesNormalizedPersistedSessionContext() { SessionContext cleared = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); PresentationProperties presentation = new PresentationProperties(); MovementProperties movement = new MovementProperties(); WorldTopologyProperties worldTopology = new WorldTopologyProperties(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java index d817622c13..00b4846f95 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java @@ -21,7 +21,7 @@ class GameplayLocalPathReadinessProbeTest { private static final long PROBE_SESSION_ID_BASE = 9_223_372_036_854_770_000L; - private static final long PROBE_ACCOUNT_ID = 9_223_372_036_854_770_001L; + private static final String PROBE_ACCOUNT_UUID = "f2ed193b-12c1-4c96-bcad-c162229af440"; private static final long PROBE_CHARACTER_ID = 9_223_372_036_854_770_002L; @Test @@ -38,7 +38,7 @@ void sessionContextProbeReturnsUpWhenContextRoundTrips() { new SessionContext( sessionId, 0L, - PROBE_ACCOUNT_ID, + PROBE_ACCOUNT_UUID, PROBE_CHARACTER_ID, 0L, "readiness-room-" + probeSequence, @@ -74,7 +74,7 @@ void sessionContextProbeRejectsStoredSecret() { new SessionContext( sessionId, 0L, - PROBE_ACCOUNT_ID, + PROBE_ACCOUNT_UUID, PROBE_CHARACTER_ID, 0L, "readiness-room-" + (sessionId - PROBE_SESSION_ID_BASE), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java index a53b8fdb29..bf13e1d3a6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java @@ -102,7 +102,16 @@ void scopedOverrideControlsPromptWindowWhenContextKnown() { List outputs = List.of(PlayerOutput.message("You say, \"hello\""), PlayerOutput.prompt("demo> ")); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Sora", 7L, "R-1", null); + new SessionContext( + 1L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 911L, + "Sora", + 7L, + "R-1", + null); coordinator.recordPromptEmission("1", outputs); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptComposerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptComposerTest.java index 8eaed1f1ea..39d3731ee0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptComposerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptComposerTest.java @@ -11,7 +11,16 @@ class PromptComposerTest { @Test void composeIncludesStructuredFieldsAlongsideClassicPromptText() { SessionContext context = - new SessionContext(41L, 22L, 77L, "demo@example.com", 123L, "Sora", 9L, "R-1021", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Sora", + 9L, + "R-1021", + "jwt"); PlayerOutput prompt = composer.compose(context).orElseThrow(); @@ -29,7 +38,16 @@ void composeIncludesStructuredFieldsAlongsideClassicPromptText() { @Test void composeFallsBackToBarePromptWhileStillPublishingIdentifiers() { SessionContext context = - new SessionContext(41L, 22L, 77L, null, 123L, null, 9L, "R-1021", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + null, + 123L, + null, + 9L, + "R-1021", + "jwt"); PlayerOutput prompt = composer.compose(context).orElseThrow(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java index 666e9ceaf2..7d50d07078 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java @@ -15,6 +15,7 @@ class TextPlayerOutputRendererTest { private static final String STRIDE_COMMAND_ID = "stride"; + private static final String SORA_ACCOUNT_ID = "5f7624ca-8aee-4d34-9cd8-3ba3a1815f30"; @Test void briefModeSuppressesLongLookDescription() { @@ -1069,7 +1070,7 @@ void renderSuccessfulForOutputFormatsFriendDetailWithFriendsEnvelope() { new FriendPresenceViewOutput.Entry( 1, 77L, - 41L, + SORA_ACCOUNT_ID, "ONLINE", null, "Sora", @@ -1094,7 +1095,9 @@ void renderSuccessfulForOutputFormatsFriendDetailWithFriendsEnvelope() { assertThat(rendered) .isEqualTo( "OK FRIENDS\n" - + "Friend Sora [acct #41]\n" + + "Friend Sora [acct #" + + SORA_ACCOUNT_ID + + "]\n" + "Link: #77\n" + "Status: online\n" + "Presence: online in Demo World / Ember Realm (active)\n" @@ -1128,7 +1131,7 @@ void rendersGenericLastSeenWithoutDisconnectDisposition() { new FriendPresenceViewOutput.Entry( 1, null, - 77L, + SORA_ACCOUNT_ID, "active", null, "Sora", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java index e9cdeade50..1484b59374 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java @@ -66,10 +66,29 @@ void tearDown() { @Test void deliverDropsStaleRecipientResolvedByGameplayIdentity() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); SessionContext clearedRecipient = new SessionContext( - 42L, 22L, 456L, "friend@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 42L, + 22L, + "8a1b4907-cc5f-43c8-842f-cb4c9316117d", + "friend@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -95,10 +114,29 @@ void deliverDropsStaleRecipientResolvedByGameplayIdentity() { @Test void deliverDropsStaleRecipientResolvedByGameplayName() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); SessionContext clearedRecipient = new SessionContext( - 42L, 22L, 456L, "friend@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 42L, + 22L, + "8a1b4907-cc5f-43c8-842f-cb4c9316117d", + "friend@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -124,7 +162,16 @@ void deliverDropsStaleRecipientResolvedByGameplayName() { @Test void deliverDoesNotFallbackToNameWhenRecipientIdIsMalformed() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -150,7 +197,16 @@ void deliverDoesNotFallbackToNameWhenRecipientIdIsMalformed() { @Test void deliverDoesNotFallbackToNameWhenRecipientIdIsNonPositive() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -174,7 +230,16 @@ void deliverDoesNotFallbackToNameWhenRecipientIdIsNonPositive() { @Test void deliverDoesNotFallbackToNameWhenStructuredRecipientIdDoesNotResolve() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -203,10 +268,29 @@ void deliverDoesNotFallbackToNameWhenStructuredRecipientIdDoesNotResolve() { @SuppressWarnings("unchecked") void deliverBuffersStructuredReplayEntryForRecipientCommunication() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); SessionContext recipient = new SessionContext( - 42L, 22L, 456L, "friend@example.com", 456L, "Sora", 1L, "R-2", "jwt", "en-NZ", 1L); + 42L, + 22L, + "8a1b4907-cc5f-43c8-842f-cb4c9316117d", + "friend@example.com", + 456L, + "Sora", + 1L, + "R-2", + "jwt", + "en-NZ", + 1L); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -252,10 +336,29 @@ void deliverBuffersStructuredReplayEntryForRecipientCommunication() { @Test void deliverDoesNotBufferNonReplayableRecipientOutput() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); SessionContext recipient = new SessionContext( - 42L, 22L, 456L, "friend@example.com", 456L, "Sora", 1L, "R-2", "jwt", "en-NZ", 1L); + 42L, + 22L, + "8a1b4907-cc5f-43c8-842f-cb4c9316117d", + "friend@example.com", + 456L, + "Sora", + 1L, + "R-2", + "jwt", + "en-NZ", + 1L); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java index 1faab651a6..e4ce1d20c3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java @@ -12,7 +12,7 @@ class DirectTextConnectScopeSessionStoreTest { @Test void resolvesOpaqueScopeOnlyForTheIssuingAccountAndTransportSession() { - SessionContext caller = session(7L, 41L); + SessionContext caller = session(7L, "11111111-1111-4111-8111-111111111111"); Instant expiry = Instant.parse("2030-01-01T00:00:00Z"); store.replaceWorldScopes( caller, @@ -24,17 +24,21 @@ void resolvesOpaqueScopeOnlyForTheIssuingAccountAndTransportSession() { .hasValueSatisfying(scope -> assertThat(scope.connectScopeId()).isEqualTo("scope-secret")); assertThat( store.publicProductionScope( - session(8L, 41L), "1", Instant.parse("2029-01-01T00:00:00Z"))) + session(8L, "11111111-1111-4111-8111-111111111111"), + "1", + Instant.parse("2029-01-01T00:00:00Z"))) .isEmpty(); assertThat( store.publicProductionScope( - session(7L, 42L), "1", Instant.parse("2029-01-01T00:00:00Z"))) + session(7L, "22222222-2222-4222-8222-222222222222"), + "1", + Instant.parse("2029-01-01T00:00:00Z"))) .isEmpty(); } @Test void refusesExpiredAndAmbiguousPublicScopes() { - SessionContext caller = session(7L, 41L); + SessionContext caller = session(7L, "11111111-1111-4111-8111-111111111111"); store.replaceWorldScopes( caller, "demo-world", @@ -64,7 +68,7 @@ void refusesExpiredAndAmbiguousPublicScopes() { @Test void clearsPriorScopeBeforeReplacingTheWorldBinding() { - SessionContext caller = session(7L, 41L); + SessionContext caller = session(7L, "11111111-1111-4111-8111-111111111111"); store.replaceWorldScopes( caller, "1", @@ -81,7 +85,7 @@ void clearsPriorScopeBeforeReplacingTheWorldBinding() { @Test void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { - SessionContext caller = session(7L, 41L); + SessionContext caller = session(7L, "11111111-1111-4111-8111-111111111111"); Instant expiry = Instant.parse("2031-01-01T00:00:00Z"); store.replaceWorldScopes( caller, @@ -120,7 +124,7 @@ void reusesJoinRequestIdForScopeRetryAndStartsANewIdAfterFreshRealms() { assertThat(newAttempt.requestId()).isNotEqualTo(firstAttempt.requestId()); } - private static SessionContext session(long sessionId, long accountId) { + private static SessionContext session(long sessionId, String accountId) { return new SessionContext(sessionId, 22L, accountId, 7001L, 9L, "jwt"); } @@ -128,7 +132,7 @@ private static DirectTextConnectScopeSessionStore.ScopedRealm scopedRealm( SessionContext caller, String realmSlug, String scopeId, Instant expiry) { PlayerExecutionContext playerContext = PlayerExecutionContext.newBuilder() - .setAccountId(Long.toString(caller.accountId())) + .setAccountId(caller.accountId()) .setSessionId(Long.toString(caller.sessionId())) .setTenantId("22") .setRealmId("4c4b57d8-e3a2-48fe-9977-e7df0fdce901") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java index 88b98b2123..fefba31007 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java @@ -11,11 +11,13 @@ import org.junit.jupiter.api.Test; class GameplayAdmissionPointerSnapshotsTest { + private static final String ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + @Test void admittedRoutingBundleReturnsNormalizedBundleWhenRoutingClaimsAreComplete() { SessionContext completeContext = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", "realm", 17L, + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", "realm", 17L, null); GameplayAdmissionPointerSnapshots.AdmittedRoutingBundle bundle = @@ -33,7 +35,8 @@ void admittedRoutingBundleReturnsNormalizedBundleWhenRoutingClaimsAreComplete() void admittedRoutingBundleReturnsEmptyForPartialRoutingClaims() { SessionContext partialRouting = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", null, 17L, null); + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", null, 17L, + null); GameplayAdmissionPointerSnapshots.AdmittedRoutingBundle bundle = GameplayAdmissionPointerSnapshots.admittedRoutingBundle(partialRouting); @@ -48,7 +51,7 @@ void admittedRoutingBundleReturnsEmptyForPartialRoutingClaims() { void admittedRoutingBundleReturnsEmptyWhenRoutingClaimsAreAbsent() { SessionContext missingRouting = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, null, null, 0L, null); + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, null, null, 0L, null); GameplayAdmissionPointerSnapshots.AdmittedRoutingBundle bundle = GameplayAdmissionPointerSnapshots.admittedRoutingBundle(missingRouting); @@ -63,7 +66,8 @@ void admittedRoutingBundleReturnsEmptyWhenRoutingClaimsAreAbsent() { void requireAdmittedRoutingBundleRejectsPartialRoutingClaimsWithCallerSpecificMessage() { SessionContext partialRouting = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", null, 17L, null); + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", null, 17L, + null); assertThatThrownBy( () -> @@ -77,7 +81,7 @@ void requireAdmittedRoutingBundleRejectsPartialRoutingClaimsWithCallerSpecificMe void requireAdmittedRoutingBundleRejectsMissingRoutingClaimsWithCallerSpecificMessage() { SessionContext missingRouting = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, null, null, 0L, null); + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, null, null, 0L, null); assertThatThrownBy( () -> @@ -426,7 +430,7 @@ void sameBootstrapRouteRejectsPlayableStateScopeChanges() { void sameBootstrapRouteRejectsFirstPartyConnectContextWhenRoutingIdentityChanges() { FirstPartyConnectContext existing = new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 7L, "scope-1", "jti-1", "req-1", "gw-1"); + ACCOUNT_ID, 22L, "demo", "production", 1L, 7L, "scope-1", "jti-1", "req-1", "gw-1"); assertThat( GameplayAdmissionPointerSnapshots.sameBootstrapRoute( @@ -454,7 +458,7 @@ void sameBootstrapRouteAcceptsTwoContextsWithNoRoutingValues() { void sameBootstrapRouteAcceptsFirstPartyConnectContextWithCaseInsensitiveRoutingIdentity() { FirstPartyConnectContext existing = new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 7L, "scope-1", "jti-1", "req-1", "gw-1"); + ACCOUNT_ID, 22L, "demo", "production", 1L, 7L, "scope-1", "jti-1", "req-1", "gw-1"); assertThat( GameplayAdmissionPointerSnapshots.sameBootstrapRoute( @@ -482,7 +486,7 @@ private static SessionContext bootstrapShell( return new SessionContext( 1L, tenantId, - 0L, + null, null, 0L, null, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java index f572ac2758..a28242237e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java @@ -7,6 +7,7 @@ import org.junit.jupiter.api.Test; class GameplayPresenceActivityResolverTest { + private static final String ACCOUNT_ID = "fd6f4d69-789b-4e0f-92f1-0c19b3bb1c17"; @Test void explicitAfkWinsOverDerivedAutoAfk() { @@ -23,7 +24,7 @@ void explicitAfkWinsOverDerivedAutoAfk() { 7L, "demo", "production", - 2L, + ACCOUNT_ID, 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -51,7 +52,7 @@ void autoAfkIgnoresAcceptedNonGameplayActivity() { 7L, "demo", "production", - 2L, + ACCOUNT_ID, 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -68,7 +69,7 @@ void autoAfkIgnoresAcceptedNonGameplayActivity() { 7L, "demo", "production", - 2L, + ACCOUNT_ID, 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -85,7 +86,7 @@ void autoAfkIgnoresAcceptedNonGameplayActivity() { 7L, "demo", "production", - 2L, + ACCOUNT_ID, 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -111,7 +112,7 @@ void autoAfkFallsBackToConnectionTimeWhenNoGameplayActivityExists() { 7L, "demo", "production", - 2L, + ACCOUNT_ID, 102L, "Ben", GameplayPresenceRole.PLAYER, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java index 208be9144e..b28200eb1b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java @@ -17,6 +17,7 @@ import org.mockito.Mockito; class SessionAuthenticationServiceTest { + private static final String ACCOUNT_ID = "7c116c4e-2332-4fea-9590-8fd704d56da6"; private final SessionContextService sessionContextService = Mockito.mock(SessionContextService.class); private final GameplayAdmissionPointerAuthorityService pointerAuthorityService = @@ -45,7 +46,7 @@ void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -66,13 +67,13 @@ void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { Optional resolved = service.resolveSessionContext("41"); assertTrue(resolved.isPresent()); - assertEquals(123L, resolved.orElseThrow().accountId()); + assertEquals(ACCOUNT_ID, resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); assertEquals(0L, resolved.orElseThrow().characterId()); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); verify(gameplayPresenceLifecycleService).clearGameplayBinding(stale, "STALE_ADMISSION_POINTER"); - assertEquals(123L, captor.getValue().accountId()); + assertEquals(ACCOUNT_ID, captor.getValue().accountId()); assertEquals(0L, captor.getValue().gameInstanceId()); assertEquals(0L, captor.getValue().pointerVersion()); } @@ -81,7 +82,7 @@ void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { void resolveSessionContextClearsGameplayBindingWhenRoutingBundleIsIncomplete() { SessionContext incomplete = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1", "jwt"); + 41L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 1L, "R-1", "jwt"); when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.of(incomplete)); when(sessionContextService.findByTenantAndSessionId(22L, 41L)) .thenReturn(Optional.of(incomplete)); @@ -89,7 +90,7 @@ void resolveSessionContextClearsGameplayBindingWhenRoutingBundleIsIncomplete() { Optional resolved = service.resolveSessionContext("41"); assertTrue(resolved.isPresent()); - assertEquals(123L, resolved.orElseThrow().accountId()); + assertEquals(ACCOUNT_ID, resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); verify(sessionContextService).save(Mockito.any(SessionContext.class)); verify(gameplayPresenceLifecycleService) @@ -102,7 +103,7 @@ void resolveSessionContextClearsGameplayBindingWhenRuntimeTargetAuthorityIsAmbig new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -139,7 +140,7 @@ void resolveSessionContextKeepsCurrentGameplayBindingWhenPointerMatches() { new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -172,7 +173,7 @@ void resolveUnverifiedSessionContextWithTenantIdNormalizesResolvedContext() { new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -192,7 +193,7 @@ void resolveUnverifiedSessionContextWithTenantIdNormalizesResolvedContext() { Optional resolved = service.resolveUnverifiedSessionContext(22L, 41L); assertTrue(resolved.isPresent()); - assertEquals(123L, resolved.orElseThrow().accountId()); + assertEquals(ACCOUNT_ID, resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); verify(sessionContextService).save(Mockito.any(SessionContext.class)); verify(gameplayPresenceLifecycleService).clearGameplayBinding(stale, "STALE_ADMISSION_POINTER"); @@ -204,7 +205,7 @@ void resolveUnverifiedSessionContextFailsClosedWhenTenantScopedSessionIsMissing( new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -260,7 +261,7 @@ void resolveByGameplayIdentityNormalizesResolvedContext() { new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -292,7 +293,7 @@ void resolveByGameplayNameKeepsCurrentContextWhenPointerMatches() { new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java index fee7ca2ce4..dd6aea6fd9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java @@ -2,25 +2,36 @@ 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.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class SessionContextTest { + private static final String ACCOUNT_ID = "5d7e83b0-e8c4-4edb-b3b7-5d99d4bbad9d"; @Test void preservesLegacyAndSyntheticRuntimeRoomIdsVerbatim() { SessionContext legacyNumeric = - new SessionContext(1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "1", "jwt"); + new SessionContext( + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 41L, "1", "jwt"); SessionContext legacyPrefixed = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "room-1", "jwt"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 41L, "room-1", "jwt"); SessionContext legacyUppercasePrefixed = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "ROOM-1", "jwt"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 41L, "ROOM-1", "jwt"); SessionContext syntheticProbe = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "readiness-room-1", "jwt"); + 1L, + 22L, + ACCOUNT_ID, + "demo@example.com", + 7001L, + "Emberline", + 41L, + "readiness-room-1", + "jwt"); assertEquals("1", legacyNumeric.roomInstanceId()); assertEquals("room-1", legacyPrefixed.roomInstanceId()); @@ -34,7 +45,7 @@ void hasPartialPersistedFirstPartyConnectContextDetectsMissingConnectRequest() { new SessionContext( 1L, 22L, - 123L, + ACCOUNT_ID, "first-party:123", 0L, null, @@ -60,7 +71,7 @@ void hasPartialPersistedFirstPartyConnectContextIgnoresStandardGameplaySession() new SessionContext( 1L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -85,7 +96,7 @@ void hasPartialPersistedFirstPartyConnectContextDetectsMissingConnectScope() { new SessionContext( 1L, 22L, - 123L, + ACCOUNT_ID, "first-party:123", 0L, null, @@ -106,12 +117,12 @@ void hasPartialPersistedFirstPartyConnectContextDetectsMissingConnectScope() { } @Test - void hasPartialPersistedFirstPartyConnectContextRequiresPositiveAccountIdentity() { + void hasPartialPersistedFirstPartyConnectContextRequiresCanonicalAccountIdentity() { SessionContext context = new SessionContext( 1L, 22L, - 0L, + null, "first-party:123", 0L, null, @@ -135,11 +146,12 @@ void hasPartialPersistedFirstPartyConnectContextRequiresPositiveAccountIdentity( void hasGameplayRegionBindingRequiresGameInstanceCharacterAndRoom() { SessionContext complete = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); SessionContext missingRoom = - new SessionContext(1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, null, "jwt"); + new SessionContext( + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 41L, null, "jwt"); SessionContext missingCharacter = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 41L, "R-1", "jwt"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 41L, "R-1", "jwt"); assertTrue(complete.hasGameplayRegionBinding()); assertFalse(missingRoom.hasGameplayRegionBinding()); @@ -149,13 +161,14 @@ void hasGameplayRegionBindingRequiresGameInstanceCharacterAndRoom() { @Test void hasGameplayBindingTreatsPartialGameplayShellsAsBound() { SessionContext gameOnly = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 41L, null, "jwt"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 41L, null, "jwt"); SessionContext characterOnly = - new SessionContext(1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 0L, null, "jwt"); + new SessionContext( + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 0L, null, "jwt"); SessionContext roomOnly = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "R-1", "jwt"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "R-1", "jwt"); SessionContext blank = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, null, "jwt"); assertTrue(gameOnly.hasGameplayBinding()); assertTrue(characterOnly.hasGameplayBinding()); @@ -167,14 +180,32 @@ void hasGameplayBindingTreatsPartialGameplayShellsAsBound() { void hasGameplayIdentityRequiresPositiveGameInstanceAndCharacter() { SessionContext complete = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); SessionContext missingGameInstance = - new SessionContext(1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 0L, "R-1", "jwt"); + new SessionContext( + 1L, 22L, ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", 0L, "R-1", "jwt"); SessionContext missingCharacter = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 41L, "R-1", "jwt"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 41L, "R-1", "jwt"); assertTrue(complete.hasGameplayIdentity()); assertFalse(missingGameInstance.hasGameplayIdentity()); assertFalse(missingCharacter.hasGameplayIdentity()); } + + @Test + void accountIdentityMustBeCanonicalNonNilUuidOrAbsent() { + SessionContext unauthenticated = new SessionContext(1L, 22L, null, null, 0L, null, 0L, null); + + assertFalse(unauthenticated.hasAccountIdentity()); + assertThrows( + IllegalArgumentException.class, + () -> new SessionContext(1L, 22L, "123", null, 0L, null, 0L, null)); + assertThrows( + IllegalArgumentException.class, + () -> + new SessionContext( + 1L, 22L, "00000000-0000-0000-0000-000000000000", null, 0L, null, 0L, null)); + assertTrue( + new SessionContext(1L, 22L, ACCOUNT_ID, null, 0L, null, 0L, null).hasAccountIdentity()); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java index 04c9c0108b..f501f4f910 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java @@ -31,7 +31,7 @@ void resolveProjectedSessionContextFailsClosedWhenTenantScopedSessionIsMissing() new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "Emberline", @@ -77,7 +77,7 @@ void normalizeProjectedContextClearsPartialGameplayShellWhenAdmissionPointerCann new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "Emberline", @@ -109,7 +109,7 @@ void normalizeProjectedContextClearsLegacyRuntimeRoomBindingBeforePointerChecks( new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "Emberline", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java index 929f616c8c..bea1576742 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java @@ -20,6 +20,10 @@ import org.mockito.Mockito; class AccountPresenceQueryServiceImplTest { + private static final String CALLER_ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; + private static final String ACCOUNT_A = "550e8400-e29b-41d4-a716-446655440000"; + private static final String ACCOUNT_B = "6ba7b810-9dad-41d1-80b4-00c04fd430c8"; + @Test void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { GameplayPresenceService presenceService = Mockito.mock(GameplayPresenceService.class); @@ -35,13 +39,16 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.containsAll(List.of(3L, 4L)) && ids.size() == 2))) + ids -> + ids != null + && ids.containsAll(List.of(ACCOUNT_A, ACCOUNT_B)) + && ids.size() == 2))) .thenReturn( java.util.Map.of( - 4L, + ACCOUNT_B, new AccountRecentPresenceState( 1L, - 4L, + ACCOUNT_B, 2L, "SHARED", "sandbox", @@ -52,10 +59,13 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.containsAll(List.of(3L, 4L)) && ids.size() == 2))) + ids -> + ids != null + && ids.containsAll(List.of(ACCOUNT_A, ACCOUNT_B)) + && ids.size() == 2))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -65,7 +75,7 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { "sandbox", "production", 17L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -78,10 +88,10 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L, 4L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A, ACCOUNT_B)); assertEquals(2, result.size()); - assertEquals(3L, result.get(0).accountId()); + assertEquals(ACCOUNT_A, result.get(0).accountId()); assertEquals(true, result.get(0).online()); assertEquals(2L, result.get(0).gameInstanceId()); assertEquals("sandbox", result.get(0).worldSlug()); @@ -94,7 +104,7 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { net.firedevops.firemud.gamesession.service.GameplayPresenceActivityState.EXPLICIT_AFK, result.get(0).activityState()); assertEquals(null, result.get(0).recentDisposition()); - assertEquals(4L, result.get(1).accountId()); + assertEquals(ACCOUNT_B, result.get(1).accountId()); assertEquals(false, result.get(1).online()); assertEquals(2L, result.get(1).gameInstanceId()); assertEquals("sandbox", result.get(1).worldSlug()); @@ -122,13 +132,13 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, new AccountRecentPresenceState( 1L, - 3L, + ACCOUNT_A, 9L, "SHARED", "sandbox", @@ -139,10 +149,10 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -152,7 +162,7 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { "sandbox", "production", 18L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -165,7 +175,7 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -188,13 +198,13 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, new AccountRecentPresenceState( 1L, - 3L, + ACCOUNT_A, 2L, "SHARED", "sandbox", @@ -205,10 +215,10 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -218,7 +228,7 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin "sandbox", "production", 0L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -231,7 +241,7 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -257,13 +267,13 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, new AccountRecentPresenceState( 1L, - 3L, + ACCOUNT_A, 2L, "SHARED", "sandbox", @@ -274,10 +284,10 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -287,7 +297,7 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna " ", "production", 17L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -300,7 +310,7 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -326,15 +336,15 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn(Map.of()); when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -344,7 +354,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { "sandbox", "production", 18L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -360,7 +370,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { "sandbox", "production", 17L, - 3L, + ACCOUNT_A, 100L, "Ben", GameplayPresenceRole.PLAYER, @@ -373,7 +383,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A)); assertEquals(1, result.size()); assertEquals(true, result.get(0).online()); @@ -397,13 +407,13 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, new AccountRecentPresenceState( 1L, - 3L, + ACCOUNT_A, 2L, "SHARED", "sandbox", @@ -414,10 +424,10 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -427,7 +437,7 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { "sandbox", "production", 17L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -441,7 +451,7 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L), pointer("sandbox", "Builder Sandbox", "preview", "Preview Realm", 1L, 2L, 18L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -467,13 +477,13 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, new AccountRecentPresenceState( 1L, - 3L, + ACCOUNT_A, 2L, "SHARED", "sandbox", @@ -484,10 +494,10 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -497,7 +507,7 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { "sandbox", "production", 17L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -522,7 +532,7 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { "", "ALLOW_NEW"))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -548,15 +558,15 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn(Map.of()); when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_A) && ids.size() == 1))) .thenReturn( Map.of( - 3L, + ACCOUNT_A, List.of( new GameplayPresence( 97L, @@ -566,7 +576,7 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { "Sandbox", "Production", 17L, - 3L, + ACCOUNT_A, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -579,7 +589,7 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_A)); assertEquals(1, result.size()); assertEquals(true, result.get(0).online()); @@ -604,13 +614,13 @@ void queryAccountPresenceTreatsCaseInsensitiveRecentRoutingIdentityAsCurrent() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(4L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_B) && ids.size() == 1))) .thenReturn( Map.of( - 4L, + ACCOUNT_B, new AccountRecentPresenceState( 1L, - 4L, + ACCOUNT_B, 2L, "SHARED", "Sandbox", @@ -621,14 +631,14 @@ void queryAccountPresenceTreatsCaseInsensitiveRecentRoutingIdentityAsCurrent() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(4L) && ids.size() == 1))) + ids -> ids != null && ids.contains(ACCOUNT_B) && ids.size() == 1))) .thenReturn(Map.of()); when(pointerAuthorityService.listByRuntimeTarget(1L, 2L)) .thenReturn( List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(4L)); + var result = service.queryAccountPresence(1L, CALLER_ACCOUNT_ID, List.of(ACCOUNT_B)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java index 5b06d7f8cb..8e1f4957e6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java @@ -846,7 +846,7 @@ private static SessionContext gameplayContext(String roomId, String playableStat return new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 44L, "char", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java index 7cac76b022..2c5ddae381 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java @@ -8,6 +8,7 @@ import static org.mockito.Mockito.verify; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameInstance; @@ -33,6 +34,8 @@ @ExtendWith(OutputCaptureExtension.class) class CommandServiceImplTest { + private static final String ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + @Test void rateLimitFailurePropagatesError() { TickService tickService = Mockito.mock(TickService.class); @@ -219,6 +222,8 @@ void enqueuePassesThroughWhenAllowed() { assertEquals("LOOK", accepted.getCommandName()); assertEquals("look", accepted.getSanitizedCommandText()); assertEquals(1L, accepted.getEnqueueSeq()); + assertNull(accepted.getAccountUuid()); + assertNull(accepted.getAccountId()); } @Test @@ -311,7 +316,17 @@ void gameplayCommandsQueueAgainstGameInstanceWhenSessionContextHasOne() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext( + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 44L, + "char", + 99L, + "R-1", + "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); CommandServiceImpl service = @@ -330,6 +345,13 @@ void gameplayCommandsQueueAgainstGameInstanceWhenSessionContextHasOne() { verify(tickService, times(1)).enqueueCommand(9L, 99L, result.commandId(), "look", false); verify(scriptEventPublisher, times(1)) .publishCommandEvent(Mockito.any(SessionContext.class), Mockito.any(GameplayCommand.class)); + org.mockito.ArgumentCaptor commandCaptor = + org.mockito.ArgumentCaptor.forClass(GameplayCommand.class); + verify(commandRepository).save(commandCaptor.capture()); + GameplayCommand accepted = commandCaptor.getValue(); + assertEquals( + UUID.fromString("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"), accepted.getAccountUuid()); + assertNull(accepted.getAccountId()); } @Test @@ -350,7 +372,7 @@ void gameplayCommandsPersistCurrentRuntimeScopeForDurableCommandEventFallback() new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 44L, "char", @@ -403,7 +425,16 @@ void gameplayCommandFailsBeforePersistenceWhenRuntimeOwnershipIsNotEstablished() Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( Optional.of( - new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "region-99", "jwt"))); + new SessionContext( + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 44L, + "char", + 99L, + "region-99", + "jwt"))); Mockito.when(runtimeRegionStatusRepository.findByTenantIdAndGameInstanceId(9L, 99L)) .thenReturn(Optional.empty()); CommandServiceImpl service = @@ -445,7 +476,16 @@ void gameplayCommandFailsClosedWhenRuntimeOwnershipReadFails() { Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( Optional.of( - new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "region-99", "jwt"))); + new SessionContext( + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 44L, + "char", + 99L, + "region-99", + "jwt"))); Mockito.when(runtimeRegionStatusRepository.findByTenantIdAndGameInstanceId(9L, 99L)) .thenThrow(new IllegalStateException("runtime ownership unavailable")); CommandServiceImpl service = @@ -489,7 +529,7 @@ void bootstrapShellQueuesAgainstBootstrapRuntimeWhenSessionIdDiffers() { new SessionContext( 17L, 9L, - 0L, + null, null, 0L, null, @@ -536,7 +576,21 @@ void staleNormalizedGameplaySessionFailsClosedWithoutBootstrapRoutingBundle() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); SessionContext cleared = new SessionContext( - 17L, 9L, 3L, "demo", 0L, null, 0L, null, "jwt", null, 99L, null, null, 0L, null); + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 0L, + null, + 0L, + null, + "jwt", + null, + 99L, + null, + null, + 0L, + null); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn(Optional.of(cleared)); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); @@ -579,7 +633,17 @@ void enqueueAddsGameplayLoggingContextWhenSessionIsBound() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext( + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 44L, + "char", + 99L, + "R-1", + "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); Mockito.doAnswer( invocation -> { @@ -629,7 +693,17 @@ void loginCommandsAreRedactedFromLogs(CapturedOutput output) { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext( + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 44L, + "char", + 99L, + "R-1", + "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); CommandServiceImpl service = newCommandService( @@ -668,7 +742,7 @@ void loginCommandPersistsBootstrapRoutingMetadataFromAuthority() { new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 0L, null, @@ -732,7 +806,7 @@ void loginCommandPersistsBootstrapRoutingMetadataFromUnambiguousRuntimeAuthority GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, 3L, "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, ACCOUNT_ID, "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -784,7 +858,7 @@ void loginCommandDropsBootstrapRoutingMetadataWhenRuntimeAuthorityIsAmbiguous() GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, 3L, "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, ACCOUNT_ID, "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -849,7 +923,7 @@ void loginCommandDropsBootstrapRoutingMetadataWhenSingularRuntimeAuthorityIsInco GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, 3L, "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, ACCOUNT_ID, "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -906,7 +980,7 @@ void gameplayCommandRepairsPartialSessionRoutingMetadataFromAuthority() { new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 44L, "char", @@ -973,7 +1047,20 @@ void gameplayCommandRepairsPointerOnlySessionRoutingMetadataFromRuntimeAuthority .thenReturn( Optional.of( new SessionContext( - 17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt", null, 99L, null, null, 17L, + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 44L, + "char", + 99L, + "R-1", + "jwt", + null, + 99L, + null, + null, + 17L, "SHARED"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( @@ -1031,7 +1118,7 @@ void gameplayCommandUsesActiveGameplayRuntimeAuthorityBeforeBootstrapRuntime() { new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 44L, "char", @@ -1103,7 +1190,7 @@ void gameplayCommandRepairsStaleCompleteSessionRoutingMetadataFromCurrentAuthori new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 0L, null, @@ -1172,7 +1259,7 @@ void gameplayCommandDropsStaleCompleteSessionRoutingMetadataWhenCurrentAuthority new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 0L, null, @@ -1227,7 +1314,7 @@ void gameplayCommandDropsPartialSessionRoutingMetadataWhenAuthorityCannotRepairI new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 44L, "char", @@ -1282,7 +1369,7 @@ void gameplayCommandDropsSessionRoutingMetadataWhenCurrentSelectorPointerIsIncom new SessionContext( 17L, 9L, - 3L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo", 44L, "char", @@ -1347,7 +1434,17 @@ void queueValidationFailureMarksPersistedCommandFailed() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext( + 17L, + 9L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "demo", + 44L, + "char", + 99L, + "R-1", + "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); Mockito.doThrow(new IllegalArgumentException("bad command")) .when(tickService) @@ -1471,14 +1568,14 @@ private SessionAuthenticationService identitySessionAuthenticationService() { private SessionContext bootstrapShell( long sessionId, long tenantId, long bootstrapGameInstanceId) { - return bootstrapShell(sessionId, tenantId, bootstrapGameInstanceId, 0L, null, null); + return bootstrapShell(sessionId, tenantId, bootstrapGameInstanceId, null, null, null); } private SessionContext bootstrapShell( long sessionId, long tenantId, long bootstrapGameInstanceId, - long accountId, + String accountId, String loginName, String jwt) { return new SessionContext( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java index ee91785206..56b49cd80e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java @@ -167,9 +167,27 @@ void executeDoesNotInferActionStateFromCombatMetadata() { @Test void executeReturnsReplayNoOpForIdempotentMoveReplay() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); SessionContext moved = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-2", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-2", + "jwt-token"); GameplayCommand command = gameplayCommand("MOVE", "north"); TickEffect effect = tickEffect("tfx-1", "cmd-1"); PlayerOutput output = PlayerOutput.message("You move north."); @@ -203,9 +221,27 @@ void executeReturnsReplayNoOpForIdempotentMoveReplay() { @Test void executePublishesMovementLifecycleEventsAfterFirstApply() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); SessionContext moved = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-2", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-2", + "jwt-token"); GameplayCommand command = gameplayCommand("MOVE", "north"); TickEffect effect = tickEffect("tfx-9", "cmd-9"); when(parser.parse("north")) @@ -228,7 +264,16 @@ void executePublishesMovementLifecycleEventsAfterFirstApply() { @Test void executeAppliesDurableItemMutationAndDeliversOutput() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("GET", "GET torch"); TickEffect effect = tickEffect("tfx-2", "cmd-2"); TextCommand parsed = @@ -263,7 +308,16 @@ void executeAppliesDurableItemMutationAndDeliversOutput() { @Test void executeRejectsDurableItemMutationAndDeliversOutput() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("PUT", "PUT ration INTO torch"); TickEffect effect = tickEffect("tfx-3", "cmd-3"); TextCommand parsed = @@ -309,7 +363,16 @@ void executeRejectsDurableItemMutationAndDeliversOutput() { @Test void executeAppliesDurableCommunicationAndDeliversOutput() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("SAY", "SAY Hello there"); TickEffect effect = tickEffect("tfx-4", "cmd-4"); TextCommand parsed = @@ -338,7 +401,16 @@ void executeAppliesDurableCommunicationAndDeliversOutput() { @Test void executeNormalizesStaleSessionContextBeforeDurableGameplayHandling() { SessionContext cleared = - new SessionContext(42L, 22L, 7L, "demo@example.com", 0L, null, 0L, null, "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 0L, + null, + 0L, + null, + "jwt-token"); GameplayCommand command = gameplayCommand("GET", "GET torch"); TickEffect effect = tickEffect("tfx-stale", "cmd-stale"); TextCommand parsed = @@ -369,7 +441,16 @@ void executeNormalizesStaleSessionContextBeforeDurableGameplayHandling() { @Test void executeResolvesAutomationCommandByGameplayIdentityWhenSessionIdIsUnset() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("SAY", "SAY Hello there"); command.setSessionId(0L); command.setTenantId(22L); @@ -445,7 +526,16 @@ void executeRejectsSessionlessCommandWhenTargetEntityIdIsNonPositive() { @Test void executeAppliesDurableAfkAndDeliversOutput() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("BRB", "BRB"); TickEffect effect = tickEffect("tfx-5", "cmd-5"); TextCommand parsed = @@ -480,7 +570,16 @@ void executeAppliesDurableAfkAndDeliversOutput() { @Test void executeAppliesDurableBlockAndStoresReplay() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("GUARD", "GUARD"); TickEffect effect = tickEffect("tfx-6", "cmd-6"); TextCommand parsed = @@ -509,7 +608,16 @@ void executeAppliesDurableBlockAndStoresReplay() { @Test void executeReplaysStoredCommunicationWithoutInvokingHandler() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("SAY", "SAY Hello there"); TickEffect effect = tickEffect("tfx-6", "cmd-6"); TextCommand parsed = @@ -537,7 +645,16 @@ void executeReplaysStoredCommunicationWithoutInvokingHandler() { @Test void executeReplaysStoredRejectedAfkWithoutInvokingHandler() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("AFK", "AFK"); TickEffect effect = tickEffect("tfx-7", "cmd-7"); TextCommand parsed = @@ -572,7 +689,16 @@ void executeReplaysStoredRejectedAfkWithoutInvokingHandler() { @Test void executeReplaysStoredBlockWithoutInvokingHandler() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("BLOCK", "BLOCK"); TickEffect effect = tickEffect("tfx-7b", "cmd-7b"); TextCommand parsed = new TextCommand(TextCommandType.BLOCK, java.util.List.of(), "BLOCK"); @@ -600,7 +726,16 @@ void executeReplaysStoredBlockWithoutInvokingHandler() { @Test void executeAppliesPersistedAuthoredActionSnapshotWithoutLiveMetadata() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -642,7 +777,16 @@ void executeAppliesPersistedAuthoredActionSnapshotWithoutLiveMetadata() { @Test void executeReplaysPersistedAuthoredActionWithoutApplyingItsSnapshotAgain() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -695,7 +839,16 @@ void executeReplaysAuthoredSnapshotAgainstItsOriginalSessionAfterSessionResumpti playerOutputDeliveryService, scriptEventPublisher); SessionContext resumedContext = - new SessionContext(43L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 43L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -735,7 +888,16 @@ void executeReplaysAuthoredSnapshotAgainstItsOriginalSessionAfterSessionResumpti @Test void executeRejectsAuthoredActionWhenTheSessionSwitchedGameplayIdentity() { SessionContext switchedContext = - new SessionContext(42L, 22L, 7L, "demo@example.com", 92L, "Other", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 92L, + "Other", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -757,7 +919,16 @@ void executeRejectsAuthoredActionWhenTheSessionSwitchedGameplayIdentity() { @Test void executeRejectsMalformedAuthoredSnapshotBeforeReplayOrScriptPublication() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -781,7 +952,16 @@ void executeRejectsMalformedAuthoredSnapshotBeforeReplayOrScriptPublication() { @Test void executeRejectsAuthoredSnapshotWithAnInvalidModifierBeforeReplay() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -823,7 +1003,16 @@ void executeRejectsAuthoredSnapshotWithAnInvalidModifierBeforeReplay() { @Test void executeRejectsAuthoredSnapshotAboveTheSharedDurationLimitBeforeReplay() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext( + 42L, + 22L, + "11111111-1111-4111-8111-111111111111", + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java index b6df308271..2bbb2cf176 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java @@ -34,7 +34,15 @@ class DefaultGameplayPresenceLifecycleServiceTest { void registerConnectedUpdatesLiveAndRecentPresence() { SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + ""); service.registerConnected(context); @@ -54,7 +62,15 @@ void recordActivityUpdatesLiveAndRecentPresence() { void clearGameplayBindingPublishesExitAndRemovesLivePresenceWithoutDisconnecting() { SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + ""); service.clearGameplayBinding(context, "STALE_ADMISSION_POINTER"); @@ -71,7 +87,16 @@ void clearGameplayBindingPublishesExitAndRemovesLivePresenceWithoutDisconnecting @Test void clearGameplayBindingSkipsExitWithoutGameplayRegionBinding() { SessionContext context = - new SessionContext(41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, ""); + new SessionContext( + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + null, + ""); service.clearGameplayBinding(context, "LOGIN_FAILED"); @@ -86,7 +111,15 @@ void clearGameplayBindingSkipsExitWithoutGameplayRegionBinding() { void recordDisconnectedWritesRecentPresenceBeforeRemovingLivePresence() { whenGameplayContextPresent( new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", "")); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + "")); service.recordDisconnected(41L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); @@ -109,7 +142,15 @@ void recordDisconnectedWritesRecentPresenceBeforeRemovingLivePresence() { void recordDisconnectedPreservesCanonicalLogoutEventId() { SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + ""); whenGameplayContextPresent(context); service.recordDisconnected(41L, AccountRecentPresenceDisposition.LOGOUT); @@ -121,7 +162,15 @@ void recordDisconnectedPreservesCanonicalLogoutEventId() { void takeoverRemovesDisplacedSessionWithoutPublishingCharacterRegionExit() { SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + ""); whenGameplayContextPresent(context); service.recordDisconnected(41L, AccountRecentPresenceDisposition.TAKEOVER); @@ -136,7 +185,7 @@ void takeoverRemovesDisplacedSessionWithoutPublishingCharacterRegionExit() { @Test void recordDisconnectedSkipsLifecycleEventWithoutGameplayRegionBinding() { whenGameplayContextPresent( - new SessionContext(41L, 22L, 0L, "demo@example.com", 7001L, "Emberline", 0L, "", "")); + new SessionContext(41L, 22L, null, "demo@example.com", 7001L, "Emberline", 0L, "", "")); service.recordDisconnected(41L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); @@ -157,7 +206,16 @@ private void whenGameplayContextPresent(SessionContext context) { @Test void recordDisconnectedSkipsExitWhenNormalizationClearsStaleGameplayBinding() { SessionContext cleared = - new SessionContext(41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, ""); + new SessionContext( + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + null, + ""); Mockito.when(sessionRoutingNormalizationService.resolveProjectedSessionContext("41")) .thenReturn(Optional.of(cleared)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImplTest.java index 3c5b060849..acd1d61e4f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImplTest.java @@ -56,6 +56,14 @@ private void whenInstance(long gameInstanceId, GameInstance instance) { private SessionContext gameplayContext() { return new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt"); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 5fb3627876..6b305fd3da 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -65,6 +65,9 @@ import org.mockito.Mockito; class GameSessionGrpcServiceTest { + private static final String ACCOUNT_VIEWER = "37bf660c-8de4-49ed-8f62-821455239d78"; + private static final String ACCOUNT_TARGET = "b693f855-e466-4eb7-bec9-c8892b530b2b"; + @AfterEach void tearDown() { SessionContext.clear(); @@ -203,12 +206,14 @@ void queryAccountPresenceReturnsMappedSnapshots() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); - Mockito.when(accountPresenceQueryService.queryAccountPresence(1L, 42L, List.of(7L))) + SessionContext.setContext(ACCOUNT_VIEWER, List.of(), Map.of()); + Mockito.when( + accountPresenceQueryService.queryAccountPresence( + 1L, ACCOUNT_VIEWER, List.of(ACCOUNT_TARGET))) .thenReturn( List.of( new AccountPresenceSnapshot( - 7L, + ACCOUNT_TARGET, true, 9L, "ISOLATED", @@ -239,8 +244,8 @@ void queryAccountPresenceReturnsMappedSnapshots() { service.queryAccountPresence( QueryAccountPresenceRequest.newBuilder() .setTenantId("1") - .setViewerAccountId("42") - .addAccountIds("7") + .setViewerAccountId(ACCOUNT_VIEWER) + .addAccountIds(ACCOUNT_TARGET) .build(), new StreamObserver<>() { @Override @@ -258,7 +263,7 @@ public void onCompleted() {} }); assertEquals(1, ref.get().getPresencesCount()); - assertEquals("7", ref.get().getPresences(0).getAccountId()); + assertEquals(ACCOUNT_TARGET, ref.get().getPresences(0).getAccountId()); assertEquals(true, ref.get().getPresences(0).getOnline()); assertEquals("demo", ref.get().getPresences(0).getWorldSlug()); assertEquals("Demo World", ref.get().getPresences(0).getWorldDisplayName()); @@ -287,7 +292,7 @@ void queryAccountPresenceRejectsMalformedAccountId() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(ACCOUNT_VIEWER, List.of(), Map.of()); GameSessionGrpcService service = newService( pingService, @@ -304,8 +309,8 @@ void queryAccountPresenceRejectsMalformedAccountId() { service.queryAccountPresence( QueryAccountPresenceRequest.newBuilder() .setTenantId("1") - .setViewerAccountId("42") - .addAccountIds("abc") + .setViewerAccountId(ACCOUNT_VIEWER) + .addAccountIds("not-a-uuid") .build(), new StreamObserver<>() { @Override @@ -323,7 +328,7 @@ public void onCompleted() {} }); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be a number", ref.get().getError().getMessage()); + assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); Mockito.verifyNoInteractions(accountPresenceQueryService); } @@ -339,7 +344,7 @@ void queryAccountPresenceRejectsZeroAccountId() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(ACCOUNT_VIEWER, List.of(), Map.of()); GameSessionGrpcService service = newService( pingService, @@ -356,8 +361,8 @@ void queryAccountPresenceRejectsZeroAccountId() { service.queryAccountPresence( QueryAccountPresenceRequest.newBuilder() .setTenantId("1") - .setViewerAccountId("42") - .addAccountIds("0") + .setViewerAccountId(ACCOUNT_VIEWER) + .addAccountIds("00000000-0000-0000-0000-000000000000") .build(), new StreamObserver<>() { @Override @@ -375,7 +380,7 @@ public void onCompleted() {} }); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); Mockito.verifyNoInteractions(accountPresenceQueryService); } @@ -391,7 +396,7 @@ void queryAccountPresenceRejectsTooManyAccountIdsBeforeParsing() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(ACCOUNT_VIEWER, List.of(), Map.of()); GameSessionGrpcService service = newService( pingService, @@ -405,9 +410,11 @@ void queryAccountPresenceRejectsTooManyAccountIdsBeforeParsing() { ipLimiter); QueryAccountPresenceRequest.Builder request = - QueryAccountPresenceRequest.newBuilder().setTenantId("1").setViewerAccountId("42"); + QueryAccountPresenceRequest.newBuilder() + .setTenantId("1") + .setViewerAccountId(ACCOUNT_VIEWER); for (int index = 0; index < 101; index++) { - request.addAccountIds(index == 100 ? "not-a-number" : Long.toString(index + 1L)); + request.addAccountIds(index == 100 ? "not-a-uuid" : ACCOUNT_TARGET); } AtomicReference ref = new AtomicReference<>(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java index 8c03ef384a..61fecbe32b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java @@ -22,7 +22,15 @@ void classifyRoleReturnsPlayerWhenJwtParserThrowsIllegalArgumentException() { GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( new SessionContext( - 1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", "boom-token"), + 1L, + 22L, + "6b56d98a-f6cd-4e39-9db9-111b9f8c6aa1", + "player@example.com", + 202L, + "Ben", + 7L, + "R-1", + "boom-token"), jwtUtil, logger); @@ -34,16 +42,25 @@ void classifyRoleReturnsModeratorForScopedModeratorRole() { Logger logger = mock(Logger.class); String jwt = JWT_UTIL.generateToken( - "202", + "54d0886e-416b-49f4-920c-ae4a19ed7a83", java.util.Map.of( "accountId", - "202", + "54d0886e-416b-49f4-920c-ae4a19ed7a83", "scopedRoles", java.util.Map.of("22", java.util.List.of("moderator")))); GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), + new SessionContext( + 1L, + 22L, + "54d0886e-416b-49f4-920c-ae4a19ed7a83", + "player@example.com", + 202L, + "Ben", + 7L, + "R-1", + jwt), JWT_UTIL, logger); @@ -55,16 +72,25 @@ void classifyRoleReturnsPlayerForGlobalRolesWithoutTenantGrant() { Logger logger = mock(Logger.class); String jwt = JWT_UTIL.generateToken( - "202", + "54d0886e-416b-49f4-920c-ae4a19ed7a83", java.util.Map.of( "accountId", - "202", + "54d0886e-416b-49f4-920c-ae4a19ed7a83", "globalRoles", java.util.List.of("platformAdmin", "support", "billingAdmin", "god", "moderator"))); GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), + new SessionContext( + 1L, + 22L, + "54d0886e-416b-49f4-920c-ae4a19ed7a83", + "player@example.com", + 202L, + "Ben", + 7L, + "R-1", + jwt), JWT_UTIL, logger); @@ -76,10 +102,10 @@ void classifyRoleKeepsGlobalControlPlaneRolesAsPlayerAfterJoin() { Logger logger = mock(Logger.class); String jwt = JWT_UTIL.generateToken( - "202", + "54d0886e-416b-49f4-920c-ae4a19ed7a83", java.util.Map.of( "accountId", - "202", + "54d0886e-416b-49f4-920c-ae4a19ed7a83", "globalRoles", java.util.List.of("platformAdmin", "support", "billingAdmin"), "scopedRoles", @@ -87,7 +113,16 @@ void classifyRoleKeepsGlobalControlPlaneRolesAsPlayerAfterJoin() { GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), + new SessionContext( + 1L, + 22L, + "54d0886e-416b-49f4-920c-ae4a19ed7a83", + "player@example.com", + 202L, + "Ben", + 7L, + "R-1", + jwt), JWT_UTIL, logger); @@ -99,16 +134,25 @@ void classifyRoleReturnsAdminForTenantAdminRole() { Logger logger = mock(Logger.class); String jwt = JWT_UTIL.generateToken( - "202", + "54d0886e-416b-49f4-920c-ae4a19ed7a83", java.util.Map.of( "accountId", - "202", + "54d0886e-416b-49f4-920c-ae4a19ed7a83", "scopedRoles", java.util.Map.of("22", java.util.List.of("tenantAdmin")))); GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), + new SessionContext( + 1L, + 22L, + "54d0886e-416b-49f4-920c-ae4a19ed7a83", + "player@example.com", + 202L, + "Ben", + 7L, + "R-1", + jwt), JWT_UTIL, logger); @@ -120,16 +164,25 @@ void classifyRoleUsesTheHighestAvailableTenantScopedGameplayRole() { Logger logger = mock(Logger.class); String jwt = JWT_UTIL.generateToken( - "202", + "54d0886e-416b-49f4-920c-ae4a19ed7a83", java.util.Map.of( "accountId", - "202", + "54d0886e-416b-49f4-920c-ae4a19ed7a83", "scopedRoles", java.util.Map.of("22", java.util.List.of("moderator", "tenantAdmin", "god")))); GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), + new SessionContext( + 1L, + 22L, + "54d0886e-416b-49f4-920c-ae4a19ed7a83", + "player@example.com", + 202L, + "Ben", + 7L, + "R-1", + jwt), JWT_UTIL, logger); @@ -140,11 +193,23 @@ void classifyRoleUsesTheHighestAvailableTenantScopedGameplayRole() { void classifyRoleReturnsPlayerWhenScopedRolesClaimIsMalformed() { Logger logger = mock(Logger.class); String jwt = - JWT_UTIL.generateToken("202", java.util.Map.of("accountId", "202", "scopedRoles", "bad")); + JWT_UTIL.generateToken( + "54d0886e-416b-49f4-920c-ae4a19ed7a83", + java.util.Map.of( + "accountId", "54d0886e-416b-49f4-920c-ae4a19ed7a83", "scopedRoles", "bad")); GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), + new SessionContext( + 1L, + 22L, + "54d0886e-416b-49f4-920c-ae4a19ed7a83", + "player@example.com", + 202L, + "Ben", + 7L, + "R-1", + jwt), JWT_UTIL, logger); @@ -156,16 +221,25 @@ void classifyRoleReturnsGodForTenantScopedGodRole() { Logger logger = mock(Logger.class); String jwt = JWT_UTIL.generateToken( - "202", + "54d0886e-416b-49f4-920c-ae4a19ed7a83", java.util.Map.of( "accountId", - "202", + "54d0886e-416b-49f4-920c-ae4a19ed7a83", "scopedRoles", java.util.Map.of("22", java.util.List.of("god")))); GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), + new SessionContext( + 1L, + 22L, + "54d0886e-416b-49f4-920c-ae4a19ed7a83", + "player@example.com", + 202L, + "Ben", + 7L, + "R-1", + jwt), JWT_UTIL, logger); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java index 750152a7c9..26f49e334d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java @@ -24,6 +24,7 @@ import org.springframework.data.redis.core.ValueOperations; class RedisAccountRecentPresenceServiceTest { + private static final String ACCOUNT_ID = "a8e3cf57-7d4e-44bd-8f4e-77c7fa18df10"; @Test void recordDisconnectPersistsRoutingBundleFromLivePresence() { @@ -43,7 +44,7 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -65,7 +66,7 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { "demo", "production", 17L, - 123L, + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -90,12 +91,15 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); assertEquals(22L, state.tenantId()); - assertEquals(123L, state.accountId()); + assertEquals(ACCOUNT_ID, state.accountId()); assertEquals(101L, state.gameInstanceId()); assertEquals("demo", state.worldSlug()); assertEquals("production", state.realmSlug()); @@ -122,7 +126,7 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 0L, null, @@ -144,7 +148,7 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() "demo", "production", 17L, - 123L, + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -170,7 +174,10 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); @@ -198,7 +205,7 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 0L, null, @@ -220,7 +227,7 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe "demo", "production", 17L, - 123L, + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -246,7 +253,10 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); @@ -274,7 +284,7 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() new SessionContext( 41L, 22L, - 123L, + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -296,7 +306,7 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() "demo", null, 17L, - 123L, + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -322,7 +332,10 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java index 3ceca2deb6..e85e285595 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java @@ -22,6 +22,8 @@ @SuppressWarnings("unchecked") class RedisFirstPartyConnectContextRegistryTest { + private static final String ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + private final ConcurrentMap store = new ConcurrentHashMap<>(); private final RedisTemplate redisTemplate = mock(RedisTemplate.class); private final ValueOperations valueOperations = mock(ValueOperations.class); @@ -56,7 +58,16 @@ void setUp() { void registerStoresContextWithShortTtl() { FirstPartyConnectContext context = new FirstPartyConnectContext( - 77L, 22L, "demo", "production", 41L, 17L, "scope-1", "jti-1", "req-1", "gateway-1"); + ACCOUNT_ID, + 22L, + "demo", + "production", + 41L, + 17L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"); registry.register(91L, context); @@ -73,7 +84,16 @@ void registerStoresContextWithShortTtl() { void unregisterRemovesStoredContext() { FirstPartyConnectContext context = new FirstPartyConnectContext( - 77L, 22L, "demo", "production", 41L, 17L, "scope-1", "jti-1", "req-1", "gateway-1"); + ACCOUNT_ID, + 22L, + "demo", + "production", + 41L, + 17L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"); registry.register(91L, context); registry.unregister(91L); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java index bee45bc8a1..ce55c1dc96 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -19,10 +20,13 @@ import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.serializer.SerializationException; @SuppressWarnings("unchecked") class RedisGameplayPresenceServiceTest { private static final Duration TTL = Duration.ofMillis(1000L); + private static final String ACCOUNT_PLAYER = "6b56d98a-f6cd-4e39-9db9-111b9f8c6aa1"; + private static final String ACCOUNT_GOD = "4f41b943-39b1-4b0f-80f6-fc9229df0712"; private final RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); private final ValueOperations valueOperations = @@ -41,7 +45,8 @@ void setUp() { @Test void registerConnectedStoresPresenceAndIndexesByGameInstance() { SessionContext context = - new SessionContext(1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", null); + new SessionContext( + 1L, 22L, ACCOUNT_PLAYER, "player@example.com", 202L, "Ben", 7L, "R-1", null); service.registerConnected(context); @@ -56,16 +61,17 @@ void registerConnectedStoresPresenceAndIndexesByGameInstance() { .equals("Ben")), org.mockito.Mockito.eq(TTL)); verify(setOperations).add("gameplaypresence:22:7:sessions", "1"); - verify(setOperations).add("gameplaypresence:22:account:102:sessions", "1"); + verify(setOperations).add("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions", "1"); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); - verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); + verify(redisTemplate) + .expire("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions", TTL); } @Test void registerConnectedClassifiesInvalidJwtAsPlayer() { SessionContext context = new SessionContext( - 1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", "not-a-jwt"); + 1L, 22L, ACCOUNT_PLAYER, "player@example.com", 202L, "Ben", 7L, "R-1", "not-a-jwt"); service.registerConnected(context); @@ -85,9 +91,11 @@ void registerConnectedClassifiesInvalidJwtAsPlayer() { void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { String godJwt = jwtUtil.generateToken( - "1", Map.of("accountId", "1", "scopedRoles", Map.of("22", List.of("god")))); + ACCOUNT_GOD, + Map.of("accountId", ACCOUNT_GOD, "scopedRoles", Map.of("22", List.of("god")))); SessionContext godContext = - new SessionContext(1L, 22L, 1L, "god@example.com", 101L, "Aster", 7L, "R-1", godJwt); + new SessionContext( + 1L, 22L, ACCOUNT_GOD, "god@example.com", 101L, "Aster", 7L, "R-1", godJwt); service.registerConnected(godContext); when(setOperations.members("gameplaypresence:22:7:sessions")) @@ -100,7 +108,7 @@ void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { 7L, "demo", "production", - 1L, + ACCOUNT_GOD, 101L, "Aster", GameplayPresenceRole.GOD, @@ -130,7 +138,7 @@ void listConnectedByGameInstancePrunesMalformedSessionIndexEntry() { 7L, "demo", "production", - 1L, + ACCOUNT_GOD, 101L, "Aster", GameplayPresenceRole.GOD, @@ -156,7 +164,7 @@ void removeBySessionIdRemovesValueAndSetMembership() { 7L, "demo", "production", - 102L, + ACCOUNT_PLAYER, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -169,7 +177,8 @@ void removeBySessionIdRemovesValueAndSetMembership() { verify(redisTemplate).delete("gameplaypresence:session:3"); verify(setOperations).remove("gameplaypresence:22:7:sessions", "3"); - verify(setOperations).remove("gameplaypresence:22:account:102:sessions", "3"); + verify(setOperations) + .remove("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions", "3"); } @Test @@ -182,8 +191,8 @@ void findConnectedBySessionIdReadsPresenceRecordDirectly() { 7L, "demo", "production", - 2L, - 102L, + ACCOUNT_PLAYER, + 202L, "Ben", GameplayPresenceRole.PLAYER, 70L, @@ -197,6 +206,17 @@ void findConnectedBySessionIdReadsPresenceRecordDirectly() { assertEquals(4L, presence.get().sessionId()); } + @Test + void unreadableLegacyPresenceFailsClosedWithoutDeletingRetainedValue() { + String key = "gameplaypresence:session:5"; + when(valueOperations.get(key)).thenThrow(new SerializationException("legacy record")); + + var presence = service.findConnectedBySessionId(5L); + + assertFalse(presence.isPresent()); + Mockito.verify(redisTemplate, Mockito.never()).delete(key); + } + @Test void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequested() { AtomicLong now = new AtomicLong(100L); @@ -209,7 +229,7 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest 7L, "demo", "production", - 102L, + ACCOUNT_PLAYER, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -237,7 +257,8 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest == null), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); - verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); + verify(redisTemplate) + .expire("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions", TTL); } @Test @@ -252,7 +273,7 @@ void setExplicitAfkRefreshesPresenceRecord() { 7L, "demo", "production", - 102L, + ACCOUNT_PLAYER, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -277,12 +298,13 @@ void setExplicitAfkRefreshesPresenceRecord() { .explicitAfkSinceEpochMs())), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); - verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); + verify(redisTemplate) + .expire("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions", TTL); } @Test void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { - when(setOperations.members("gameplaypresence:22:account:102:sessions")) + when(setOperations.members("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions")) .thenReturn(new LinkedHashSet<>(List.of("3", "4"))); when(valueOperations.get("gameplaypresence:session:3")) .thenReturn( @@ -294,7 +316,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { "demo", "production", 17L, - 102L, + ACCOUNT_PLAYER, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -312,7 +334,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { "demo", "production", 17L, - 102L, + ACCOUNT_PLAYER, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -321,17 +343,17 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { 110L, 120L)); - var result = service.listConnectedByAccountIds(22L, List.of(102L)); + var result = service.listConnectedByAccountIds(22L, List.of(ACCOUNT_PLAYER)); assertEquals(1, result.size()); - assertEquals(2, result.get(102L).size()); - assertEquals(4L, result.get(102L).get(0).sessionId()); - assertEquals(3L, result.get(102L).get(1).sessionId()); + assertEquals(2, result.get(ACCOUNT_PLAYER).size()); + assertEquals(4L, result.get(ACCOUNT_PLAYER).get(0).sessionId()); + assertEquals(3L, result.get(ACCOUNT_PLAYER).get(1).sessionId()); } @Test void listConnectedByAccountIdsPrunesMalformedSessionIndexEntry() { - when(setOperations.members("gameplaypresence:22:account:102:sessions")) + when(setOperations.members("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions")) .thenReturn(new LinkedHashSet<>(List.of("bad-session", "4"))); when(valueOperations.get("gameplaypresence:session:4")) .thenReturn( @@ -343,7 +365,7 @@ void listConnectedByAccountIdsPrunesMalformedSessionIndexEntry() { "demo", "production", 17L, - 102L, + ACCOUNT_PLAYER, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -352,11 +374,12 @@ void listConnectedByAccountIdsPrunesMalformedSessionIndexEntry() { 110L, 120L)); - var result = service.listConnectedByAccountIds(22L, List.of(102L)); + var result = service.listConnectedByAccountIds(22L, List.of(ACCOUNT_PLAYER)); assertEquals(1, result.size()); - assertEquals(1, result.get(102L).size()); - assertEquals(4L, result.get(102L).get(0).sessionId()); - verify(setOperations).remove("gameplaypresence:22:account:102:sessions", "bad-session"); + assertEquals(1, result.get(ACCOUNT_PLAYER).size()); + assertEquals(4L, result.get(ACCOUNT_PLAYER).get(0).sessionId()); + verify(setOperations) + .remove("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions", "bad-session"); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java index e04525b15a..88e29513af 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java @@ -57,7 +57,7 @@ void applyPreservesRoutingBundleWhenUpdatingRoom() throws Exception { new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -103,7 +103,9 @@ void applyReturnsConflictWhenGameplayIdentityMismatch() { SessionContext current = baselineContext(); when(valueOperations.get("sessionctx:22:41:context")).thenReturn(current); when(valueOperations.get("sessionctx:22:41:movement-effect:tfx-1")).thenReturn(null); - MoveEffectApplyResult result = service.apply("tfx-1", withAccountId(current, 999L), "R-2045"); + MoveEffectApplyResult result = + service.apply( + "tfx-1", withAccountId(current, "11111111-1111-4111-8111-111111111111"), "R-2045"); assertEquals(MoveEffectApplyStatus.CONFLICT, result.status()); assertEquals(current.withoutJwt(), result.context()); @@ -171,7 +173,7 @@ private SessionContext baselineContext() { return new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 7001L, "demo", @@ -186,7 +188,7 @@ private SessionContext baselineContext() { "SHARED"); } - private SessionContext withAccountId(SessionContext context, long accountId) { + private SessionContext withAccountId(SessionContext context, String accountId) { return new SessionContext( context.sessionId(), context.tenantId(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java index 85ec4718f4..5f1f59c396 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -23,11 +24,13 @@ import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SessionCallback; import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.serializer.SerializationException; @SuppressWarnings("unchecked") class RedisSessionContextServiceTest { private static final Duration TTL = Duration.ofMillis(1000L); private static final String DISTINCTIVE_JWT = "distinctive-raw-backend-jwt-for-test"; + private static final String ACCOUNT_ID = "22b7315e-204f-4d9f-85df-975c3fce8e7f"; private final RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); private final ValueOperations valueOperations = @@ -49,7 +52,7 @@ void setUp() { @Test void saveStoresContextInSessionAndIdentityKeys() throws Exception { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_ID, 30L, 40L, DISTINCTIVE_JWT); service.save(context); @@ -70,8 +73,8 @@ void saveStoresContextInSessionAndIdentityKeys() throws Exception { @Test void saveRemovesStaleSessionKeyBeforeWritingNewIdentityBinding() { - SessionContext existing = new SessionContext(1L, 10L, 20L, 30L, 40L, "old-jwt"); - SessionContext replacement = new SessionContext(2L, 10L, 20L, 30L, 40L, "new-jwt"); + SessionContext existing = new SessionContext(1L, 10L, ACCOUNT_ID, 30L, 40L, "old-jwt"); + SessionContext replacement = new SessionContext(2L, 10L, ACCOUNT_ID, 30L, 40L, "new-jwt"); when(valueOperations.get("sessionctx:10:identity:40:30:context")).thenReturn(existing); service.save(replacement); @@ -84,7 +87,7 @@ void saveRemovesStaleSessionKeyBeforeWritingNewIdentityBinding() { @Test void findByTenantAndSessionIdProjectsLegacyJwtOut() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_ID, 30L, 40L, DISTINCTIVE_JWT); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(context); Optional result = service.findByTenantAndSessionId(10L, 1L); @@ -95,7 +98,7 @@ void findByTenantAndSessionIdProjectsLegacyJwtOut() { @Test void findBySessionIdProjectsLegacyJwtOut() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_ID, 30L, 40L, DISTINCTIVE_JWT); when(valueOperations.get("sessionctx:session:1:context")).thenReturn(context); Optional result = service.findBySessionId(1L); @@ -106,7 +109,7 @@ void findBySessionIdProjectsLegacyJwtOut() { @Test void findByGameplayIdentityProjectsLegacyJwtOut() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_ID, 30L, 40L, DISTINCTIVE_JWT); when(valueOperations.get("sessionctx:10:identity:40:30:context")).thenReturn(context); Optional result = service.findByGameplayIdentity(10L, 40L, 30L); @@ -121,7 +124,7 @@ void findByGameplayNameProjectsLegacyJwtOut() { new SessionContext( 1L, 10L, - 20L, + ACCOUNT_ID, "demo", 30L, "Hero", @@ -142,9 +145,19 @@ void findByGameplayNameProjectsLegacyJwtOut() { assertNull(result.orElseThrow().jwt()); } + @Test + void unreadableLegacyContextFailsClosedWithoutDeletingRetainedValue() { + String key = "sessionctx:10:1:context"; + when(valueOperations.get(key)).thenThrow(new SerializationException("legacy record")); + + assertEquals(Optional.empty(), service.findByTenantAndSessionId(10L, 1L)); + + verify(redisTemplate, never()).delete(key); + } + @Test void deleteBySessionIdRemovesBothKeys() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, "jwt"); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_ID, 30L, 40L, "jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(context); service.deleteBySessionId(10L, 1L); @@ -158,7 +171,7 @@ void deleteBySessionIdRemovesBothKeys() { @Test void savePreservesLocaleTagInStoredContext() { SessionContext context = - new SessionContext(1L, 10L, 20L, null, 30L, null, 40L, "R-1", "jwt", "fr", 40L); + new SessionContext(1L, 10L, ACCOUNT_ID, null, 30L, null, 40L, "R-1", "jwt", "fr", 40L); service.save(context); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java index 1a01de632f..6f12e16184 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java @@ -717,7 +717,7 @@ void pauseAndResumeTicksForGameInstanceBumpOwnershipEpochAndPauseFlag() { @Test void queryStateUsesSessionContextTenantFromSessionAuthority() { when(sessionAuthenticationService.resolveUnverifiedSessionContext("7")) - .thenReturn(Optional.of(new SessionContext(7L, 11L, 0L, 0L, 0L, null))); + .thenReturn(Optional.of(new SessionContext(7L, 11L, null, 0L, 0L, null))); when(valueOps.get("session:11:7")).thenReturn("{\"status\":\"ready\"}"); String state = service.queryState(7L); @@ -739,7 +739,7 @@ void queryStateFailsClosedWhenSessionContextMissing() { @Test void queryStateFailsClosedWhenSessionContextHasNoTenantAuthority() { when(sessionAuthenticationService.resolveUnverifiedSessionContext("7")) - .thenReturn(Optional.of(new SessionContext(7L, 0L, 0L, 0L, 0L, null))); + .thenReturn(Optional.of(new SessionContext(7L, 0L, null, 0L, 0L, null))); IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> service.queryState(7L)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java index 19d5f2894f..c284141ea0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java @@ -47,6 +47,8 @@ import org.springframework.web.socket.WebSocketSession; class GameSessionWebSocketHandlerTest { + private static final String FIRST_PARTY_ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + private final TextCommandInterpreter interpreter = Mockito.mock(TextCommandInterpreter.class); private final LookCommandHandler lookHandler = Mockito.mock(LookCommandHandler.class); private final SessionAuthenticationService sessionAuthenticationService = @@ -137,7 +139,16 @@ void afterConnectionEstablishedRegistersValidFirstPartyConnectContext() { "token")); FirstPartyConnectContext connectContext = new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 7L, 3L, "scope-1", "jti", "req-1", "gw-1"); + FIRST_PARTY_ACCOUNT_ID, + 22L, + "demo", + "production", + 7L, + 3L, + "scope-1", + "jti", + "req-1", + "gw-1"); when(firstPartyConnectContextService.parse("token")).thenReturn(Optional.of(connectContext)); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenReturn( @@ -214,7 +225,16 @@ void afterConnectionEstablishedClosesWithServiceUnavailableWhenPointerAuthorityF "token")); FirstPartyConnectContext connectContext = new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 7L, 3L, "scope-1", "jti", "req-1", "gw-1"); + FIRST_PARTY_ACCOUNT_ID, + 22L, + "demo", + "production", + 7L, + 3L, + "scope-1", + "jti", + "req-1", + "gw-1"); when(firstPartyConnectContextService.parse("token")).thenReturn(Optional.of(connectContext)); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenThrow(new IllegalStateException("database unavailable")); @@ -470,7 +490,7 @@ void afterConnectionEstablishedDropsPartialRoutingTupleWhenRuntimeAuthorityIsAmb .save( eq( new SessionContext( - 41L, 22L, 0L, null, 0L, null, 0L, null, null, null, 7L, null, null, 0L, null, + 41L, 22L, null, null, 0L, null, 0L, null, null, null, 7L, null, null, 0L, null, null, null))); } @@ -601,7 +621,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "Emberline", @@ -650,7 +670,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority context -> context.sessionId() == 41L && context.tenantId() == 22L - && context.accountId() == 0L + && context.accountId() == null && context.bootstrapGameInstanceId() == 7L && "demo".equals(context.worldSlug()) && "production".equals(context.realmSlug()) @@ -665,7 +685,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority new SessionContext( 41L, 22L, - 123L, + "f2ed193b-12c1-4c96-bcad-c162229af440", "demo@example.com", 123L, "Emberline", @@ -727,7 +747,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority context -> context.sessionId() == 41L && context.tenantId() == 22L - && context.accountId() == 0L + && context.accountId() == null && context.bootstrapGameInstanceId() == 7L && context.worldSlug() == null && context.realmSlug() == null @@ -740,7 +760,17 @@ void handleMessageDoesNotAppendScreenBufferForNormalizedLoggedInShell() throws E PlayerOutput output = PlayerOutput.message("Recent room line"); SessionContext clearedShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); when(parser.parse("LOOK")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -775,7 +805,17 @@ void handleMessageDoesNotAppendScreenBufferForPartialGameplayIdentityShell() thr PlayerOutput output = PlayerOutput.message("Recent room line"); SessionContext partialShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 0L, null, "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 0L, + null, + "jwt", + "en-NZ", + 1L); when(parser.parse("LOOK")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -810,7 +850,17 @@ void handleMessageForcesPromptBurstByUiActionMetadata() throws Exception { PlayerOutput output = PlayerOutput.message("Presence: online in Demo World / Live Realm"); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); when(parser.parse("WHO")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -847,7 +897,17 @@ void handleMessageForcesPromptBurstForGameplayEntryMetadata() throws Exception { PlayerOutput output = PlayerOutput.message("Entering Demo World"); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); when(parser.parse("PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -891,7 +951,17 @@ void handleMessageDoesNotForcePromptBurstForPlayTypeWithoutGameplayEntryMetadata PlayerOutput output = PlayerOutput.message("Custom session response"); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); when(parser.parse("CUSTOM-PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -928,7 +998,17 @@ void handleMessageKeepsNonUiCommunicationUnderNormalPromptBurstPolicy() throws E WebSocketSession decoratedSession = Mockito.mock(WebSocketSession.class); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); when(session.getId()).thenReturn("session-41"); when(decoratedSession.getId()).thenReturn("session-41"); when(activeTransportSessionRegistry.find(41L)).thenReturn(Optional.of(decoratedSession)); @@ -976,7 +1056,17 @@ void handleMessageDoesNotReplayReconnectBufferForNormalizedLoggedInShell() throw TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); SessionContext clearedShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); when(parser.parse("PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -1007,7 +1097,17 @@ void handleMessageDoesNotReplayReconnectBufferForPartialGameplayIdentityShell() TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); SessionContext partialShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 1L, null, "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 1L, + null, + "jwt", + "en-NZ", + 1L); when(parser.parse("PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -1038,7 +1138,17 @@ void freshFirstPartyPlayDoesNotReplayRetainedBufferFromAnEarlierLogout() throws TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); SessionContext freshBinding = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); when(session.getAttributes()) .thenReturn( Map.of( @@ -1084,7 +1194,17 @@ void resumedPlayRefreshesLookWhenNoRetainedBufferExists() throws Exception { TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); SessionContext binding = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); when(parser.parse("PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -1123,7 +1243,17 @@ void reconnectPlayEmitsPromptOnlyWhenBothPromptSettingsAreEnabled( TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); SessionContext binding = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); PresentationProperties presentation = new PresentationProperties( "en-NZ", @@ -1181,7 +1311,17 @@ void handleMessageUsesTenantScopedSessionContextWhenTenantAttributePresent() thr PlayerOutput output = PlayerOutput.message("Recent room line"); SessionContext clearedShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 41L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); when(parser.parse("LOOK")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -1369,7 +1509,21 @@ void handleMessageRebootsGenericSessionContextWhenSessionIndexLookupIsMissing() "LOGIN demo@example.com swordfish"); SessionContext tenantScoped = new SessionContext( - 41L, 22L, 0L, null, 0L, null, 0L, null, null, null, 7L, "demo", "production", 3L, null); + 41L, + 22L, + null, + null, + 0L, + null, + 0L, + null, + null, + null, + 7L, + "demo", + "production", + 3L, + null); when(parser.parse("LOGIN demo@example.com swordfish")).thenReturn(command); when(sessionAuthenticationService.resolveUnverifiedSessionContext(22L, 41L)) .thenReturn(Optional.of(tenantScoped)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java index cf9cc8606a..4c0077aae2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java @@ -37,6 +37,10 @@ import org.springframework.web.socket.WebSocketSession; class WebSocketOutputProjectorTest { + private static final String SORA_ACCOUNT_ID = "5f7624ca-8aee-4d34-9cd8-3ba3a1815f30"; + private static final String EMBERLINE_ACCOUNT_ID = "c91fb96e-5ad8-4e4e-a12d-2838640093b2"; + private static final String NYX_ACCOUNT_ID = "3a16e242-3467-4d98-906f-71d47b888b5e"; + private static final String REDACTED_FRIEND_ACCOUNT_ID = "6ba7b810-9dad-41d1-80b4-00c04fd430c8"; private final PresentationProperties presentation = new PresentationProperties(); private final ObjectMapper objectMapper = new ObjectMapper(); @@ -156,7 +160,15 @@ void firstPartyWebUsesAdmittedMetadataForAuthoredCommand() throws Exception { GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); SessionContext context = new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, + 22L, + "d0c68a37-5126-42d2-9506-8df13e97699e", + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); AdmittedTextCommandRegistryResolver admittedResolver = mock(AdmittedTextCommandRegistryResolver.class); when(admittedResolver.resolveMetadata(context, "wave", "wave")) @@ -254,7 +266,7 @@ void genericWebSocketProjectsFriendViewThroughFriendsRenderer() { new FriendPresenceViewOutput.Entry( 1, 77L, - 41L, + SORA_ACCOUNT_ID, "ONLINE", null, "Sora", @@ -421,7 +433,7 @@ void firstPartyWebProjectsFriendsViewPayloads() throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + SORA_ACCOUNT_ID, "active", 1_744_336_000_000L, "Sora", @@ -446,7 +458,7 @@ void firstPartyWebProjectsFriendsViewPayloads() throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + SORA_ACCOUNT_ID, "active", 1_744_336_000_000L, "Sora", @@ -477,8 +489,8 @@ void firstPartyWebProjectsFriendsViewPayloads() throws Exception { .path("friends") .get(0) .path("friendAccountId") - .asLong()) - .isEqualTo(3L); + .asText()) + .isEqualTo(SORA_ACCOUNT_ID); assertThat( json.path("outputs") .get(0) @@ -546,7 +558,7 @@ void firstPartyWebOmitsDisconnectDispositionForPublicAndFriendsOnlyPresence() th new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + EMBERLINE_ACCOUNT_ID, "active", null, "Public Friend", @@ -564,7 +576,7 @@ void firstPartyWebOmitsDisconnectDispositionForPublicAndFriendsOnlyPresence() th new FriendPresenceViewOutput.Entry( 2, 12L, - 4L, + NYX_ACCOUNT_ID, "active", null, "Friends-only Friend", @@ -611,7 +623,7 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + SORA_ACCOUNT_ID, "active", 1_744_336_000_000L, "Sora", @@ -632,7 +644,7 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + SORA_ACCOUNT_ID, "active", 1_744_336_000_000L, "Sora", @@ -660,8 +672,8 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { .path("payload") .path("friend") .path("friendAccountId") - .asLong()) - .isEqualTo(3L); + .asText()) + .isEqualTo(SORA_ACCOUNT_ID); assertThat( json.path("outputs") .get(0) @@ -692,10 +704,10 @@ void firstPartyWebOmitsRedactedFriendPresenceFields() throws Exception { new FriendPresenceViewOutput.Entry( 4, 12L, - 77L, + REDACTED_FRIEND_ACCOUNT_ID, "active", 1_744_336_000_000L, - "Friend #77", + "Friend #" + REDACTED_FRIEND_ACCOUNT_ID, null, null, null, @@ -716,10 +728,11 @@ void firstPartyWebOmitsRedactedFriendPresenceFields() throws Exception { JsonNode friend = objectMapper.readTree(payload).path("outputs").get(0).path("payload").path("friend"); - assertThat(friend.path("friendAccountId").asLong()).isEqualTo(77L); + assertThat(friend.path("friendAccountId").asText()).isEqualTo(REDACTED_FRIEND_ACCOUNT_ID); assertThat(friend.path("friendLinkId").asLong()).isEqualTo(12L); assertThat(friend.path("status").asText()).isEqualTo("active"); - assertThat(friend.path("displayName").asText()).isEqualTo("Friend #77"); + assertThat(friend.path("displayName").asText()) + .isEqualTo("Friend #" + REDACTED_FRIEND_ACCOUNT_ID); assertThat(friend.has("online")).isFalse(); assertThat(friend.has("worldSlug")).isFalse(); assertThat(friend.has("characterName")).isFalse(); @@ -818,7 +831,7 @@ void firstPartyWebProjectsFriendMutationResultPayloads() throws Exception { GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); FriendMutationResultOutput payloadView = - new FriendMutationResultOutput("REMOVE", 77L, "Sora", "Sora", 1); + new FriendMutationResultOutput("REMOVE", SORA_ACCOUNT_ID, "Sora", "Sora", 1); String payload = projector.projectCommandResponse( @@ -836,8 +849,8 @@ void firstPartyWebProjectsFriendMutationResultPayloads() throws Exception { .isEqualTo("friend_mutation_result"); assertThat(json.path("outputs").get(0).path("payload").path("action").asText()) .isEqualTo("REMOVE"); - assertThat(json.path("outputs").get(0).path("payload").path("friendAccountId").asLong()) - .isEqualTo(77L); + assertThat(json.path("outputs").get(0).path("payload").path("friendAccountId").asText()) + .isEqualTo(SORA_ACCOUNT_ID); assertThat(json.path("outputs").get(0).path("payload").path("displayName").asText()) .isEqualTo("Sora"); assertThat(json.path("outputs").get(0).path("payload").path("ordinal").asInt()).isEqualTo(1); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index 050c62a4e0..729c24ed17 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -206,7 +206,7 @@ ModerationPolicyClient moderationPolicyClient() { ModerationPolicyClient client = org.mockito.Mockito.mock(ModerationPolicyClient.class); org.mockito.Mockito.when( client.evaluateGameplayAdmission( - org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())) + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) 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 e566df0f41..902ba33f23 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 @@ -22,21 +22,21 @@ public final class RuntimeMembershipTestFixtures { private RuntimeMembershipTestFixtures() {} public static GetTenantMembershipForRuntimeResponse active( - long accountId, long tenantId, String membershipVersion) { + String accountId, long tenantId, String membershipVersion) { return complete(accountId, tenantId, true, "ACTIVE", true, membershipVersion); } - public static GetTenantMembershipForRuntimeResponse missing(long accountId, long tenantId) { + public static GetTenantMembershipForRuntimeResponse missing(String accountId, long tenantId) { return complete(accountId, tenantId, false, "MISSING", false, "1"); } public static GetTenantMembershipForRuntimeResponse inactive( - long accountId, long tenantId, String membershipVersion) { + String accountId, long tenantId, String membershipVersion) { return complete(accountId, tenantId, true, "INACTIVE", false, membershipVersion); } public static GetTenantMembershipForRuntimeResponse left( - long accountId, long tenantId, List retainedRoles) { + String accountId, long tenantId, List retainedRoles) { return complete( accountId, tenantId, true, "INACTIVE", false, "3", "2", "2", "2", true, retainedRoles); } @@ -47,20 +47,20 @@ public static GetTenantMembershipForRuntimeResponse echoRequestId( } public static GetTenantMembershipForRuntimeResponse incomplete( - long accountId, + String accountId, long tenantId, boolean membershipExists, String lifecycle, boolean gameplayAdmissionAllowed, String membershipVersion, String evaluatedAt) { - String accountUuid = uuid(accountId); + String accountUuid = accountId; String tenantUuid = uuid(tenantId); GetTenantMembershipForRuntimeResponse.Builder response = GetTenantMembershipForRuntimeResponse.newBuilder() .setAccountId(accountUuid) .setTenantId(tenantUuid) - .setRequestAccountId(Long.toString(accountId)) + .setRequestAccountId(accountId) .setRequestTenantId(Long.toString(tenantId)) .setMembershipExists(membershipExists) .setMembershipLifecycleState(lifecycle) @@ -73,7 +73,7 @@ public static GetTenantMembershipForRuntimeResponse incomplete( } public static GetTenantMembershipForRuntimeResponse advancedTenantWithZeroCheckpoint( - long accountId, long tenantId) { + String accountId, long tenantId) { GetTenantMembershipForRuntimeResponse response = active(accountId, tenantId, "1"); return response.toBuilder() .setAuthorityTuple( @@ -83,7 +83,7 @@ public static GetTenantMembershipForRuntimeResponse advancedTenantWithZeroCheckp } private static GetTenantMembershipForRuntimeResponse complete( - long accountId, + String accountId, long tenantId, boolean exists, String lifecycle, @@ -104,7 +104,7 @@ private static GetTenantMembershipForRuntimeResponse complete( } private static GetTenantMembershipForRuntimeResponse complete( - long accountId, + String accountId, long tenantId, boolean exists, String lifecycle, @@ -115,7 +115,7 @@ private static GetTenantMembershipForRuntimeResponse complete( String outboxSequence, boolean callerBoundAuthorityInvalidated, List roles) { - String accountUuid = uuid(accountId); + String accountUuid = accountId; String tenantUuid = uuid(tenantId); String membershipStream = STREAM_PREFIX + "membership/" + accountUuid + "/" + tenantUuid; List checkpoints = @@ -144,7 +144,7 @@ private static GetTenantMembershipForRuntimeResponse complete( GetTenantMembershipForRuntimeResponse.newBuilder() .setAccountId(accountUuid) .setTenantId(tenantUuid) - .setRequestAccountId(Long.toString(accountId)) + .setRequestAccountId(accountId) .setRequestTenantId(Long.toString(tenantId)) .setMembershipExists(exists) .setMembershipLifecycleState(lifecycle) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java index 5c92ce6ff3..2272947932 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java @@ -57,7 +57,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_EMBERLINE) .setTenantId("1") - .setAccountId("7") + .setAccountId("c91fb96e-5ad8-4e4e-a12d-2838640093b2") .setName("Emberline") .build(); } @@ -65,7 +65,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_SORA) .setTenantId("1") - .setAccountId("8") + .setAccountId("5f7624ca-8aee-4d34-9cd8-3ba3a1815f30") .setName("Sora") .build(); } @@ -73,7 +73,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_NYX) .setTenantId("1") - .setAccountId("9") + .setAccountId("3a16e242-3467-4d98-906f-71d47b888b5e") .setName("Nyx") .build(); } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 680cb0cbc3..6b2ddf208b 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -225,7 +225,7 @@ public void seedLiveSession(SessionContext context) { public void seedLiveSession( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -248,7 +248,7 @@ public void seedLiveSession( public void seedLiveSession( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayWebSocketDriver.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayWebSocketDriver.java index 9ace5c0d3e..81555f8240 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayWebSocketDriver.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayWebSocketDriver.java @@ -132,7 +132,12 @@ public static GameplayWebSocketDriver connectFirstPartyWeb( String jwtSecret, Map connectClaims) { return connectFirstPartyWeb( - uri, waitTimeout, transportSessionId, jwtSecret, "123", connectClaims); + uri, + waitTimeout, + transportSessionId, + jwtSecret, + "f2ed193b-12c1-4c96-bcad-c162229af440", + connectClaims); } public static GameplayWebSocketDriver connectFirstPartyWeb( From ee52078f065d260968ee29015fefdc076f716373 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 03:59:00 +1300 Subject: [PATCH 02/11] Align Account UUID fixture echoes without weakening gameplay assertions --- .../client/GameLogicClientTest.java | 11 +++++----- .../text/FriendsCommandHandlerTest.java | 4 +++- .../command/text/PlayCommandHandlerTest.java | 20 ++++++++++--------- .../text/TextCommandInterpreterTest.java | 20 +++++++------------ .../WorldsTextCommandDispatchHandlerTest.java | 18 +++++------------ .../GameplayLocalPathReadinessProbeTest.java | 2 +- 6 files changed, 33 insertions(+), 42 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java index 159d4a4586..a6ff1ab169 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java @@ -39,11 +39,12 @@ import org.mockito.ArgumentCaptor; class GameLogicClientTest { + private static final String ACCOUNT_UUID = "f2ed193b-12c1-4c96-bcad-c162229af440"; private static final SessionContext SESSION_CONTEXT = new SessionContext( 41L, 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", + ACCOUNT_UUID, "", 123L, "", @@ -331,7 +332,7 @@ void pickupVisibleRoomItemForwardsRawReferenceAndSessionContextThroughGameLogic( PickupVisibleRoomItemRequest.newBuilder() .setTenantId("22") .setSessionId("41") - .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") + .setAccountId(ACCOUNT_UUID) .setCharacterId("123") .setGameInstanceId("1") .setRoomInstanceId("R-1021") @@ -436,7 +437,7 @@ void dropCarriedItemForwardsRawReferenceAndSessionContextThroughGameLogic() thro DropCarriedItemRequest.newBuilder() .setTenantId("22") .setSessionId("41") - .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") + .setAccountId(ACCOUNT_UUID) .setCharacterId("123") .setGameInstanceId("1") .setRoomInstanceId("R-1021") @@ -541,10 +542,10 @@ private static GameLogicClient newClient() { GameplaySessionAttestationService attestationService = mock(GameplaySessionAttestationService.class); when(attestationService.issueGameplaySessionAttestation( - "22", "41", "0", "123", "1", "R-1021", "world", "realm", "17", "SHARED")) + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "world", "realm", "17", "SHARED")) .thenReturn("attestation"); when(attestationService.issueGameplaySessionAttestation( - "22", "41", "0", "123", "1", "R-2045", "world", "realm", "17", "SHARED")) + "22", "41", ACCOUNT_UUID, "123", "1", "R-2045", "world", "realm", "17", "SHARED")) .thenReturn("destination-attestation"); when(attestationService.issueInternalProbeAttestation("22", "1", "R-1021")) .thenReturn("probe-attestation"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java index feac69aeb4..657b1abbac 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java @@ -989,7 +989,9 @@ void friendsMutationRejectsSelfLink() { TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("ADD", "41"), "FRIENDS ADD 41"), + TextCommandType.FRIENDS, + java.util.List.of("ADD", CALLER_ACCOUNT_ID), + "FRIENDS ADD " + CALLER_ACCOUNT_ID), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isFalse(); 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 16dd3baa3a..2a5e0e9b5e 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 @@ -118,7 +118,7 @@ void setUp() { .echoRequestId( freshMembership( net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1")), + .active(PLAYER_ACCOUNT_ID, 22L, "1")), invocation.getArgument(0))); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -578,7 +578,8 @@ void playRejectsEntityRosterErrorWithoutBinding() { .setError(ErrorDetail.newBuilder().setCode("UNAVAILABLE").build()) .build()) .when(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -624,14 +625,15 @@ void playReadsEntitlementMembershipAndGrantBeforeActorRoster() { order .verify(accountClient) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(PLAYER_ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); order .verify(entityManagementClient) - .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test @@ -1464,7 +1466,7 @@ void playInvisibleRealmWithGrantedAccessContinuesAdmission() { assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(PLAYER_ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("sandbox"), Mockito.eq("preview"), @@ -1504,7 +1506,7 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { && saved.roomInstanceId() == null)); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(PLAYER_ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("sandbox"), Mockito.eq("preview"), @@ -1531,7 +1533,7 @@ void playNonPublicRealmDoesNotConsumePublicJoinPolicy() { assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(PLAYER_ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("sandbox"), Mockito.eq("preview"), @@ -2911,7 +2913,7 @@ private void stubOwnedRoster( String gameInstanceId, PlayableStateScope scope, Character... characters) { Mockito.doReturn(roster(characters)) .when(entityManagementClient) - .listCharactersByAccount("22", "123", gameInstanceId, scope); + .listCharactersByAccount("22", PLAYER_ACCOUNT_ID, gameInstanceId, scope); } private static ListCharactersByAccountResponse roster(Character... characters) { @@ -2924,7 +2926,7 @@ private static Character actor(String id, String name, PlayableStateScope scope) return Character.newBuilder() .setId(id) .setTenantId("22") - .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") + .setAccountId(PLAYER_ACCOUNT_ID) .setName(name) .setPlayableStateScope(scope) .build(); 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 68783f263b..59b486a344 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 @@ -87,6 +87,8 @@ @SuppressWarnings("unchecked") class TextCommandInterpreterTest { + private static final String ACCOUNT_ID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + private final CommandService commandService = Mockito.mock(CommandService.class); private final GameLogicClient gameLogicClient = Mockito.mock(GameLogicClient.class); private final EntityManagementClient entityManagementClient = @@ -161,7 +163,7 @@ void setUp() { .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken("auth-token") - .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") + .setAccountId(ACCOUNT_ID) .build()); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -169,7 +171,7 @@ void setUp() { invocation -> { var response = net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( - "f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1") + ACCOUNT_ID, 22L, "1") .toBuilder() .setEvaluatedAt(Instant.now().toString()) .build(); @@ -402,14 +404,14 @@ void setUp() { lookCacheService, new TextPlayerOutputRenderer(new PresentationProperties())); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse.newBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") .setTenantId("22") - .setAccountId("f2ed193b-12c1-4c96-bcad-c162229af440") + .setAccountId(ACCOUNT_ID) .setName("Emberline") .setLevel(12) .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) @@ -854,15 +856,7 @@ void gameplayWithRoomOnlyPartialShellStillReturnsPlayRequired() { ((InMemorySessionContextService) sessionContextService) .save( new SessionContext( - 56L, - 22L, - "f2ed193b-12c1-4c96-bcad-c162229af440", - "demo@example.com", - 0L, - null, - 0L, - "R-7", - null)); + 56L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "R-7", null)); TextCommandInterpretationResult interpretation = interpreter.interpret("56", "LOOK", false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index fd1faddd3b..33bd79441a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -23,6 +23,8 @@ import org.mockito.Mockito; class WorldsTextCommandDispatchHandlerTest { + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; + private final EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); private final GameplayCatalogProperties gameplayCatalogProperties = @@ -192,15 +194,7 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { .setOutcomeCode("CREATED") .build()); SessionContext context = - new SessionContext( - 7L, - 22L, - "11111111-1111-4111-8111-111111111111", - "emberline@example.com", - 0L, - null, - 0L, - "jwt"); + new SessionContext(7L, 22L, ACCOUNT_ID, "emberline@example.com", 0L, null, 0L, "jwt"); TextCommandInterpretationResult realmsResult = scopedHandler.handle( @@ -248,8 +242,7 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { org.mockito.ArgumentCaptor.forClass(DirectTextConnectScopeTarget.class); Mockito.verify(accountClient) .issueDirectTextConnectScope(callerCaptor.capture(), targetCaptor.capture()); - assertThat(callerCaptor.getValue().getAccountId()) - .isEqualTo("d0c68a37-5126-42d2-9506-8df13e97699e"); + assertThat(callerCaptor.getValue().getAccountId()).isEqualTo(ACCOUNT_ID); assertThat(callerCaptor.getValue().getSessionId()).isEqualTo("7"); assertThat(targetCaptor.getValue().realmId()).isEqualTo(realmId.toString()); assertThat(targetCaptor.getValue().catalogRevision()).isEqualTo(7L); @@ -275,8 +268,7 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { assertThat(requestIds.getLast()).isEqualTo(requestIds.getFirst()); assertThat(scopeIds.getLast()).isEqualTo(scopeIds.getFirst()); assertThat(joinContexts.getFirst().getRequestId()).isEqualTo(requestIds.getFirst()); - assertThat(joinContexts.getFirst().getAccountId()) - .isEqualTo("d0c68a37-5126-42d2-9506-8df13e97699e"); + assertThat(joinContexts.getFirst().getAccountId()).isEqualTo(ACCOUNT_ID); assertThat(joinContexts.getFirst().getSessionId()).isEqualTo("7"); assertThat(joinContexts.getFirst().getRealmId()).isEqualTo(realmId.toString()); assertThat(joinContexts.getLast()).isEqualTo(joinContexts.getFirst()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java index 00b4846f95..ccbc6e791d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java @@ -21,7 +21,7 @@ class GameplayLocalPathReadinessProbeTest { private static final long PROBE_SESSION_ID_BASE = 9_223_372_036_854_770_000L; - private static final String PROBE_ACCOUNT_UUID = "f2ed193b-12c1-4c96-bcad-c162229af440"; + private static final String PROBE_ACCOUNT_UUID = "ff36f51a-6cbd-4f26-8332-031535e2e3b4"; private static final long PROBE_CHARACTER_ID = 9_223_372_036_854_770_002L; @Test From de5f2a532f668f573ab6d25671f04e52ec55518f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 04:15:32 +1300 Subject: [PATCH 03/11] docs(game-session): state UUID carrier and activation limits --- .../microservices/game-session-service/runtime-and-data.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 87392bf33a..1e52710b94 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,11 +10,11 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: -- V9 adds a nullable, non-nil `gameplay_command.account_uuid` storage slot and exact repository readback for a verified producer's canonical Account identity. It preserves the complete existing row and numeric `account_id` evidence without deriving or backfilling a UUID. The current command ingress still uses its older carrier until the consumer correction is integrated; retained rows without authenticated mapping cannot become canonical UUID evidence. Storage availability alone does not prove caller authorization, retained-command replay, or activation of the denied credential and membership paths. +- Command ingress carries the canonical Account UUID unchanged into V9's `gameplay_command.account_uuid` slot; an absent Account identity does not invent either a UUID or private numeric selector. Existing numeric row evidence is retained without guessed mapping or backfill. Retained-command replay, complete owner/consumer handoff and activation remain unproved; component implementation and proof are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). - The shared Gateway connect-context codec now declares and verifies the complete signed-context shape and has local vectors, but first-party runtime parsing remains fail-closed. It does not admit the target context until the independent Gateway Ed25519 verification key is published, Account-to-tenant UUID mapping is available, and the real Account exchange/source-evidence path is proved. Codec and vector presence is not a live issuer/consumer handoff or gameplay-admission proof. -- The Account membership client rejects noncanonical, nil or numeric Account/tenant selectors before stub/channel use and preserves exact UUID request echoes. This is boundary validation, not Account authorization. The current numeric session/catalog carriers still lack the proved canonical UUID handoff required by the [Identifier Glossary](../../system-architecture-identifier-glossary.md#identifier-format-conventions); numeric stringification cannot satisfy that handoff. The complete signed-context parser, Account runtime RPC and credential producer remain denied; component and runtime proof are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). +- 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). - 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). From 3c9dab0f5f17d2ca9355d6e18d3d4b1e9ceb0301 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 04:19:43 +1300 Subject: [PATCH 04/11] docs(access): distinguish UUID carriers from activation proof --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 1f796d059c..9479e3a738 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,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The Account authentication producer now returns its exact persisted canonical non-nil UUID and signs that same identity in `sub`/`accountId` for password and email-OTP paths. Profile and supported self-service readers first bind the canonical UUID to the authenticated subject, then perform an Account-owned read-only provenance-checked lookup of the private numeric storage key; an unmapped UUID cannot select or mutate another row. Disabled deletion, login-factor mutation and tenant export remain denied without writes. Other numeric DTO, catalog and cross-service consumers are explicitly unfinished; this component does not establish a working end-to-end login/admission path. Game Session V9 separately adds exact command UUID storage without altering or inventing identities for retained numeric rows. The consumer-carrier correction remains a separate unpublished candidate. +The Account authentication producer now returns its exact persisted canonical non-nil UUID and signs that same identity in `sub`/`accountId` for password and email-OTP paths. Profile and supported self-service readers first bind the canonical UUID to the authenticated subject, then perform an Account-owned read-only provenance-checked lookup of the private numeric storage key; an unmapped UUID cannot select or mutate another row. Disabled deletion, login-factor mutation and tenant export remain denied without writes. Game Session's consumer candidate preserves canonical Account UUIDs in LOGIN, sessions, presence, Account-qualified client requests and V9 command storage; it no longer stringifies private numeric Account keys. Retained command evidence is preserved without inferred mapping or backfill, and unreadable retained Redis session/presence values fail closed without deletion. Tenant/catalog carriers and other cross-service owners remain unfinished; this component does not establish a working authenticated end-to-end login/admission path. First-party credential/context parsing, Account runtime membership and catalog activation remain denied; the candidate has no authorization to publish beyond the file ceiling. Local consolidated Account/Game Session full checks and JARs passed (156 tasks, 72 executed/84 up-to-date), including formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown. Account's 502 unit cases passed in the preceding same-code execution; their final task was up-to-date, not a second execution. All 149 Account PostgreSQL cases compiled/discovered and skipped without Docker, including the three new persisted-identity/profile no-mutation cases. Game Session executed 1,747 unit, 18 non-PostgreSQL integration and one cross-service case; 17 unit, 133 integration and 33 cross-service cases skipped, including five new command-storage/migration cases. The earlier possible-null integration fixture readback defect was corrected with explicit required-row checks, not an analyzer suppression. Ring publication infrastructure is an open Platform Operations prerequisite; its mount and all previously denied activation paths remain held back. From 0f7346f6cdb51b9f36997ed5397e105c93a1ff0f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 06:06:28 +1300 Subject: [PATCH 05/11] Record composed UUID carrier proof and remaining management boundary --- .../implementation-tracking/player-access-and-session.md | 4 ++++ 1 file changed, 4 insertions(+) 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 8e536d17ad..05a041df2d 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,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The local Game Session Account-UUID carrier candidate normally incorporates published Account parent `91c062f6b43159ee57a3d53c82e940014728047f` at `b26efb3fdcc6b4ed095353fb6eca189a0c9923a7`, preserving all preceding Game Session service hunks. Composed Account/Game Session full checks and JARs, links and Markdown passed154tasks(79executed/13from-cache/62up-to-date). Game Session executed1,752unit,18non-PostgreSQL integration and1cross-service cases with zero failures/errors;17unit,133integration and33cross-service cases skipped. Account's508unit and159skipped PostgreSQL results were restored from cache, not newly executed in that composed run. All PostgreSQL proof limits remain explicit. The candidate has108unique files, including its required owner/status documents, and remains unpublished pending cap treatment. + +The separate Game Session management/catalog Account carrier remains required: dev-demo forwards `/auth/player-bootstrap`'s canonical UUID as `ownerAccountId`, but the current `StartSession` handler parses it as a positive Long and `StartSessionRequest`/OpenAPI still declare numeric storage. The session/presence/client candidate above does not fix this boundary. It needs canonical Account carrier convergence alongside the Game Session-owned catalog/tenant source handoff and focused producer/consumer proof; it must not infer a numeric Account identity or claim that registration DTO convergence enables session creation. + Registration and the Account component of the local export now emit the exact persisted canonical UUID as `AccountDto.id`; `CreateAccount` returns it unchanged, and new `ACCOUNT_REGISTERED` platform audit payloads bind that same UUID. The private numeric row key remains only an Account-owned storage selector. The unused reverse DTO-to-entity mapper is removed; no UUID-to-numeric compatibility path is added and retained audit history is not rewritten. Export verifies UUID/provenance/source-row readback before profile reads, with unmapped and contradictory identity denial tests. Profile and tenant DTO identities remain open migration work. The affected full Account check/JAR and docs passed70tasks(42executed/28up-to-date);508unit cases executed without failures/errors/skips, while all159PostgreSQL cases compiled/discovered but skipped without Docker. Updated registration UUID/private-row and exact durable-audit assertions still require corrected-head runner execution. No credential, membership RPC, catalog or ring mount is enabled. Exact bootstrap UUID source `56a222bf289caa710285bf8655eee1d04161b22e` [CI36888416843](https://github.com/benhook1013/FireMUD/actions/runs/36888416843) executed all12Account UUID/OTP/bootstrap and2HTTP cases without skips. Thirteen passed, including the three new bootstrap UUID cases; one existing OTP case failed during Mockito setup through a Spring repository proxy, not at its persistence assertion. The corrected fixture configures and verifies ultimate Mockito targets while the tested service still uses its real injected proxies and owner transaction. A separate scheduled-cleanup warning is not established as the cause. Corrected-head runner proof remains required. From a36d7ea131be760e250b9b5b86743e27272f36e8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 06:43:41 +1300 Subject: [PATCH 06/11] Preserve composed UUID availability proof and exact Account fixtures --- .../player-access-and-session.md | 2 ++ .../command/text/PlayCommandHandlerTest.java | 21 +++++++++++++------ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 751fc6c510..09c2cfd0bc 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 preserved local Game Session UUID child normally incorporates published Account parent `b93efaedbaec8a36294a594a946a010641e345b4` at `5c12cd690929b935a7169fed456e50e028a1d284`. Its two newly imported availability tests now use the existing exact canonical Account UUID fixture rather than a numeric Account selector; tenant/lifecycle/no-mutation predicates are unchanged. Composed Account/Game Session/Common Test Support checks, both JARs, formatting/static analysis and docs passed164tasks(82executed/29from-cache/53up-to-date). Game Session executed1,767unit,18non-PostgreSQL integration and1cross-service cases with zero failures/errors, while17unit/133integration/33cross-service cases skipped. Account508unit and159skipped PostgreSQL results and Common Test Support43unit results came from cache, not new execution. Normal ancestry retains the original carrier preservation commit and exact corrected parent; only the parent's availability and port-fixture changes and the two required UUID test adaptations alter the preceding Game Session subtree. The child remains108unique files and unpublished pending cap treatment. All activation and live producer/consumer gates remain closed. + The local Game Session Account-UUID carrier candidate normally incorporates published Account parent `91c062f6b43159ee57a3d53c82e940014728047f` at `b26efb3fdcc6b4ed095353fb6eca189a0c9923a7`, preserving all preceding Game Session service hunks. Composed Account/Game Session full checks and JARs, links and Markdown passed154tasks(79executed/13from-cache/62up-to-date). Game Session executed1,752unit,18non-PostgreSQL integration and1cross-service cases with zero failures/errors;17unit,133integration and33cross-service cases skipped. Account's508unit and159skipped PostgreSQL results were restored from cache, not newly executed in that composed run. All PostgreSQL proof limits remain explicit. The candidate has108unique files, including its required owner/status documents, and remains unpublished pending cap treatment. The separate Game Session management/catalog Account carrier remains required: dev-demo forwards `/auth/player-bootstrap`'s canonical UUID as `ownerAccountId`, but the current `StartSession` handler parses it as a positive Long and `StartSessionRequest`/OpenAPI still declare numeric storage. The session/presence/client candidate above does not fix this boundary. It needs canonical Account carrier convergence alongside the Game Session-owned catalog/tenant source handoff and focused producer/consumer proof; it must not infer a numeric Account identity or claim that registration DTO convergence enables session creation. 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 5782072b62..db96044ef0 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 @@ -2653,7 +2653,16 @@ void playWhenMembershipAuthorityUnavailableFailsClosed(String errorCode) { void playRequiresExplicitAvailableMembershipAuthorityBeforePublicOutcomes( String lifecycle, String availability) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + "f2ed193b-12c1-4c96-bcad-c162229af440", + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) @@ -2663,13 +2672,13 @@ void playRequiresExplicitAvailableMembershipAuthorityBeforePublicOutcomes( switch (lifecycle) { case "ACTIVE" -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .active(123L, 22L, "1"); + .active("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "1"); case "MISSING" -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L); + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L); case "INACTIVE" -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive(123L, 22L, "3"); + .inactive("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "3"); default -> throw new IllegalArgumentException("Unexpected lifecycle: " + lifecycle); }; @@ -2716,9 +2725,9 @@ void playRequiresExplicitAvailableMembershipAuthorityBeforeNonPublicOutcome( var membership = "MISSING".equals(lifecycle) ? net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .missing(123L, 22L) + .missing("f2ed193b-12c1-4c96-bcad-c162229af440", 22L) : net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive(123L, 22L, "3"); + .inactive("f2ed193b-12c1-4c96-bcad-c162229af440", 22L, "3"); var builder = freshMembership(membership).toBuilder(); if (!"ABSENT".equals(availability)) { builder.setAuthorityAvailability(availability); From 41976ef14d8a8e187e925305b868711c79276d73 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 09:23:52 +1300 Subject: [PATCH 07/11] Converge canonical Account UUID authority and actor fixtures --- .../test/AccountRuntimeStubServerTest.java | 106 +++++++++++++++-- .../test/AccountRuntimeStubServer.java | 107 ++++++++++-------- ...ommunicationWebSocketCrossServiceTest.java | 106 +++++++++-------- .../LookWebSocketCrossServiceTest.java | 11 +- .../MultiplayerLoadProofCrossServiceTest.java | 22 ++-- .../gamesession/test/ChatTestFixtures.java | 9 +- .../stubs/EntityManagementStubServer.java | 54 ++++++--- .../GameplayCrossServiceStack.java | 31 ++--- .../testsupport/GameplayLoadScenarios.java | 41 ++++--- ...ionAccountCrossServiceIntegrationTest.java | 28 +++-- 10 files changed, 333 insertions(+), 182 deletions(-) diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index 6aa0551522..7fc1dd6f56 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java @@ -1,10 +1,12 @@ package net.firedevops.firemud.test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.time.Instant; +import java.util.Locale; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.GetProfileRequest; @@ -16,6 +18,9 @@ import org.junit.jupiter.api.Test; class AccountRuntimeStubServerTest { + private static final String ACCOUNT_UUID = "c91fb96e-5ad8-4e4e-a12d-2838640093b2"; + private static final String NIL_ACCOUNT_UUID = "00000000-0000-0000-0000-000000000000"; + @Test void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmission() throws Exception { @@ -25,7 +30,7 @@ void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmissio try { AccountServiceGrpc.AccountServiceBlockingStub stub = AccountServiceGrpc.newBlockingStub(channel); - server.mapAccountId("demo@example.com", 7L); + server.mapAccountUuid("demo@example.com", ACCOUNT_UUID); assertThat( stub.authenticate( @@ -34,13 +39,13 @@ void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmissio .setPassword("password") .build()) .getAccountId()) - .isEqualTo("7"); + .isEqualTo(ACCOUNT_UUID); var request = GetTenantMembershipForRuntimeRequest.newBuilder() .setPlayerContext( net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() - .setAccountId("7") + .setAccountId(ACCOUNT_UUID) .setTenantId("1") .setRequestId("request-1")) .build(); @@ -48,6 +53,8 @@ void authenticationCanonicalizesMappedEmailAndMembershipLifecycleMatchesAdmissio GetTenantMembershipForRuntimeResponse active = stub.getTenantMembershipForRuntime(request); Instant activeAfter = Instant.now(); assertThat(active.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(active.getAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(active.getRequestAccountId()).isEqualTo(ACCOUNT_UUID); assertThat(active.getRequestId()).isEqualTo("request-1"); assertThat(active.getMembershipAuthorityGeneration()).isEqualTo("1"); assertMembershipEventMatches(active, "ACTIVE", true); @@ -138,7 +145,10 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { AccountProfileJson initialProfile = AccountProfileJson.parse( stub.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("7").build()) + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .build()) .getProfileJson(), "FRIENDS_ONLY"); assertThat(initialProfile.presenceVisibilityPolicy()).isEqualTo("FRIENDS_ONLY"); @@ -147,11 +157,10 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { stub.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId("7") + .setAccountId(ACCOUNT_UUID) .setProfileJson( - """ - {"displayName":"Demo-7","bio":null,"presenceVisibilityPolicy":"PRIVATE"} - """) + "{\"displayName\":\"Demo-%s\",\"bio\":null,\"presenceVisibilityPolicy\":\"PRIVATE\"}" + .formatted(ACCOUNT_UUID)) .build()) .getSuccess()) .isTrue(); @@ -159,7 +168,10 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { AccountProfileJson updatedProfile = AccountProfileJson.parse( stub.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("7").build()) + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .build()) .getProfileJson(), "FRIENDS_ONLY"); assertThat(updatedProfile.presenceVisibilityPolicy()).isEqualTo("PRIVATE"); @@ -169,6 +181,65 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { } } + @Test + void rejectsInvalidAccountSelectorsForRegistrationAndProfileMutation() throws Exception { + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + server.setDefaultAccountUuid(ACCOUNT_UUID); + assertThat( + stub.updateProfile(profileUpdate(ACCOUNT_UUID, "Protected profile")).getSuccess()) + .isTrue(); + + String[] invalidAccountUuids = { + "7", ACCOUNT_UUID.toUpperCase(Locale.ROOT), NIL_ACCOUNT_UUID + }; + for (String invalidAccountUuid : invalidAccountUuids) { + assertThatThrownBy( + () -> server.mapAccountUuid("candidate@example.com", invalidAccountUuid)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> server.setDefaultAccountUuid(invalidAccountUuid)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> server.setPresenceVisibilityPolicy(invalidAccountUuid, "PRIVATE")) + .isInstanceOf(IllegalArgumentException.class); + assertThat( + stub.updateProfile(profileUpdate(invalidAccountUuid, "Overwritten profile")) + .getSuccess()) + .isFalse(); + } + + assertThatThrownBy(() -> server.mapAccountUuid("candidate@example.com", null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> server.setDefaultAccountUuid(null)) + .isInstanceOf(IllegalArgumentException.class); + AuthenticateRequest candidateRequest = + AuthenticateRequest.newBuilder() + .setEmail("candidate@example.com") + .setPassword("password") + .build(); + assertThat(stub.authenticate(candidateRequest).getAccountId()).isEqualTo(ACCOUNT_UUID); + + AccountProfileJson protectedProfile = + AccountProfileJson.parse( + stub.getProfile( + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .build()) + .getProfileJson(), + "FRIENDS_ONLY"); + assertThat(protectedProfile.displayName()).isEqualTo("Protected profile"); + assertThat(protectedProfile.presenceVisibilityPolicy()).isEqualTo("PRIVATE"); + } finally { + channel.shutdownNow(); + } + } + } + @Test void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { @@ -182,7 +253,7 @@ void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { stub.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId("7") + .setAccountId(ACCOUNT_UUID) .setProfileJson( """ {"displayName":"Demo-7","bio":null,"presenceVisibilityPolicy":"PRIVATE"} @@ -196,7 +267,10 @@ void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { AccountProfileJson resetProfile = AccountProfileJson.parse( stub.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("7").build()) + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .build()) .getProfileJson(), "FRIENDS_ONLY"); assertThat(resetProfile.presenceVisibilityPolicy()).isEqualTo("FRIENDS_ONLY"); @@ -205,4 +279,14 @@ void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { } } } + + private static UpdateProfileRequest profileUpdate(String accountUuid, String displayName) { + return UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountUuid) + .setProfileJson( + "{\"displayName\":\"%s\",\"bio\":null,\"presenceVisibilityPolicy\":\"PRIVATE\"}" + .formatted(displayName)) + .build(); + } } diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index ca7ed5a663..ad125758d0 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -10,6 +10,7 @@ import java.util.Locale; import java.util.Map; import java.util.Set; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; @@ -49,6 +50,7 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe implements AutoCloseable { private static final String AUTHORITY_STREAM_PREFIX = "account:auth-authority:v1:"; private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final String DEFAULT_ACCOUNT_UUID = "a7e0feac-60ab-4fd1-9002-0ad38d585db0"; private static final String MEMBERSHIP_EVENT_ID = "00000000-0000-0000-0000-000000000099"; private static final String MEMBERSHIP_EVENT_REQUEST_ID = "runtime-membership-request"; private static final Set IMPLEMENTED_RUNTIME_METHODS = @@ -69,10 +71,11 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe private final AtomicBoolean gameplayAvailable = new AtomicBoolean(true); private final AtomicBoolean allowPublicJoin = new AtomicBoolean(true); private final AtomicBoolean realmAccessGranted = new AtomicBoolean(true); - private final AtomicLong defaultAccountId = new AtomicLong(1L); + private final AtomicReference defaultAccountUuid = + new AtomicReference<>(DEFAULT_ACCOUNT_UUID); private final AtomicLong nextConnectScopeId = new AtomicLong(1L); - private final Map accountIdsByEmail = new ConcurrentHashMap<>(); - private final Map profilesByAccountId = new ConcurrentHashMap<>(); + private final Map accountUuidsByEmail = new ConcurrentHashMap<>(); + private final Map profilesByAccountUuid = new ConcurrentHashMap<>(); private final Map connectScopesById = new ConcurrentHashMap<>(); public AccountRuntimeStubServer(int port) throws IOException { @@ -91,19 +94,21 @@ public List capturedAuthenticateRequests() { return List.copyOf(authenticateRequests); } - public void setDefaultAccountId(long accountId) { - defaultAccountId.set(accountId); + public void setDefaultAccountUuid(String accountUuid) { + defaultAccountUuid.set(requireCanonicalAccountUuid(accountUuid)); } - public void mapAccountId(String email, long accountId) { - accountIdsByEmail.put(EmailCanonicalization.normalize(email), accountId); + public void mapAccountUuid(String email, String accountUuid) { + accountUuidsByEmail.put( + EmailCanonicalization.normalize(email), requireCanonicalAccountUuid(accountUuid)); } - public void setPresenceVisibilityPolicy(long accountId, String visibilityPolicy) { - profilesByAccountId.compute( - accountId, + public void setPresenceVisibilityPolicy(String accountUuid, String visibilityPolicy) { + String canonicalAccountUuid = requireCanonicalAccountUuid(accountUuid); + profilesByAccountUuid.compute( + canonicalAccountUuid, (ignored, current) -> - (current == null ? StubProfile.defaultFor(accountId) : current) + (current == null ? StubProfile.defaultFor(canonicalAccountUuid) : current) .withPresenceVisibilityPolicy(visibilityPolicy)); } @@ -150,7 +155,7 @@ public void resetRuntimeState() { gameplayAvailable.set(true); allowPublicJoin.set(true); realmAccessGranted.set(true); - profilesByAccountId.clear(); + profilesByAccountUuid.clear(); } @Override @@ -164,12 +169,12 @@ public void authenticate( AuthenticateRequest request, StreamObserver responseObserver) { authenticateRequests.add(request); String canonicalEmail = EmailCanonicalization.normalize(request.getEmail()); - long accountId = accountIdsByEmail.getOrDefault(canonicalEmail, defaultAccountId.get()); - profilesByAccountId.computeIfAbsent(accountId, StubProfile::defaultFor); + String accountUuid = accountUuidsByEmail.getOrDefault(canonicalEmail, defaultAccountUuid.get()); + profilesByAccountUuid.computeIfAbsent(accountUuid, StubProfile::defaultFor); responseObserver.onNext( AuthenticateResponse.newBuilder() - .setAccountId(Long.toString(accountId)) - .setAuthToken("stub-token-" + accountId) + .setAccountId(accountUuid) + .setAuthToken("stub-token-" + accountUuid) .build()); responseObserver.onCompleted(); } @@ -179,7 +184,7 @@ public void getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest request, StreamObserver responseObserver) { boolean exists = membershipExists.get(); - String accountSelector = request.getPlayerContext().getAccountId(); + String accountUuid = requireCanonicalAccountUuid(request.getPlayerContext().getAccountId()); String tenantSelector = request.getPlayerContext().getTenantId(); String lifecycle = membershipLifecycleState.get(); boolean admitted = gameplayAdmissionAllowed.get(); @@ -187,30 +192,21 @@ public void getTenantMembershipForRuntime( if (exists && admitted && "ACTIVE".equals(lifecycle)) { response = completeMembershipSnapshot( - accountSelector, - tenantSelector, - request.getPlayerContext().getRequestId(), - lifecycle); + accountUuid, tenantSelector, request.getPlayerContext().getRequestId(), lifecycle); } else if (exists && !admitted && "INACTIVE".equals(lifecycle)) { response = completeMembershipSnapshot( - accountSelector, - tenantSelector, - request.getPlayerContext().getRequestId(), - lifecycle); + accountUuid, tenantSelector, request.getPlayerContext().getRequestId(), lifecycle); } else if (!exists && !admitted && "MISSING".equals(lifecycle)) { response = completeMembershipSnapshot( - accountSelector, - tenantSelector, - request.getPlayerContext().getRequestId(), - lifecycle); + accountUuid, tenantSelector, request.getPlayerContext().getRequestId(), lifecycle); } else { response = GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId(canonicalUuid(accountSelector)) - .setTenantId(canonicalUuid(tenantSelector)) - .setRequestAccountId(accountSelector) + .setAccountId(accountUuid) + .setTenantId(syntheticTenantUuid(tenantSelector)) + .setRequestAccountId(accountUuid) .setRequestTenantId(tenantSelector) .setRequestId(request.getPlayerContext().getRequestId()) .setMembershipExists(exists) @@ -224,11 +220,10 @@ public void getTenantMembershipForRuntime( } private static GetTenantMembershipForRuntimeResponse completeMembershipSnapshot( - String accountSelector, String tenantSelector, String requestId, String lifecycle) { + String accountUuid, String tenantSelector, String requestId, String lifecycle) { boolean exists = !"MISSING".equals(lifecycle); boolean admitted = "ACTIVE".equals(lifecycle); - String accountUuid = canonicalUuid(accountSelector); - String tenantUuid = canonicalUuid(tenantSelector); + String tenantUuid = syntheticTenantUuid(tenantSelector); String membershipStream = AUTHORITY_STREAM_PREFIX + "membership/" + accountUuid + "/" + tenantUuid; List checkpoints = @@ -257,7 +252,7 @@ private static GetTenantMembershipForRuntimeResponse completeMembershipSnapshot( GetTenantMembershipForRuntimeResponse.newBuilder() .setAccountId(accountUuid) .setTenantId(tenantUuid) - .setRequestAccountId(accountSelector) + .setRequestAccountId(accountUuid) .setRequestTenantId(tenantSelector) .setRequestId(requestId) .setAuthorityAvailability("AVAILABLE") @@ -321,10 +316,29 @@ private static RuntimeOutboxCheckpoint checkpoint(String streamKey, String seque .build(); } - private static String canonicalUuid(String selector) { + private static String requireCanonicalAccountUuid(String selector) { + if (selector == null) { + throw new IllegalArgumentException("Account UUID must be canonical and non-nil"); + } + UUID parsed; + try { + parsed = UUID.fromString(selector); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Account UUID must be canonical and non-nil", exception); + } + if ((parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) + || !parsed.toString().equals(selector)) { + throw new IllegalArgumentException("Account UUID must be canonical and non-nil"); + } + return selector; + } + + private static String syntheticTenantUuid(String selector) { + // This stable UUID-shaped key is only a legacy synthetic-tenant test fixture. It is not + // evidence of an Account-owned tenant identity or an authenticated membership snapshot. long value = Long.parseLong(selector); if (value <= 0L || !Long.toString(value).equals(selector)) { - throw new IllegalArgumentException("runtime membership fixture selector must be canonical"); + throw new IllegalArgumentException("synthetic tenant fixture selector must be canonical"); } return "00000000-0000-0000-0000-" + String.format(Locale.ROOT, "%012d", value); } @@ -468,9 +482,10 @@ public void joinPublicProductionMembership( @Override public void getProfile( GetProfileRequest request, StreamObserver responseObserver) { - long accountId = Long.parseLong(request.getAccountId()); - StubProfile profile = profilesByAccountId.computeIfAbsent(accountId, StubProfile::defaultFor); try { + String accountUuid = requireCanonicalAccountUuid(request.getAccountId()); + StubProfile profile = + profilesByAccountUuid.computeIfAbsent(accountUuid, StubProfile::defaultFor); responseObserver.onNext( GetProfileResponse.newBuilder() .setProfileJson( @@ -489,13 +504,13 @@ public void getProfile( public void updateProfile( UpdateProfileRequest request, StreamObserver responseObserver) { try { - long accountId = Long.parseLong(request.getAccountId()); + String accountUuid = requireCanonicalAccountUuid(request.getAccountId()); AccountProfileJson profile = AccountProfileJson.parse(request.getProfileJson(), StubProfile.DEFAULT_VISIBILITY_POLICY); StubProfile existing = - profilesByAccountId.computeIfAbsent(accountId, StubProfile::defaultFor); - profilesByAccountId.put( - accountId, + profilesByAccountUuid.computeIfAbsent(accountUuid, StubProfile::defaultFor); + profilesByAccountUuid.put( + accountUuid, new StubProfile( profile.displayName(), profile.bio(), @@ -518,8 +533,8 @@ public void close() { private record StubProfile(String displayName, String bio, String presenceVisibilityPolicy) { private static final String DEFAULT_VISIBILITY_POLICY = "FRIENDS_ONLY"; - private static StubProfile defaultFor(long accountId) { - return new StubProfile("Demo-" + accountId, null, DEFAULT_VISIBILITY_POLICY); + private static StubProfile defaultFor(String accountUuid) { + return new StubProfile("Demo-" + accountUuid, null, DEFAULT_VISIBILITY_POLICY); } private StubProfile withPresenceVisibilityPolicy(String visibilityPolicy) { diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index e44dc7b3c0..1b1ed1ae38 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -29,8 +29,14 @@ class CommunicationWebSocketCrossServiceTest { private static final Duration COMMAND_WAIT = Duration.ofSeconds(45); private static final long TENANT_ID = 1L; - private static final long ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_EMBERLINE); - private static final long SORA_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_SORA); + private static final String ACCOUNT_UUID = ChatTestFixtures.ACCOUNT_UUID_EMBERLINE; + private static final String SORA_ACCOUNT_UUID = ChatTestFixtures.ACCOUNT_UUID_SORA; + private static final String NYX_ACCOUNT_UUID = ChatTestFixtures.ACCOUNT_UUID_NYX; + private static final long EMBERLINE_CHARACTER_ID = + Long.parseLong(ChatTestFixtures.PLAYER_EMBERLINE); + private static final long SORA_CHARACTER_ID = Long.parseLong(ChatTestFixtures.PLAYER_SORA); + private static final long NYX_CHARACTER_ID = Long.parseLong(ChatTestFixtures.PLAYER_NYX); + private static final long MANAGEMENT_OWNER_SELECTOR = EMBERLINE_CHARACTER_ID; private static final long DEMO_WORLD_INSTANCE_ID = 1L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; private static final String SORA_EMAIL = "sora@example.com"; @@ -75,7 +81,7 @@ void websocketSayFlowReportsCanonicalTranscriptAndMetrics() throws Exception { .hasValueSatisfying( request -> { assertThat(request.getTenantId()).isEqualTo(Long.toString(TENANT_ID)); - assertThat(request.getAccountId()).isEqualTo(Long.toString(ACCOUNT_ID)); + assertThat(request.getAccountId()).isEqualTo(ACCOUNT_UUID); assertThat(request.getGameInstanceId()) .isEqualTo(Long.toString(DEMO_WORLD_INSTANCE_ID)); assertThat(request.getPlayableStateScope()) @@ -201,7 +207,7 @@ void websocketFriendsShowsCanonicalCrossGamePresence() throws Exception { runCommunicationSequence( sessionId, "FRIENDS", - "Sora [acct #" + SORA_ACCOUNT_ID + "] - online in Demo World / Live Realm (idle)"); + "Sora [acct #" + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); assertThat(responses).hasSizeGreaterThanOrEqualTo(3); assertThat(responses) @@ -209,10 +215,10 @@ void websocketFriendsShowsCanonicalCrossGamePresence() throws Exception { response -> response.contains( "Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)")); GameplaySocialAssertions.assertListFriendsRequest( - socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), Long.toString(ACCOUNT_ID)); + socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); } @Test @@ -226,7 +232,7 @@ void websocketFriendsOnlineFiltersCanonicalRoster() throws Exception { "FRIENDS ONLINE", "Friends ONLINE [1/1]:\n" + "1) Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); assertThat(responses) @@ -235,12 +241,12 @@ void websocketFriendsOnlineFiltersCanonicalRoster() throws Exception { response.contains("Friends ONLINE [1/1]:") && response.contains( "1) Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)")); GameplaySocialAssertions.assertListFriendsRequest( socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), + ACCOUNT_UUID, net.firedevops.firemud.socialgroups.v1.FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); } @@ -255,7 +261,7 @@ void websocketFriendsSharedFiltersCanonicalRoster() throws Exception { "FRIENDS SHARED", "Friends SHARED [1/1]:\n" + "1) Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); assertThat(responses) @@ -264,12 +270,12 @@ void websocketFriendsSharedFiltersCanonicalRoster() throws Exception { response.contains("Friends SHARED [1/1]:") && response.contains( "1) Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)")); GameplaySocialAssertions.assertListFriendsRequest( socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), + ACCOUNT_UUID, net.firedevops.firemud.socialgroups.v1.FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED); } @@ -284,14 +290,14 @@ void freshGameplayBaselineReappliesConfiguredFriendPresenceBaseline() throws Exc runCommunicationSequence( sessionId, "FRIENDS", - "Sora [acct #" + SORA_ACCOUNT_ID + "] - online in Demo World / Live Realm (idle)"); + "Sora [acct #" + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); assertThat(responses) .anyMatch( response -> response.contains( "Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)")); } @@ -300,7 +306,7 @@ void websocketFriendsDetailRedactsMissingPolicyPresenceWithoutDisconnecting() th ensureTestServicesStarted(); FriendPresenceEntry missingPolicyPresence = FriendPresenceEntry.newBuilder() - .setFriendAccountId(Long.toString(SORA_ACCOUNT_ID)) + .setFriendAccountId(SORA_ACCOUNT_UUID) .setOnline(true) .setCharacterId(ChatTestFixtures.PLAYER_SORA) .setCharacterName("Sora") @@ -336,22 +342,22 @@ void websocketFriendsMutationFlowUsesCanonicalRosterSurface() throws Exception { try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-mutate-conn")) { - client.send("FRIENDS ADD 77"); - client.awaitContains("Friend #77 added."); - client.send("FRIENDS REMOVE 77"); - client.awaitContains("Friend #77 removed."); + client.send("FRIENDS ADD " + SORA_ACCOUNT_UUID); + client.awaitContains("Friend #" + SORA_ACCOUNT_UUID + " added."); + client.send("FRIENDS REMOVE " + SORA_ACCOUNT_UUID); + client.awaitContains("Friend #" + SORA_ACCOUNT_UUID + " removed."); } GameplaySocialAssertions.assertAddFriendRequest( socialStub().lastAddFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - "77"); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); GameplaySocialAssertions.assertRemoveFriendRequest( socialStub().lastRemoveFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - "77"); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); } @Test @@ -362,21 +368,21 @@ void websocketFriendsMutationByCharacterNameUsesCanonicalIdentityLookup() throws try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-mutate-name-conn")) { client.send("FRIENDS ADD Sora"); - client.awaitContains("Sora [acct #" + SORA_ACCOUNT_ID + "] added."); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] added."); client.send("FRIENDS REMOVE Sora"); - client.awaitContains("Sora [acct #" + SORA_ACCOUNT_ID + "] removed."); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] removed."); } GameplaySocialAssertions.assertAddFriendRequest( socialStub().lastAddFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - Long.toString(SORA_ACCOUNT_ID)); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); GameplaySocialAssertions.assertRemoveFriendRequest( socialStub().lastRemoveFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - Long.toString(SORA_ACCOUNT_ID)); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); } @Test @@ -387,14 +393,11 @@ void websocketFriendsRemoveByRosterOrdinalUsesRenderedRosterIdentity() throws Ex try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-remove-ordinal-conn")) { client.send("FRIENDS REMOVE #1"); - client.awaitContains("Sora [acct #" + SORA_ACCOUNT_ID + "] removed."); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] removed."); } GameplaySocialAssertions.assertRemoveFriendByOrdinalRequest( - socialStub().lastRemoveFriendByOrdinalRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - 1); + socialStub().lastRemoveFriendByOrdinalRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID, 1); } @Test @@ -405,16 +408,13 @@ void websocketFriendsShowUsesCanonicalFriendDetailSurface() throws Exception { try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-show-detail-conn")) { client.send("FRIENDS SHOW #1"); - client.awaitContains("Friend Sora [acct #" + SORA_ACCOUNT_ID + "]"); + client.awaitContains("Friend Sora [acct #" + SORA_ACCOUNT_UUID + "]"); client.awaitContains("Presence: online in Demo World / Live Realm (idle)"); client.awaitContains("Roster entry: #1"); } GameplaySocialAssertions.assertGetFriendByOrdinalRequest( - socialStub().lastGetFriendByOrdinalRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - 1); + socialStub().lastGetFriendByOrdinalRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID, 1); } @Test @@ -433,7 +433,7 @@ void websocketFriendsSummaryUsesCanonicalRosterSummarySurface() throws Exception } GameplaySocialAssertions.assertFriendRosterSummaryRequest( - socialStub().lastSummaryRequest(), Long.toString(TENANT_ID), Long.toString(ACCOUNT_ID)); + socialStub().lastSummaryRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); } @Test @@ -451,13 +451,11 @@ void websocketFriendsVisibilityShowsCurrentPolicy() throws Exception { } GameplaySocialAssertions.assertGetVisibilityRequest( - socialStub().lastGetVisibilityRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID)); + socialStub().lastGetVisibilityRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); GameplaySocialAssertions.assertUpdateVisibilityRequest( socialStub().lastUpdateVisibilityRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), + ACCOUNT_UUID, FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); } @@ -640,15 +638,15 @@ void websocketEquipmentLoopMovesCarriedItemThroughSlotAndBack() throws Exception private static synchronized void ensureTestServicesStarted() throws Exception { if (STACK == null) { STACK = - GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_ID) - .mapAccountId("sora@example.com", SORA_ACCOUNT_ID) + GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_UUID) + .mapAccountUuid("sora@example.com", SORA_ACCOUNT_UUID) .withInitialRoomEntities(ChatTestFixtures.sampleEntities()) .withSocialEnabled(true) .withInitialFriendPresenceResponse( net.firedevops.firemud.socialgroups.v1.ListFriendPresenceResponse.newBuilder() .addPresences( FriendPresenceEntry.newBuilder() - .setFriendAccountId(Long.toString(SORA_ACCOUNT_ID)) + .setFriendAccountId(SORA_ACCOUNT_UUID) .setOnline(true) .setCharacterId(ChatTestFixtures.PLAYER_SORA) .setCharacterName("Sora") @@ -676,14 +674,14 @@ private long prepareGameInstance() { STACK.freshGameplayBaseline( TENANT_ID, DEMO_WORLD_INSTANCE_ID, - ACCOUNT_ID, + MANAGEMENT_OWNER_SELECTOR, 7L, - ACCOUNT_ID, - Long.parseLong(ChatTestFixtures.PLAYER_SORA), - Long.parseLong(ChatTestFixtures.PLAYER_NYX)); + EMBERLINE_CHARACTER_ID, + SORA_CHARACTER_ID, + NYX_CHARACTER_ID); entityStub().resetCharacterRosterState(); - STACK.accountStub().mapAccountId(SORA_EMAIL, Long.parseLong(ChatTestFixtures.PLAYER_SORA)); - STACK.accountStub().mapAccountId(NYX_EMAIL, Long.parseLong(ChatTestFixtures.PLAYER_NYX)); + STACK.accountStub().mapAccountUuid(SORA_EMAIL, SORA_ACCOUNT_UUID); + STACK.accountStub().mapAccountUuid(NYX_EMAIL, NYX_ACCOUNT_UUID); return sessionId; } @@ -703,7 +701,7 @@ private void seedLiveTargetSession() { TENANT_ID, ChatTestFixtures.characterByName("Sora").getAccountId(), "sora@example.com", - Long.parseLong(ChatTestFixtures.PLAYER_SORA), + SORA_CHARACTER_ID, "Sora", DEMO_WORLD_INSTANCE_ID, ChatTestFixtures.ROOM_ID, diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java index 9d1b543947..56b685062c 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.entitymanagement.v1.ActorConditionState; import net.firedevops.firemud.entitymanagement.v1.ActorResourceValue; import net.firedevops.firemud.entitymanagement.v1.QueryActorStateResponse; +import net.firedevops.firemud.gamesession.test.ChatTestFixtures; import net.firedevops.firemud.gamesession.test.LookTestFixtures; import net.firedevops.firemud.gamesession.testsupport.GameplayAsyncAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplayCrossServiceStack; @@ -28,7 +29,8 @@ class LookWebSocketCrossServiceTest { private static final Duration COMMAND_WAIT = Duration.ofSeconds(8); private static final long TENANT_ID = 1L; - private static final long ACCOUNT_ID = 7L; + private static final String ACCOUNT_UUID = ChatTestFixtures.ACCOUNT_UUID_EMBERLINE; + private static final long MANAGEMENT_OWNER_SELECTOR = 7L; private static final long CHARACTER_ID = 123L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; @@ -329,7 +331,7 @@ void websocketReconnectWithoutBufferedTranscriptStillGetsFreshLook() throws Exce private static synchronized void ensureTestServicesStarted() throws Exception { if (STACK == null) { - STACK = GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_ID).start(); + STACK = GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_UUID).start(); } } @@ -343,9 +345,10 @@ private long prepareAdditionalGameInstance() { private long insertGameInstance(boolean clearExisting) { if (clearExisting) { - return STACK.freshGameplayBaseline(TENANT_ID, 1L, ACCOUNT_ID, 7L, CHARACTER_ID); + return STACK.freshGameplayBaseline( + TENANT_ID, 1L, MANAGEMENT_OWNER_SELECTOR, 7L, CHARACTER_ID); } - return STACK.insertRunningGameInstance(TENANT_ID, ACCOUNT_ID, 7L, false); + return STACK.insertRunningGameInstance(TENANT_ID, MANAGEMENT_OWNER_SELECTOR, 7L, false); } private List runLookSequence(long sessionId) throws Exception { diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java index fece520e58..714459e851 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java @@ -13,6 +13,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.test.ChatTestFixtures; import net.firedevops.firemud.gamesession.test.LookTestFixtures; import net.firedevops.firemud.gamesession.test.stubs.SocialGroupsStubServer; import net.firedevops.firemud.gamesession.testsupport.GameplayAsyncAssertions; @@ -35,7 +36,7 @@ class MultiplayerLoadProofCrossServiceTest { private static final Duration FOLLOW_UP_PHASE_BUDGET = Duration.ofSeconds(15); private static final long TENANT_ID = 1L; private static final int CLIENT_COUNT = 10; - private static final long ACCOUNT_ID_BASE = 7000L; + private static final long CHARACTER_ID_BASE = 7000L; @Container static final PostgreSQLContainer POSTGRES = @@ -67,7 +68,8 @@ static synchronized void stopServices() { void tenConcurrentPlayersCanLoginPlayAndLookAgainstRealCrossServiceStack() throws Exception { ensureTestServicesStarted(); List players = - GameplayLoadScenarios.seedPlayers(STACK, TENANT_ID, 1L, ACCOUNT_ID_BASE, CLIENT_COUNT, 7L); + GameplayLoadScenarios.seedPlayers( + STACK, TENANT_ID, 1L, CHARACTER_ID_BASE, CLIENT_COUNT, 7L); URI uri = URI.create("ws://localhost:" + gameSession().port() + "/ws/game"); TimedResult> playerRuns = timed( @@ -117,8 +119,9 @@ void tenConcurrentPlayersCanLoginPlayAndLookAgainstRealCrossServiceStack() throw .hasValueSatisfying( context -> { assertThat(context.tenantId()).isEqualTo(TENANT_ID); + assertThat(context.accountId()).isEqualTo(player.accountUuid()); assertThat(context.gameInstanceId()).isEqualTo(1L); - assertThat(context.characterId()).isEqualTo(player.accountId()); + assertThat(context.characterId()).isEqualTo(player.characterId()); assertThat(context.roomInstanceId()).isEqualTo(LookTestFixtures.ROOM_ID); }); } @@ -134,7 +137,8 @@ void tenConcurrentPlayersCanLoginPlayAndLookAgainstRealCrossServiceStack() throw void tenConcurrentPlayersCanMoveNorthAfterConcurrentEntry() throws Exception { ensureTestServicesStarted(); List players = - GameplayLoadScenarios.seedPlayers(STACK, TENANT_ID, 1L, ACCOUNT_ID_BASE, CLIENT_COUNT, 7L); + GameplayLoadScenarios.seedPlayers( + STACK, TENANT_ID, 1L, CHARACTER_ID_BASE, CLIENT_COUNT, 7L); URI uri = URI.create("ws://localhost:" + gameSession().port() + "/ws/game"); TimedResult> readyPlayers = @@ -180,7 +184,8 @@ void tenConcurrentPlayersCanMoveNorthAfterConcurrentEntry() throws Exception { void tenConcurrentPlayersCanBroadcastSayAfterConcurrentEntry() throws Exception { ensureTestServicesStarted(); List players = - GameplayLoadScenarios.seedPlayers(STACK, TENANT_ID, 1L, ACCOUNT_ID_BASE, CLIENT_COUNT, 7L); + GameplayLoadScenarios.seedPlayers( + STACK, TENANT_ID, 1L, CHARACTER_ID_BASE, CLIENT_COUNT, 7L); URI uri = URI.create("ws://localhost:" + gameSession().port() + "/ws/game"); TimedResult> readyPlayers = @@ -236,7 +241,8 @@ void tenConcurrentPlayersCanBroadcastSayAfterConcurrentEntry() throws Exception private static synchronized void ensureTestServicesStarted() throws Exception { if (STACK == null) { STACK = - GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_ID_BASE) + GameplayCrossServiceStack.defaultDemoBuilder( + POSTGRES, REDIS, ChatTestFixtures.ACCOUNT_UUID_EMBERLINE) .withSocialEnabled(true) .start(); } @@ -309,11 +315,11 @@ private void runConcurrentSayBurst(List connectedPlayers) t } private String sayText(GameplayLoadScenarios.PlayerSeed player) { - return "multiplayer burst " + player.accountId(); + return "multiplayer burst " + player.characterId(); } private String expectedSayTranscript(GameplayLoadScenarios.PlayerSeed player) { - return "You say, \"Multiplayer burst " + player.accountId() + ".\""; + return "You say, \"Multiplayer burst " + player.characterId() + ".\""; } private List runConcurrently(List items, ConcurrentTask task) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java index 2272947932..7804fbbd36 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java @@ -11,6 +11,9 @@ public final class ChatTestFixtures { public static final String PLAYER_EMBERLINE = "7"; public static final String PLAYER_SORA = "8"; public static final String PLAYER_NYX = "9"; + public static final String ACCOUNT_UUID_EMBERLINE = "c91fb96e-5ad8-4e4e-a12d-2838640093b2"; + public static final String ACCOUNT_UUID_SORA = "5f7624ca-8aee-4d34-9cd8-3ba3a1815f30"; + public static final String ACCOUNT_UUID_NYX = "3a16e242-3467-4d98-906f-71d47b888b5e"; private ChatTestFixtures() {} @@ -57,7 +60,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_EMBERLINE) .setTenantId("1") - .setAccountId("c91fb96e-5ad8-4e4e-a12d-2838640093b2") + .setAccountId(ACCOUNT_UUID_EMBERLINE) .setName("Emberline") .build(); } @@ -65,7 +68,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_SORA) .setTenantId("1") - .setAccountId("5f7624ca-8aee-4d34-9cd8-3ba3a1815f30") + .setAccountId(ACCOUNT_UUID_SORA) .setName("Sora") .build(); } @@ -73,7 +76,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_NYX) .setTenantId("1") - .setAccountId("3a16e242-3467-4d98-906f-71d47b888b5e") + .setAccountId(ACCOUNT_UUID_NYX) .setName("Nyx") .build(); } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java index a845624349..1f23362405 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java @@ -5,6 +5,9 @@ import io.grpc.stub.StreamObserver; import java.io.IOException; import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.entitymanagement.v1.ContainerItem; import net.firedevops.firemud.entitymanagement.v1.DropItemToRoomRequest; @@ -63,6 +66,8 @@ public final class EntityManagementStubServer implements AutoCloseable { new AtomicReference<>(LookTestFixtures.sampleEntities()); private final AtomicReference lastListCharactersByAccountRequest = new AtomicReference<>(); + private final ConcurrentMap + syntheticCharactersByAccountUuid = new ConcurrentHashMap<>(); private final AtomicReference actorState = new AtomicReference<>(QueryActorStateResponse.getDefaultInstance()); private boolean torchOnGround = true; @@ -253,37 +258,52 @@ public void resetCharacterRosterState() { lastListCharactersByAccountRequest.set(null); } + public void registerCharacterForAccountUuid( + String accountUuid, net.firedevops.firemud.entitymanagement.v1.Character character) { + String canonicalAccountUuid = requireCanonicalAccountUuid(accountUuid); + if (character == null + || !canonicalAccountUuid.equals(character.getAccountId()) + || character.getId().isBlank()) { + throw new IllegalArgumentException("synthetic character must be bound to its Account UUID"); + } + syntheticCharactersByAccountUuid.put(canonicalAccountUuid, character.toBuilder().build()); + } + + public void resetSyntheticAccountCharacters() { + syntheticCharactersByAccountUuid.clear(); + } + public Optional lastListCharactersByAccountRequest() { return Optional.ofNullable(lastListCharactersByAccountRequest.get()); } private net.firedevops.firemud.entitymanagement.v1.Character characterForAccount( - String accountId) { + String accountUuid) { net.firedevops.firemud.entitymanagement.v1.Character fixedCharacter = - switch (accountId) { - case "7" -> ChatTestFixtures.characterByName("Emberline"); - case "8" -> ChatTestFixtures.characterByName("Sora"); - case "9" -> ChatTestFixtures.characterByName("Nyx"); + switch (accountUuid) { + case ChatTestFixtures.ACCOUNT_UUID_EMBERLINE -> + ChatTestFixtures.characterByName("Emberline"); + case ChatTestFixtures.ACCOUNT_UUID_SORA -> ChatTestFixtures.characterByName("Sora"); + case ChatTestFixtures.ACCOUNT_UUID_NYX -> ChatTestFixtures.characterByName("Nyx"); default -> null; }; if (fixedCharacter != null) { return fixedCharacter; } + return syntheticCharactersByAccountUuid.get(requireCanonicalAccountUuid(accountUuid)); + } + + private static String requireCanonicalAccountUuid(String accountUuid) { try { - long numericAccountId = Long.parseLong(accountId); - if (numericAccountId >= 7_001L && numericAccountId <= 7_010L) { - long playerNumber = numericAccountId - 7_000L; - return net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId(Long.toString(numericAccountId)) - .setTenantId("1") - .setAccountId(Long.toString(numericAccountId)) - .setName("player-" + playerNumber) - .build(); + UUID parsed = UUID.fromString(accountUuid); + if ((parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) + || !parsed.toString().equals(accountUuid)) { + throw new IllegalArgumentException("Account UUID must be canonical and non-nil"); } - } catch (NumberFormatException ignored) { - // Non-numeric account identities are not persisted actors in this fixture. + return accountUuid; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Account UUID must be canonical and non-nil", exception); } - return null; } public synchronized void resetItemState() { diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 10bc30f717..297effcac9 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -41,7 +41,7 @@ public final class GameplayCrossServiceStack implements AutoCloseable { private final net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesResponse baselineRoomEntities; private final ListFriendPresenceResponse baselineFriendPresenceResponse; - private final Map syntheticManagementOwnerUuids = new HashMap<>(); + private final Map syntheticManagementOwnerUuidsBySelector = new HashMap<>(); private CrossServiceAppHarness.GameLogicHolder gameLogic; private final CrossServiceAppHarness.GameSessionHolder gameSession; @@ -71,7 +71,7 @@ public static Builder builder() { } public static Builder defaultDemoBuilder( - PostgreSQLContainer postgres, GenericContainer redis, long defaultAccountId) { + PostgreSQLContainer postgres, GenericContainer redis, String defaultAccountUuid) { return builder() .withPostgres( postgres.getHost(), @@ -80,7 +80,7 @@ public static Builder defaultDemoBuilder( postgres.getUsername(), postgres.getPassword()) .withRedis(redis.getHost(), redis.getMappedPort(6379)) - .withDefaultAccountId(defaultAccountId); + .withDefaultAccountUuid(defaultAccountUuid); } @SuppressFBWarnings( @@ -160,6 +160,7 @@ public void resetScenarioState() { socialStub.setFriendPresenceResponse(baselineFriendPresenceResponse); } } + entityStub.resetSyntheticAccountCharacters(); } public void clearScreenBuffers(long tenantId, long gameInstanceId, long... characterIds) { @@ -172,7 +173,7 @@ public void clearScreenBuffers(long tenantId, long gameInstanceId, long... chara public long freshGameplayBaseline( long tenantId, long gameplayInstanceId, - long ownerAccountId, + long managementOwnerSelector, long gameTemplateId, long... characterIds) { resetScenarioState(); @@ -282,7 +283,7 @@ public void seedLiveSession( } public long insertRunningGameInstance( - long tenantId, long accountId, long gameTemplateId, boolean clearExisting) { + long tenantId, long managementOwnerSelector, long gameTemplateId, boolean clearExisting) { JdbcTemplate jdbc = jdbc(); if (clearExisting) { clearRedis(); @@ -293,8 +294,8 @@ public long insertRunningGameInstance( GameInstanceTestFixtures.insertRunningGameInstance( jdbc, tenantId, - syntheticManagementOwnerUuids.computeIfAbsent( - accountId, ignored -> UUID.randomUUID().toString()), + syntheticManagementOwnerUuidsBySelector.computeIfAbsent( + managementOwnerSelector, ignored -> UUID.randomUUID().toString()), gameTemplateId); seedRuntimeOwnership(tenantId, gameInstanceId); return gameInstanceId; @@ -348,12 +349,12 @@ public static final class Builder { private String postgresPassword; private String redisHost; private int redisPort; - private long defaultAccountId = 7L; + private String defaultAccountUuid = "a7e0feac-60ab-4fd1-9002-0ad38d585db0"; private String defaultRoomId = LookTestFixtures.ROOM_ID; private net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesResponse initialRoomEntities; private ListFriendPresenceResponse initialFriendPresenceResponse; private boolean includeSocial; - private final Map accountMappings = new LinkedHashMap<>(); + private final Map accountUuidMappings = new LinkedHashMap<>(); private final Map gameLogicProps = new LinkedHashMap<>(); private final Map gameSessionProps = new LinkedHashMap<>(); private Class[] gameLogicConfigs = new Class[0]; @@ -377,13 +378,13 @@ public Builder withRedis(String host, int port) { return this; } - public Builder withDefaultAccountId(long accountId) { - this.defaultAccountId = accountId; + public Builder withDefaultAccountUuid(String accountUuid) { + this.defaultAccountUuid = accountUuid; return this; } - public Builder mapAccountId(String email, long accountId) { - this.accountMappings.put(email, accountId); + public Builder mapAccountUuid(String email, String accountUuid) { + this.accountUuidMappings.put(email, accountUuid); return this; } @@ -431,8 +432,8 @@ public Builder withGameSessionConfigs(Class... configs) { public GameplayCrossServiceStack start() throws IOException { requireConfigured(); AccountRuntimeStubServer accountStub = new AccountRuntimeStubServer(0); - accountStub.setDefaultAccountId(defaultAccountId); - accountMappings.forEach(accountStub::mapAccountId); + accountStub.setDefaultAccountUuid(defaultAccountUuid); + accountUuidMappings.forEach(accountStub::mapAccountUuid); GameDesignStubServer gameDesignStub = new GameDesignStubServer(0); WorldManagementStubServer worldStub = new WorldManagementStubServer(0); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java index 1217c2c65f..9d0246191c 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.UUID; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; @@ -19,35 +20,37 @@ public static List seedPlayers( GameplayCrossServiceStack stack, long tenantId, long gameplayInstanceId, - long firstAccountId, + long firstCharacterId, int count, long gameTemplateId) { long[] characterIds = new long[count]; for (int i = 0; i < count; i++) { - characterIds[i] = firstAccountId + i + 1; + characterIds[i] = firstCharacterId + i + 1; } stack.freshGameplayBaseline( - tenantId, gameplayInstanceId, firstAccountId, gameTemplateId, characterIds); + tenantId, gameplayInstanceId, firstCharacterId, gameTemplateId, characterIds); // Cross-service test bootstraps reserve runtime target 2 for the built-in sandbox pointer. // Skip that id so demo-player bootstrap instances do not inherit unrelated sandbox authority. - stack.insertRunningGameInstance(tenantId, firstAccountId, gameTemplateId, false); + stack.insertRunningGameInstance(tenantId, firstCharacterId, gameTemplateId, false); List players = new ArrayList<>(); for (int i = 0; i < count; i++) { - long accountId = characterIds[i]; + long characterId = characterIds[i]; + String accountUuid = UUID.randomUUID().toString(); long bootstrapGameInstanceId = - stack.insertRunningGameInstance(tenantId, accountId, gameTemplateId, false); + stack.insertRunningGameInstance(tenantId, characterId, gameTemplateId, false); // Admission pointers are uniquely identified by world/realm and runtime target. Give each // isolated player target its own world and retain the persisted pointer version for the // matching WebSocket bootstrap headers. - String bootstrapWorldSlug = GameplayCrossServiceStack.SYNTHETIC_LOAD_WORLD_PREFIX + accountId; + String bootstrapWorldSlug = + GameplayCrossServiceStack.SYNTHETIC_LOAD_WORLD_PREFIX + characterId; GameplayAdmissionPointerSnapshot pointer = stack .gameSessionBean(GameplayAdmissionPointerAuthorityService.class) .upsertPointer( new GameplayAdmissionPointerMutation( bootstrapWorldSlug, - "Demo Player " + accountId, + "Demo Player " + characterId, DEFAULT_REALM_SLUG, "Live Realm", tenantId, @@ -59,17 +62,28 @@ public static List seedPlayers( "ALLOW_NEW", GameplayCrossServiceStack.SYNTHETIC_LOAD_ACTOR, "Seed per-player load-test admission pointer", - "load-test:" + accountId, + "load-test:" + characterId, null, null)); - long sessionId = firstAccountId + 10_000L + i + 1; + long sessionId = firstCharacterId + 10_000L + i + 1; String email = "player" + (i + 1) + "@example.com"; - stack.accountStub().mapAccountId(email, accountId); + stack.accountStub().mapAccountUuid(email, accountUuid); + stack + .entityStub() + .registerCharacterForAccountUuid( + accountUuid, + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId(Long.toString(characterId)) + .setTenantId(Long.toString(tenantId)) + .setAccountId(accountUuid) + .setName("player-" + (i + 1)) + .build()); players.add( new PlayerSeed( sessionId, bootstrapGameInstanceId, - accountId, + characterId, + accountUuid, email, "player-" + (i + 1), bootstrapWorldSlug, @@ -104,7 +118,8 @@ public static GameplayWebSocketDriver openReadyPlayer( public record PlayerSeed( long sessionId, long bootstrapGameInstanceId, - long accountId, + long characterId, + String accountUuid, String username, String label, String bootstrapWorldSlug, diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index 89a4b8bf40..2d17c87a93 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -66,11 +66,15 @@ class TelnetGatewayGameSessionAccountCrossServiceIntegrationTest { private static final String CROSS_SERVICE_TEST_JWT_SECRET = "stub-secret-key-for-tests-1234567890"; private static final long TENANT_ID = 1L; - private static final long ACCOUNT_ID = 7L; + private static final String ACCOUNT_UUID = ChatTestFixtures.ACCOUNT_UUID_EMBERLINE; + private static final long MANAGEMENT_OWNER_SELECTOR = 7L; + private static final long EMBERLINE_CHARACTER_ID = + Long.parseLong(ChatTestFixtures.PLAYER_EMBERLINE); private static final String SORA_EMAIL = "sora@example.com"; - private static final long SORA_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_SORA); + private static final String SORA_ACCOUNT_UUID = ChatTestFixtures.ACCOUNT_UUID_SORA; + private static final long SORA_CHARACTER_ID = Long.parseLong(ChatTestFixtures.PLAYER_SORA); private static final String NYX_EMAIL = "nyx@example.com"; - private static final long NYX_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_NYX); + private static final String NYX_ACCOUNT_UUID = ChatTestFixtures.ACCOUNT_UUID_NYX; private static final long DEMO_WORLD_INSTANCE_ID = 1L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; @@ -127,7 +131,8 @@ static synchronized void stopTestServices() { @BeforeEach void clearSharedRuntimeState() throws Exception { ensureTestServicesStarted(); - STACK.freshGameplayBaseline(TENANT_ID, DEFAULT_GAME_INSTANCE_ID, ACCOUNT_ID, 7L, ACCOUNT_ID); + STACK.freshGameplayBaseline( + TENANT_ID, DEFAULT_GAME_INSTANCE_ID, MANAGEMENT_OWNER_SELECTOR, 7L, EMBERLINE_CHARACTER_ID); } @Test @@ -519,7 +524,7 @@ void telnetReconnectAfterStaleSessionFreshEntersGameplay() throws Exception { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); long activeGameplaySessionId = sessionContextService - .findByGameplayIdentity(TENANT_ID, DEMO_WORLD_INSTANCE_ID, ACCOUNT_ID) + .findByGameplayIdentity(TENANT_ID, DEMO_WORLD_INSTANCE_ID, EMBERLINE_CHARACTER_ID) .orElseThrow(() -> new IllegalStateException("Expected active gameplay binding")) .sessionId(); sessionContextService.deleteBySessionId(TENANT_ID, activeGameplaySessionId); @@ -722,9 +727,9 @@ private static synchronized void ensureTestServicesStarted() { GatewayHolder gateway = null; try { stack = - GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_ID) - .mapAccountId(SORA_EMAIL, SORA_ACCOUNT_ID) - .mapAccountId(NYX_EMAIL, NYX_ACCOUNT_ID) + GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_UUID) + .mapAccountUuid(SORA_EMAIL, SORA_ACCOUNT_UUID) + .mapAccountUuid(NYX_EMAIL, NYX_ACCOUNT_UUID) .withSocialEnabled(true) .withGameLogicProps( Map.of( @@ -745,7 +750,8 @@ private static synchronized void ensureTestServicesStarted() { GatewayBackedGameSessionTestOverrides.class, NestedReadinessOverrides.class) .start(); long defaultGameInstanceId = - stack.freshGameplayBaseline(TENANT_ID, 1L, ACCOUNT_ID, 7L, ACCOUNT_ID); + stack.freshGameplayBaseline( + TENANT_ID, 1L, MANAGEMENT_OWNER_SELECTOR, 7L, EMBERLINE_CHARACTER_ID); awaitGameSessionReadiness(stack.gameSessionPort()); gateway = startGateway(stack.gameSessionPort()); @@ -793,9 +799,9 @@ private void seedLiveTargetSession() { STACK.seedLiveSession( 90210L, TENANT_ID, - Long.parseLong(ChatTestFixtures.PLAYER_SORA), + SORA_ACCOUNT_UUID, "sora@example.com", - Long.parseLong(ChatTestFixtures.PLAYER_SORA), + SORA_CHARACTER_ID, "Sora", DEMO_WORLD_INSTANCE_ID, LookTestFixtures.ROOM_ID, From 9c6a360660144b62b160a0f737aa055ffaf81739 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 11:49:32 +1300 Subject: [PATCH 08/11] Preserve unreadable retained gameplay identity carriers --- .../player-access-and-session.md | 4 + .../FirstPartyConnectContextResolution.java | 11 ++- .../impl/RedisGameplayPresenceService.java | 30 +++++- .../command/text/LoginCommandHandlerTest.java | 47 ++++++++++ .../command/text/PlayCommandHandlerTest.java | 61 ++++++++++++ .../RedisGameplayPresenceServiceTest.java | 93 +++++++++++++++++++ 6 files changed, 239 insertions(+), 7 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 85bf514186..9a1baf7286 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,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +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. + +### Earlier Checkpoint Evidence + The unpublished Game Session Account-UUID carrier now incorporates #2929's reconciled grant-containment checkpoint `67dd8be6b3ef9d886e4b1dd26ec719cf9e29e4b3` through normal ancestry. Its corrected fake Account and Entity services preserve explicit Account UUIDs; synthetic load actors use registered UUID-to-character associations, not numeric Account aliases. FRIENDS direct selectors are UUIDs while roster ordinals and character/session/tenant selectors stay distinct. Negative fixture tests reject numeric, noncanonical, nil and null Account selectors without changing valid profile readback. The unique scope is115files and remains unpublished pending cap treatment. The earlier corrected-fixture shared-support/Game Session/TCP checks and both affected JARs passed189tasks(64executed/125up-to-date). Shared44unit and TCP194unit/7integration/3cross-service cases executed cleanly; Game Session18non-PostgreSQL integration and1cross-service executed cleanly, while its1,773unit results were up-to-date from the preceding same-code run. Game Session skipped17unit/135integration/33cross-service cases; TCP skipped14cross-service cases without Docker. No skipped case proves positive cross-service admission. The existing synthetic numeric tenant fixture is not owner provenance or a complete authenticated snapshot. Production Game Logic/Social numeric sender authority/storage and Entity's numeric actor-owner lookup are separate remaining consumer/data boundaries, not fixed by these fixtures. Runtime activation and section completion remain denied. Final composed Account/Game Session/TCP/shared-support checks, all three service JARs and docs passed218tasks(27executed/4from-cache/187up-to-date). Account517unit cases newly executed cleanly, while all161Account PostgreSQL cases skipped and other modules' test tasks were up-to-date. Stable patch ID `3c1e7ccb70b1f8256a70044afbcb90e2a7acd885` is unchanged for the entire unique services/protos patch across the parent merge; only the seven incoming correction paths change from the preceding carrier. Earlier merge/proof reports below are historical checkpoints. The local gameplay Account-UUID carrier now normally incorporates corrected published #2929 `96fb1b803d4dd1c6a3cc8f39bda91ae537e25bb6`, including the username-bound and typed JDBC UUID fixture corrections. Composed Account/Game Session/shared-support checks, both JARs and documentation passed163tasks(18executed/145up-to-date). The preceding same-code Game Session executions remain1,773unit,18non-PostgreSQL integration and1cross-service without failures/errors; final test tasks were up-to-date rather than new executions. Account PostgreSQL and Game Session PostgreSQL/cross-service skips remain explicit. The exact corrected parent runner proof is pending. The child remains108unique files and unpublished; neither reconciliation nor cached/up-to-date results establish runtime activation or section completion. The following earlier parent merges and proof reports are chronological history. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java index b3be62a86b..56889d3476 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java @@ -2,6 +2,7 @@ import java.util.Objects; import java.util.Optional; +import org.springframework.data.redis.serializer.SerializationException; public record FirstPartyConnectContextResolution( Optional connectContext, boolean invalid) { @@ -16,8 +17,14 @@ public static FirstPartyConnectContextResolution resolve( FirstPartyConnectContextRegistry firstPartyConnectContextRegistry) { Objects.requireNonNull( firstPartyConnectContextRegistry, "firstPartyConnectContextRegistry must not be null"); - Optional registryContext = - firstPartyConnectContextRegistry.find(sessionId); + Optional registryContext; + try { + registryContext = firstPartyConnectContextRegistry.find(sessionId); + } catch (SerializationException | ClassCastException ex) { + // A retained value using the old numeric Account carrier is not an absent registry entry: + // treating it as absent would permit fallback to persisted session context. + return new FirstPartyConnectContextResolution(Optional.empty(), true); + } if (registryContext.isPresent()) { FirstPartyConnectContext connectContext = registryContext.orElseThrow(); return new FirstPartyConnectContextResolution( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java index b336d298f6..7a65ecc48d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java @@ -25,6 +25,7 @@ import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.serializer.SerializationException; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @@ -112,7 +113,7 @@ public void registerConnected(SessionContext context) { @Override public void removeBySessionId(long sessionId) { - GameplayPresence existing = readPresence(presenceKey(sessionId)); + GameplayPresence existing = readPresenceForMutation(presenceKey(sessionId)); redisTemplate.delete(presenceKey(sessionId)); if (existing != null) { String gameInstanceKey = gameInstanceKey(existing.tenantId(), existing.gameInstanceId()); @@ -203,7 +204,13 @@ public List listConnectedByGameInstance(long tenantId, long ga setOps.remove(gameInstanceKey, sessionIdText); continue; } - GameplayPresence presence = readPresence(presenceKey); + GameplayPresence presence; + try { + presence = readPresenceForMutation(presenceKey); + } catch (SerializationException | ClassCastException ex) { + // Keep the index member until its retained presence value can be read safely. + continue; + } if (presence == null) { setOps.remove(gameInstanceKey, sessionIdText); continue; @@ -247,7 +254,13 @@ public Map> listConnectedByAccountIds( setOps.remove(accountKey, sessionIdText); continue; } - GameplayPresence presence = readPresence(presenceKey); + GameplayPresence presence; + try { + presence = readPresenceForMutation(presenceKey); + } catch (SerializationException | ClassCastException ex) { + // Keep the index member until its retained presence value can be read safely. + continue; + } if (presence == null) { setOps.remove(accountKey, sessionIdText); continue; @@ -275,14 +288,21 @@ private GameplayPresence readPresence(String key) { ValueOperations valueOps = redisTemplate.opsForValue(); try { return (GameplayPresence) valueOps.get(key); - } catch (org.springframework.data.redis.serializer.SerializationException - | ClassCastException ex) { + } catch (SerializationException | ClassCastException ex) { // An older numeric Account carrier cannot be mapped to a UUID. Fail closed without // mutating the retained record; the session must authenticate through its context path. return null; } } + private GameplayPresence readPresenceForMutation(String key) { + ValueOperations valueOps = redisTemplate.opsForValue(); + // Unlike read-only lookups, mutation cleanup must distinguish absence from a retained value + // that cannot be decoded under the current Account carrier. Propagate these decode failures + // so callers do not delete or overwrite the record or its indexes. + return (GameplayPresence) valueOps.get(key); + } + private String presenceKey(long sessionId) { return String.format(PRESENCE_KEY_TEMPLATE, sessionId); } 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 6fa20bdcab..363428efd6 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 @@ -42,9 +42,12 @@ import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mockito; +import org.springframework.data.redis.serializer.SerializationException; @SuppressWarnings("unchecked") class LoginCommandHandlerTest { @@ -707,6 +710,50 @@ void bareLoginRejectsIncompletePersistedFirstPartyContextWhenRegistryEntryIsMiss joinedOutputText(result.outputs())); } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void bareLoginRejectsUnreadableRegistryContextWithoutPersistedFallback( + boolean serializationFailure) { + TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + SessionContext persisted = + new SessionContext( + 1L, + 22L, + ACCOUNT_77, + null, + 0L, + null, + 0L, + null, + null, + "en-NZ", + 1L, + "demo", + "production", + 1L, + null, + "persisted-scope", + "persisted-request"); + stubSessionContext(persisted); + RuntimeException decodeFailure = + serializationFailure + ? new SerializationException("legacy numeric Account carrier") + : new ClassCastException("legacy numeric Account carrier"); + when(firstPartyConnectContextRegistry.find(1L)).thenThrow(decodeFailure); + + LoginCommandHandlingResult result = handler.handle("1", command, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + assertEquals( + "ERROR CONNECT_CONTEXT_INVALID Connect context invalid", + joinedOutputText(result.outputs())); + verify(accountClient, never()).authenticate(anyString(), anyString()); + verify(accountClient, never()).requestEmailLoginOtp(anyString()); + verify(gameInstanceRepository, never()).findById(anyLong()); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + } + @Test void bareLoginDoesNotFallBackToRawPersistedFirstPartyContextWhenTenantScopedSessionIsMissing() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); 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 db96044ef0..4b83c987f4 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 @@ -48,6 +48,7 @@ import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; +import org.springframework.data.redis.serializer.SerializationException; class PlayCommandHandlerTest { private static final String PLAY_COMMAND_NAME = "PLAY"; @@ -958,6 +959,66 @@ void firstPartyPlayRejectsConnectContextMissingRealmSlug() { .isEqualTo("ERROR CONNECT_CONTEXT_INVALID Connect context invalid"); } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void firstPartyPlayRejectsUnreadableRegistryContextWithoutPersistedFallback( + boolean serializationFailure) { + SessionContext persisted = + new SessionContext( + 1L, + 22L, + PLAYER_ACCOUNT_ID, + null, + 0L, + null, + 0L, + null, + null, + "en-NZ", + 1L, + "demo", + "production", + 1L, + null, + "persisted-scope", + "persisted-request"); + when(sessionAuthenticationService.resolveSessionContext("1")) + .thenReturn(Optional.of(persisted)); + RuntimeException decodeFailure = + serializationFailure + ? new SerializationException("legacy numeric Account carrier") + : new ClassCastException("legacy numeric Account carrier"); + when(firstPartyConnectContextRegistry.find(1L)).thenThrow(decodeFailure); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_CONTEXT_INVALID"); + assertThat(joinedOutputText(result.outputs())) + .isEqualTo("ERROR CONNECT_CONTEXT_INVALID Connect context invalid"); + Mockito.verify(accountClient, Mockito.never()).getTenantMembershipForRuntime(Mockito.any()); + Mockito.verify(accountClient, Mockito.never()) + .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verify(entityManagementClient, Mockito.never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + Mockito.verify(sessionContextService, Mockito.never()).save(Mockito.any()); + Mockito.verify(gameplayPresenceLifecycleService, Mockito.never()) + .registerConnected(Mockito.any()); + Mockito.verify(scriptEventPublisher, Mockito.never()) + .publishCommandEvent(Mockito.any(), Mockito.any(GameplayCommand.class)); + } + @Test void firstPartyPlayRejectsConnectContextMissingConnectScope() { SessionContext context = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java index ce55c1dc96..db320bfed9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java @@ -2,6 +2,7 @@ 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.ArgumentMatchers.argThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -16,6 +17,8 @@ import net.firedevops.firemud.gamesession.service.SessionContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; @@ -154,6 +157,35 @@ void listConnectedByGameInstancePrunesMalformedSessionIndexEntry() { verify(setOperations).remove("gameplaypresence:22:7:sessions", "not-a-session"); } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void listConnectedByGameInstancePreservesIndexForUnreadablePresence( + boolean serializationFailure) { + String indexKey = "gameplaypresence:22:7:sessions"; + when(setOperations.members(indexKey)).thenReturn(new LinkedHashSet<>(List.of("5"))); + when(valueOperations.get("gameplaypresence:session:5")) + .thenThrow(unreadablePresenceFailure(serializationFailure)); + + var result = service.listConnectedByGameInstance(22L, 7L); + + assertEquals(List.of(), result); + verify(setOperations, Mockito.never()).remove(indexKey, "5"); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void listConnectedByAccountIdsPreservesIndexForUnreadablePresence(boolean serializationFailure) { + String indexKey = "gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions"; + when(setOperations.members(indexKey)).thenReturn(new LinkedHashSet<>(List.of("5"))); + when(valueOperations.get("gameplaypresence:session:5")) + .thenThrow(unreadablePresenceFailure(serializationFailure)); + + var result = service.listConnectedByAccountIds(22L, List.of(ACCOUNT_PLAYER)); + + assertEquals(Map.of(), result); + verify(setOperations, Mockito.never()).remove(indexKey, "5"); + } + @Test void removeBySessionIdRemovesValueAndSetMembership() { when(valueOperations.get("gameplaypresence:session:3")) @@ -181,6 +213,52 @@ void removeBySessionIdRemovesValueAndSetMembership() { .remove("gameplaypresence:22:account:" + ACCOUNT_PLAYER + ":sessions", "3"); } + @Test + void removeBySessionIdPreservesUnreadableRetainedPresence() { + String key = "gameplaypresence:session:5"; + when(valueOperations.get(key)).thenThrow(new SerializationException("legacy record")); + + assertThrows(SerializationException.class, () -> service.removeBySessionId(5L)); + + verifyNoPresenceMutations(key); + } + + @Test + void removeBySessionIdPreservesWrongTypeRetainedPresence() { + String key = "gameplaypresence:session:5"; + when(valueOperations.get(key)).thenReturn(42L); + + assertThrows(ClassCastException.class, () -> service.removeBySessionId(5L)); + + verifyNoPresenceMutations(key); + } + + @Test + void registerConnectedDoesNotOverwriteUnreadableRetainedPresence() { + String key = "gameplaypresence:session:1"; + when(valueOperations.get(key)).thenThrow(new SerializationException("legacy record")); + SessionContext context = + new SessionContext( + 1L, 22L, ACCOUNT_PLAYER, "player@example.com", 202L, "Ben", 7L, "R-1", null); + + assertThrows(SerializationException.class, () -> service.registerConnected(context)); + + verifyNoPresenceMutations(key); + } + + @Test + void registerConnectedDoesNotOverwriteWrongTypeRetainedPresence() { + String key = "gameplaypresence:session:1"; + when(valueOperations.get(key)).thenReturn(42L); + SessionContext context = + new SessionContext( + 1L, 22L, ACCOUNT_PLAYER, "player@example.com", 202L, "Ben", 7L, "R-1", null); + + assertThrows(ClassCastException.class, () -> service.registerConnected(context)); + + verifyNoPresenceMutations(key); + } + @Test void findConnectedBySessionIdReadsPresenceRecordDirectly() { when(valueOperations.get("gameplaypresence:session:4")) @@ -217,6 +295,21 @@ void unreadableLegacyPresenceFailsClosedWithoutDeletingRetainedValue() { Mockito.verify(redisTemplate, Mockito.never()).delete(key); } + private void verifyNoPresenceMutations(String presenceKey) { + verify(redisTemplate, Mockito.never()).delete(presenceKey); + verify(redisTemplate, Mockito.never()).expire(Mockito.anyString(), Mockito.any(Duration.class)); + verify(valueOperations, Mockito.never()) + .set(Mockito.anyString(), Mockito.any(), Mockito.any(Duration.class)); + verify(setOperations, Mockito.never()).add(Mockito.anyString(), Mockito.any()); + verify(setOperations, Mockito.never()).remove(Mockito.anyString(), Mockito.any()); + } + + private static RuntimeException unreadablePresenceFailure(boolean serializationFailure) { + return serializationFailure + ? new SerializationException("legacy record") + : new ClassCastException("legacy record"); + } + @Test void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequested() { AtomicLong now = new AtomicLong(100L); From 5aca20ad5e8ae5809f8c23c44d8cf6e6da49c8de Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 19:08:05 +1300 Subject: [PATCH 09/11] docs: record approved Account UUID alignment boundary --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 cd7d39d145..b2e1365e14 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,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Current reconciliation of [#2932](https://github.com/benhook1013/FireMUD/pull/2932) normally incorporates [#2969](https://github.com/benhook1013/FireMUD/pull/2969) at exact head `783dd1ea6bcd3b76cae474a032f0a551066a00ee`. All 116 preserved carrier paths remain: 69 are byte-identical and the other 47 changed only where the incoming parent overlaps. Six necessary parent runtime or fixture adaptations bring the unique composed delta to 122 files; final publication and retargeting require that exact scope's Overseer disposition. The base/head hashes and runner evidence below remain historical source checkpoints, not proof for this composed state. +Current reconciliation of [#2932](https://github.com/benhook1013/FireMUD/pull/2932) normally incorporates [#2969](https://github.com/benhook1013/FireMUD/pull/2969) at exact head `783dd1ea6bcd3b76cae474a032f0a551066a00ee`. All 116 preserved carrier paths remain: 69 are byte-identical and the other 47 changed only where the incoming parent overlaps. Six necessary parent runtime or fixture adaptations bring the unique composed delta to 122 files; Overseer approved this exact alignment-only scope, without waiving provider limits or authorizing new capability. The base/head hashes and runner evidence below remain historical source checkpoints, not proof for this composed state. The corrected composed Account, Game Session, TCP Proxy, Common Test Support and Common Security checks, three service JAR builds, formatting/static analysis and documentation passed in 1 minute 16 seconds (232 tasks: 28 executed, 204 up-to-date). Game Session newly executed 2,256 unit, 18 integration and one cross-service cases without failures or errors; 17 unit, 155 integration and 35 cross-service cases skipped. Account's 662 unit, Common Test Support's 51 unit, Common Security's 122 unit and TCP's 194 unit, seven integration and three cross-service clean results were up-to-date in this final invocation, not new executions. All 178 Account integration cases and 14 TCP cross-service cases skipped without native Docker. The reconciliation preserves current-pointer/lifecycle/JOIN/CAS/expiry checks and mutation-free unavailable `LOGOUT`; explicit UUID fixtures and complete LEFT evidence replace malformed legacy assertions, not the production guards. No skipped case, historical runner result or synthetic tenant fixture establishes current-head PostgreSQL, retained-Redis, fresh-image, authenticated cross-owner or enabled admission proof. Runtime paths and the Account ring mount remain denied or unpublished. From 9f038127e5ff830563b73de3f483b6df12ea864d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:24:00 +1300 Subject: [PATCH 10/11] Allow Validation for stacked pull requests --- .github/workflows/ci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8ffe77bb8f..7a90f08063 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: From ffe1300cc0e30a1479812f8f852a5bb4e638bb53 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:35:12 +1300 Subject: [PATCH 11/11] Carry forward reviewed CI safety corrections --- .github/workflows/ci.yml | 2 +- .../workflows/publish-pr-runtime-images.yml | 4 +- .github/workflows/security.yml | 3 +- .github/workflows/smoke.yml | 51 +++++++++++- .github/workflows/static-analysis-summary.yml | 3 +- .../preview/resolve-preview-image-tag.sh | 2 +- .../tests/ci-validation-summary-contract.sh | 12 +++ .../pr-required-gate-context-contract.sh | 83 +++++++++++++++++++ .../tests/pr-retarget-workflow-contract.sh | 79 +++++++++++++++++- .../pr-runtime-image-publication-contract.sh | 29 ++++++- dev-tools/tests/security-summary-contract.sh | 51 ++++++++++++ .../tests/static-analysis-summary-contract.sh | 11 ++- 12 files changed, 314 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7a90f08063..15afae6f35 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1255,7 +1255,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) {