From b07e20655d4a4a367866ede61d5d9e378f6df59f Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 14 Nov 2026 01:29:40 +1300 Subject: [PATCH 01/17] Consolidate Social report UUID receiver groundwork --- .../logging-admin-service/runtime-and-data.md | 2 +- .../platform-operations-and-delivery.md | 6 +- ...r-experience-commands-and-communication.md | 4 + .../loggingadmin/data/TestDataSeeder.java | 25 +- .../loggingadmin/dto/CreateReportRequest.java | 16 +- .../firemud/loggingadmin/dto/ReportDto.java | 5 +- .../loggingadmin/entity/PlayerReport.java | 5 +- .../repository/PlayerReportRepository.java | 3 +- .../migration/V1008__report_account_uuid.sql | 23 ++ ...tUuidMigrationPostgresIntegrationTest.java | 360 ++++++++++++++++++ .../loggingadmin/data/TestDataSeederTest.java | 13 +- .../dto/CreateReportRequestTest.java | 48 +++ .../service/impl/ReportServiceImplTest.java | 9 +- .../client/LoggingAdminClient.java | 2 + .../SocialInternalGrpcClientAuthTest.java | 24 ++ 15 files changed, 497 insertions(+), 48 deletions(-) create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V1008__report_account_uuid.sql create mode 100644 services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ReportAccountUuidMigrationPostgresIntegrationTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/dto/CreateReportRequestTest.java diff --git a/design/architecture/microservices/logging-admin-service/runtime-and-data.md b/design/architecture/microservices/logging-admin-service/runtime-and-data.md index bbf21fa335..f206622a4f 100644 --- a/design/architecture/microservices/logging-admin-service/runtime-and-data.md +++ b/design/architecture/microservices/logging-admin-service/runtime-and-data.md @@ -121,7 +121,7 @@ For plugin operations, Automation remains the activation/lifecycle owner and Gam - `moderation_actions` is the target durable record for accepted moderation policy intent and audit evidence, with the fixed category, normalized explicit scope, actor/case/source request, safe notice/reason, local intent-reference redemption outcome, separate owner command/result linkage when a later enforcement command exists, and the idempotency identity, digest, and timestamps. A linked owner-result revision is recorded only when that result supplies it; the local policy-intent commit never synthesizes owner revision or enforcement epoch. Raw authorization references are never persisted. The legacy `POST /moderation/actions` and `ApplyModerationAction` transport stubs now hard fail closed after narrow checks without persisting their generic legacy row; they are unsupported/nonconformant and not target fixed-category proof. Owner restriction tables and owner-command redemption are separate; Logging & Admin does not mutate them. - `moderation_actions.account_id` stores canonical non-nil Account UUID ownership at the target storage boundary. Receiver/storage preparation and retained-row disposition are tracked in [Platform Operations](../../../project-management/implementation-tracking/platform-operations-and-delivery.md#operator-write-boundary-status). - `moderation_appeal_cases` and bounded `moderation_appeal_evidence_refs` are target Logging & Admin records for the `SUBMITTED -> UNDER_REVIEW -> DECIDED` lifecycle, exact appealed owner revision/digest, jurisdiction, eligibility policy, safe submission/decision, bounded evidence references, retention/legal-hold/export state, and resulting owner command identity. No complete appeal table or workflow is currently implemented. -- `player_reports` is the target durable store for abuse and bug reports accepted through the report-persistence seam, including tenant scope in its `tenant_id` column. Current report persistence is unavailable: both the internal `CreateReport` ingress and the service-layer mutation fail closed before any repository save, and public administrative and target caller-bound external/player submission remain unavailable. +- `player_reports` is the target durable store for abuse and bug reports accepted through the report-persistence seam, including tenant scope in its `tenant_id` column. Reporter and optional target selectors are canonical non-nil Account UUIDs; tenant, private row and generic-log identifiers remain numeric. Legacy numeric report rows require explicit Account-owned identity disposition before storage convergence; no service-local inferred mapping or destructive cleanup is permitted. Current report persistence is unavailable: both the internal `CreateReport` ingress and the service-layer mutation fail closed before any repository save, and public administrative and target caller-bound external/player submission remain unavailable. - Runtime feature-flag truth is owned by Game Session. After the action-family schema, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus owner-side redemption gate passes, Logging & Admin records operator intent and audit context for feature-flag requests, then forwards the mutation to Game Session rather than maintaining a competing `feature_flag` runtime table. ## Moderation Workflow diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index 3ca382658e..da9d3a1d50 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -92,7 +92,9 @@ The StartSession prerequisite now includes the shared action/digest and pre-auth The tracker separates implemented fail-closed ingress stubs from supported durable operator workflows and the target external ingress contract. Game Session `/sessions*` routes remain internal/owner-local. Logging & Admin feature-flag and scoped tick ingress stubs remain externally unavailable because they do not currently forward and the complete [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) owner-write gate is not implemented or proved. Moderation and appeal implementation status remains owned by the [Logging & Admin moderation policies](../../architecture/microservices/logging-admin-service/moderation-policies.md) contract; quota overrides, broader remediation, external session-lifecycle forwarding, and other unproved owner mutations remain gated or target-only. -Ordinary moderation Account UUID storage and the matching PLAY policy receiver remain final receiving work in #2972. Its forward V1003 migration takes an access-exclusive lock and refuses any populated legacy moderation table before alteration; it supplies no inferred Account mapping, backfill or deletion. Retained data requires an explicit owner-backed disposition before that migration can proceed. Moderation mutations remain fail-closed; storage preparation is not fixed-category enforcement or production activation proof. The [Logging & Admin data model](../../architecture/microservices/logging-admin-service/runtime-and-data.md#data-model) owns the target representation. +Ordinary moderation Account UUID storage and the matching PLAY policy receiver landed through #2972. Its forward V1003 migration takes an access-exclusive lock and refuses any populated legacy moderation table before alteration; it supplies no inferred Account mapping, backfill or deletion. Retained data requires an explicit owner-backed disposition before that migration can proceed. Moderation mutations remain fail-closed; storage preparation is not fixed-category enforcement or production activation proof. The [Logging & Admin data model](../../architecture/microservices/logging-admin-service/runtime-and-data.md#data-model) owns the target representation. + +Report receiving now uses canonical Account UUID request validation and UUID report DTO/entity/repository fields. New forward V1008 converts only empty report storage after an access-exclusive lock and refuses retained numeric rows without changing their values or earlier migration history. It does not rewrite V1003 or infer Account mappings. Synthetic report seeding is removed; generic log identifiers remain numeric. ReportAccountUuidMigrationPostgresIntegrationTest covers fresh and V1007 upgrades, unaffected moderation data, retained-report refusal and concurrent-writer refusal. Execution proof is still required before readiness; this source preparation neither enables report mutation nor retires #2976 or changes #2933 dependencies. ## Canonical Design Sources @@ -132,7 +134,7 @@ The authoritative external-monitoring ownership and target-state detail remain i ### Canonical Demo and Runtime Seed State -Smoke and hosted preview seeders reassert canonical state by stable business identity instead of relying on empty tables. Preview/dev-demo bootstrap uses the canonical Account bootstrap flow and the same demo runtime-seeding contract as local Compose. Account reasserts the demo account and membership; Game Design reasserts the published game/template/version/revision/release-bundle/asset-artifact proof rows; Game Session reasserts manifest, feature-flag, and running-instance rows; Logging & Admin reasserts smoke-facing log/report/moderation rows; and World Management reasserts authored starter topology by natural demo identity before layering runtime topology on it. +Smoke and hosted preview seeders reassert canonical state by stable business identity instead of relying on empty tables. Preview/dev-demo bootstrap uses the canonical Account bootstrap flow and the same demo runtime-seeding contract as local Compose. Account reasserts the demo account and membership; Game Design reasserts the published game/template/version/revision/release-bundle/asset-artifact proof rows; Game Session reasserts manifest, feature-flag, and running-instance rows; Logging & Admin reasserts smoke-facing generic log rows; report/moderation examples require Account-owned canonical identity and are not fabricated; and World Management reasserts authored starter topology by natural demo identity before layering runtime topology on it. World Management runtime-target seeding is isolated behind `SmokeDemoRuntimeSeedProperties` and consumes explicit `{tenantId, gameInstanceId}` targets. It no longer imports `GameplayCatalogProperties` in main-code smoke seeding, declares canonical demo and sandbox targets explicitly, and honors the shared `FIREMUD_BOOTSTRAP_*` overrides. The fresh-bootstrap script invokes helper scripts explicitly so file-mode drift cannot break the repo-owned proof path. The seed boundary does not attempt to become a general fixture framework or seed authored content beyond the smoke/demo contract. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index 3e3b758ea7..26dfa0bb5e 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -133,3 +133,7 @@ Resolve the remaining design choices in the canonical [player command model](../ | First-party frontend | `web-client` presentation artifact and browser API/WebSocket consumer remain partial; independent artifact/host and browser proof remain incomplete | [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md) | The service boundaries above summarize current ownership and implementation status; they are non-normative. Canonical communication ownership and delivery contracts remain in [ADR 0147](../../architecture/decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md) and the owning architecture sources linked above. Game Session is the player-facing policy/rendering, runtime-presence, connected gameplay transport fanout, and player-projection owner; Game Logic is the gameplay/action and communication-resolution owner; Social Groups is the social policy/history/social-channel fanout and delivery-state owner; World Management is the authoritative room-content owner; Account is the profile-policy source; and Logging & Admin consumes canonical control-plane diagnostics. + +### Old-stack report receiver preparation + +The Social/Logging consolidation receiver carries the verified report UUID preparation from `433d706b` onto its current Account preparation parent, preserving the canonical forward V1008 migration and disabled report writes. Social rejects malformed, numeric, nil and noncanonical report Account identifiers before request or channel access, preserving the existing internal workload identity and downstream unavailable response. Receiving-head focused JVM proof passes 20 cases (14 Logging and six Social), with zero failures/errors. Logging integration-test compilation and affected Java formatting pass using explicit Mockito startup instrumentation. Physical migration execution and remote CI remain pending; this is not report activation or donor retirement. diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/data/TestDataSeeder.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/data/TestDataSeeder.java index 7c2f863e66..0b2a710e56 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/data/TestDataSeeder.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/data/TestDataSeeder.java @@ -4,9 +4,7 @@ import java.time.Instant; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.loggingadmin.entity.LogEvent; -import net.firedevops.firemud.loggingadmin.entity.PlayerReport; import net.firedevops.firemud.loggingadmin.repository.LogEventRepository; -import net.firedevops.firemud.loggingadmin.repository.PlayerReportRepository; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -25,18 +23,14 @@ justification = "Spring injects the shared repository singletons for demo seeding.") public class TestDataSeeder implements ApplicationRunner { private static final long DEMO_TENANT_ID = 1L; - private static final long DEMO_REPORTER_ACCOUNT_ID = 1L; - private static final long DEMO_TARGET_ACCOUNT_ID = 2L; private final LogEventRepository logEventRepository; - private final PlayerReportRepository playerReportRepository; @Override @Transactional public void run(ApplicationArguments args) { ensureStartupLogEvent(); - ensureSamplePlayerReport(); - // Moderation examples require an Account-owned canonical UUID association. + // Report and moderation examples require an Account-owned canonical UUID association. // The legacy numeric demo key is not evidence of that identity. } @@ -53,21 +47,4 @@ private void ensureStartupLogEvent() { } logEventRepository.save(event); } - - private void ensureSamplePlayerReport() { - PlayerReport report = - playerReportRepository - .findFirstByTenantIdAndReporterAccountIdAndTargetAccountIdAndType( - DEMO_TENANT_ID, DEMO_REPORTER_ACCOUNT_ID, DEMO_TARGET_ACCOUNT_ID, "bug") - .orElseGet(PlayerReport::new); - report.setTenantId(DEMO_TENANT_ID); - report.setReporterAccountId(DEMO_REPORTER_ACCOUNT_ID); - report.setTargetAccountId(DEMO_TARGET_ACCOUNT_ID); - report.setType("bug"); - report.setDescription("Sample report"); - if (report.getCreatedAt() == null) { - report.setCreatedAt(Instant.now()); - } - playerReportRepository.save(report); - } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateReportRequest.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateReportRequest.java index 0d31f1cfb2..809aac2486 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateReportRequest.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateReportRequest.java @@ -1,12 +1,22 @@ package net.firedevops.firemud.loggingadmin.dto; +import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; import jakarta.validation.constraints.Size; +import net.firedevops.firemud.common.security.JwtClaims; public record CreateReportRequest( @NotNull @Positive Long tenantId, - @NotNull @Positive Long reporterAccountId, - @Positive Long targetAccountId, + @NotNull @NotBlank String reporterAccountId, + String targetAccountId, @NotNull @Size(max = 20) String type, - @NotNull @Size(max = 255) String description) {} + @NotNull @Size(max = 255) String description) { + public CreateReportRequest { + reporterAccountId = + JwtClaims.requireCanonicalAccountUuid(reporterAccountId, "reporterAccountId"); + if (targetAccountId != null) { + targetAccountId = JwtClaims.requireCanonicalAccountUuid(targetAccountId, "targetAccountId"); + } + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ReportDto.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ReportDto.java index bb9348b6d2..966caff1cc 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ReportDto.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ReportDto.java @@ -3,12 +3,13 @@ import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; import java.time.Instant; +import java.util.UUID; public record ReportDto( Long id, @NotNull Long tenantId, - @NotNull Long reporterAccountId, - Long targetAccountId, + @NotNull UUID reporterAccountId, + UUID targetAccountId, @NotNull @Size(max = 20) String type, @NotNull @Size(max = 255) String description, @NotNull Instant createdAt) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/PlayerReport.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/PlayerReport.java index 23d940ead6..a38bd5c614 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/PlayerReport.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/PlayerReport.java @@ -1,15 +1,16 @@ package net.firedevops.firemud.loggingadmin.entity; import java.time.Instant; +import java.util.UUID; import lombok.Data; @Data public class PlayerReport { private Long id; private Long tenantId; - private Long reporterAccountId; + private UUID reporterAccountId; - private Long targetAccountId; + private UUID targetAccountId; private String type; private String description; private Instant createdAt; diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/PlayerReportRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/PlayerReportRepository.java index 3f91fa1cd3..7c02f937c3 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/PlayerReportRepository.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/PlayerReportRepository.java @@ -6,6 +6,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.loggingadmin.entity.PlayerReport; import net.firedevops.firemud.loggingadmin.jooq.tables.records.PlayerReportsRecord; import org.jooq.DSLContext; @@ -28,7 +29,7 @@ public long count() { } public Optional findFirstByTenantIdAndReporterAccountIdAndTargetAccountIdAndType( - Long tenantId, Long reporterAccountId, Long targetAccountId, String type) { + Long tenantId, UUID reporterAccountId, UUID targetAccountId, String type) { return dsl.selectFrom(PLAYER_REPORTS) .where( PLAYER_REPORTS diff --git a/services/logging-admin-service/src/main/resources/db/migration/V1008__report_account_uuid.sql b/services/logging-admin-service/src/main/resources/db/migration/V1008__report_account_uuid.sql new file mode 100644 index 0000000000..41864ae031 --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V1008__report_account_uuid.sql @@ -0,0 +1,23 @@ +-- Numeric report Account references have no service-local canonical UUID mapping. +-- Refuse retained rows; never infer identities, backfill, delete or rewrite history. +-- [jooq ignore start] +LOCK TABLE player_reports IN ACCESS EXCLUSIVE MODE -- [jooq ignore stop] +; +-- [jooq ignore start] +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM player_reports) THEN + RAISE EXCEPTION 'Cannot migrate populated legacy report Account references: Account-owned recovery is required'; + END IF; +END $$; +-- [jooq ignore stop] +ALTER TABLE player_reports ALTER COLUMN reporter_account_id TYPE UUID -- [jooq ignore start] +USING NULL::UUID -- [jooq ignore stop] +; +ALTER TABLE player_reports ALTER COLUMN target_account_id TYPE UUID -- [jooq ignore start] +USING NULL::UUID -- [jooq ignore stop] +; +ALTER TABLE player_reports ADD CONSTRAINT player_reports_reporter_account_id_non_nil + CHECK (reporter_account_id <> '00000000-0000-0000-0000-000000000000'::UUID); +ALTER TABLE player_reports ADD CONSTRAINT player_reports_target_account_id_non_nil + CHECK (target_account_id IS NULL OR target_account_id <> '00000000-0000-0000-0000-000000000000'::UUID); diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ReportAccountUuidMigrationPostgresIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ReportAccountUuidMigrationPostgresIntegrationTest.java new file mode 100644 index 0000000000..16d5ded0c8 --- /dev/null +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ReportAccountUuidMigrationPostgresIntegrationTest.java @@ -0,0 +1,360 @@ +package net.firedevops.firemud.loggingadmin; + +import static org.assertj.core.api.Assertions.assertThat; +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 java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.FlywayException; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class ReportAccountUuidMigrationPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = "classpath:db/migration"; + + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void freshSchemaMigratesWithCanonicalAccountUuidsAndNumericLocalIdentifiers() throws Exception { + String schema = createSchema(); + + migrateToLatest(schema); + + assertThat(columnType(schema, "moderation_actions", "account_id")).isEqualTo("uuid"); + assertThat(columnType(schema, "player_reports", "reporter_account_id")).isEqualTo("uuid"); + assertThat(columnType(schema, "player_reports", "target_account_id")).isEqualTo("uuid"); + assertThat(columnType(schema, "moderation_actions", "tenant_id")).isEqualTo("int8"); + assertThat(columnType(schema, "player_reports", "tenant_id")).isEqualTo("int8"); + assertThat(columnType(schema, "moderation_actions", "id")).isEqualTo("int8"); + assertThat(columnType(schema, "player_reports", "id")).isEqualTo("int8"); + assertThat(columnType(schema, "log_events", "account_id")).isEqualTo("int8"); + execute( + schema, + "INSERT INTO player_reports (tenant_id, reporter_account_id, target_account_id, type, description) VALUES (1, 'b8d093f7-cb70-40ed-9fac-3c82d4bf28f1', NULL, 'BUG', 'canonical')"); + assertThat( + scalarLong( + schema, + "SELECT count(*) FROM player_reports WHERE reporter_account_id = 'b8d093f7-cb70-40ed-9fac-3c82d4bf28f1'::uuid AND target_account_id IS NULL")) + .isEqualTo(1L); + assertThrows( + SQLException.class, + () -> + execute( + schema, + "INSERT INTO player_reports (tenant_id, reporter_account_id, type, description) VALUES (1, '00000000-0000-0000-0000-000000000000', 'BUG', 'nil reporter')")); + assertThrows( + SQLException.class, + () -> + execute( + schema, + "INSERT INTO player_reports (tenant_id, reporter_account_id, target_account_id, type, description) VALUES (1, 'b8d093f7-cb70-40ed-9fac-3c82d4bf28f1', '00000000-0000-0000-0000-000000000000', 'BUG', 'nil target')")); + assertThrows( + SQLException.class, + () -> + execute( + schema, + "INSERT INTO player_reports (tenant_id, reporter_account_id, type, description) VALUES (1, NULL, 'BUG', 'null reporter')")); + // Runtime discovery includes the unchanged service and Saga migration history. + assertThat(history(schema)).hasSize(13); + } + + @Test + void emptyAffectedTablesUpgradeFromV1007AndGenericLogAccountIdRemainsNumeric() throws Exception { + String schema = createSchema(); + migrateToVersion(schema, "1007"); + execute( + schema, + "INSERT INTO log_events (tenant_id, type, message, account_id) VALUES (1, 'INFO', 'preserve generic log', 42)"); + + migrateToLatest(schema); + + assertThat(columnType(schema, "moderation_actions", "account_id")).isEqualTo("uuid"); + assertThat(columnType(schema, "player_reports", "reporter_account_id")).isEqualTo("uuid"); + assertThat(columnType(schema, "player_reports", "target_account_id")).isEqualTo("uuid"); + assertThat(columnType(schema, "player_reports", "tenant_id")).isEqualTo("int8"); + assertThat(columnType(schema, "moderation_actions", "id")).isEqualTo("int8"); + assertThat(columnType(schema, "player_reports", "id")).isEqualTo("int8"); + assertThat(columnType(schema, "log_events", "account_id")).isEqualTo("int8"); + assertThat( + scalarLong( + schema, "SELECT account_id FROM log_events WHERE message = 'preserve generic log'")) + .isEqualTo(42L); + // All earlier service and Saga migrations remain present. + assertThat(history(schema)).hasSize(13); + } + + @Test + void existingCanonicalModerationRowsAreUntouchedByReportOnlyMigration() throws Exception { + String schema = createSchema(); + migrateToVersion(schema, "1007"); + execute( + schema, + "INSERT INTO moderation_actions (tenant_id, account_id, action, reason) VALUES (17, 'b8d093f7-cb70-40ed-9fac-3c82d4bf28f1', 'warning', 'retained action')"); + List rowsBefore = rows(schema, "moderation_actions"); + List historyBefore = history(schema); + migrateToLatest(schema); + assertThat(rows(schema, "moderation_actions")).isEqualTo(rowsBefore); + assertThat(history(schema).subList(0, historyBefore.size())).isEqualTo(historyBefore); + assertThat(history(schema)).hasSize(historyBefore.size() + 1); + } + + @Test + void retainedPlayerReportRefusesWithoutChangingRowsOrMigrationHistory() throws Exception { + String schema = createSchema(); + migrateToVersion(schema, "1007"); + execute( + schema, + "INSERT INTO player_reports (tenant_id, reporter_account_id, target_account_id, type, description) VALUES (41, 43, 47, 'BUG', 'retained report')"); + List historyBefore = history(schema); + List rowsBefore = rows(schema, "player_reports"); + + FlywayException failure = assertThrows(FlywayException.class, () -> migrateToLatest(schema)); + + assertThat(failure).hasStackTraceContaining("Account-owned recovery is required"); + assertThat(history(schema)).isEqualTo(historyBefore); + assertThat(rows(schema, "player_reports")).isEqualTo(rowsBefore); + assertThat(columnType(schema, "player_reports", "reporter_account_id")).isEqualTo("int8"); + assertThat(columnType(schema, "player_reports", "target_account_id")).isEqualTo("int8"); + assertThat( + scalarLong( + schema, + "SELECT tenant_id FROM player_reports WHERE description = 'retained report'")) + .isEqualTo(41L); + assertThat(scalarLong(schema, "SELECT count(*) FROM player_reports WHERE type = 'BUG'")) + .isEqualTo(1L); + assertThat( + scalarLong( + schema, + "SELECT reporter_account_id FROM player_reports WHERE description = 'retained report'")) + .isEqualTo(43L); + assertThat( + scalarLong( + schema, + "SELECT target_account_id FROM player_reports WHERE description = 'retained report'")) + .isEqualTo(47L); + assertThat(scalarLong(schema, "SELECT count(*) FROM moderation_actions")).isZero(); + assertThat(columnType(schema, "log_events", "account_id")).isEqualTo("int8"); + } + + @Test + void migrationWaitsForConcurrentWriterAndRefusesAfterItsRowCommits() throws Exception { + String schema = createSchema(); + migrateToVersion(schema, "1007"); + List historyBefore = history(schema); + + ExecutorService executor = Executors.newSingleThreadExecutor(); + try (Connection writer = connection()) { + writer.setAutoCommit(false); + try (Statement statement = writer.createStatement()) { + statement.executeUpdate( + inSchema( + schema, + "INSERT INTO player_reports (tenant_id, reporter_account_id, type, description) VALUES (7, 11, 'BUG', 'concurrent writer')")); + } + + CountDownLatch migrationStarted = new CountDownLatch(1); + Future migration = + executor.submit( + () -> { + migrationStarted.countDown(); + migrateToLatest(schema); + }); + + assertTrue(migrationStarted.await(5, TimeUnit.SECONDS)); + awaitBlockedMigrationLock(schema); + assertFalse(migration.isDone()); + writer.commit(); + + ExecutionException failure = + assertThrows(ExecutionException.class, () -> migration.get(10, TimeUnit.SECONDS)); + assertThat(failure).hasStackTraceContaining("Account-owned recovery is required"); + assertThat(history(schema)).isEqualTo(historyBefore); + assertThat(history(schema)).hasSize(12); + assertThat(columnType(schema, "player_reports", "reporter_account_id")).isEqualTo("int8"); + assertThat(scalarLong(schema, "SELECT count(*) FROM player_reports")).isEqualTo(1L); + assertThat( + scalarLong( + schema, + "SELECT reporter_account_id FROM player_reports WHERE description = 'concurrent writer'")) + .isEqualTo(11L); + } finally { + executor.shutdownNow(); + executor.awaitTermination(5, TimeUnit.SECONDS); + } + } + + private static String createSchema() throws SQLException { + String schema = "logging_account_uuid_" + UUID.randomUUID().toString().replace("-", ""); + try (Connection connection = connection(); + Statement statement = connection.createStatement()) { + statement.execute("CREATE SCHEMA " + quote(schema)); + } + return schema; + } + + private static void migrateToVersion(String schema, String version) { + Flyway.configure() + .dataSource(dataSource()) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target(MigrationVersion.fromVersion(version)) + .load() + .migrate(); + } + + private static void migrateToLatest(String schema) { + Flyway.configure() + .dataSource(dataSource()) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + } + + private static void execute(String schema, String sql) throws SQLException { + try (Connection connection = connection(); + Statement statement = connection.createStatement()) { + statement.execute(inSchema(schema, sql)); + } + } + + private static String columnType(String schema, String table, String column) throws SQLException { + try (Connection connection = connection(); + PreparedStatement statement = + connection.prepareStatement( + "SELECT udt_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND column_name = ?")) { + statement.setString(1, schema); + statement.setString(2, table); + statement.setString(3, column); + try (ResultSet result = statement.executeQuery()) { + assertTrue(result.next(), "expected column " + schema + "." + table + "." + column); + return result.getString(1); + } + } + } + + private static long scalarLong(String schema, String sql) throws SQLException { + try (Connection connection = connection(); + Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery(inSchema(schema, sql))) { + assertTrue(result.next(), "expected scalar query result"); + return result.getLong(1); + } + } + + private static List history(String schema) throws SQLException { + List entries = new ArrayList<>(); + try (Connection connection = connection(); + Statement statement = connection.createStatement(); + ResultSet result = + statement.executeQuery( + inSchema( + schema, + "SELECT version, checksum, success FROM flyway_schema_history ORDER BY installed_rank"))) { + while (result.next()) { + entries.add( + result.getString("version") + + ":" + + result.getString("checksum") + + ":" + + result.getBoolean("success")); + } + } + return entries; + } + + private static List rows(String schema, String table) throws SQLException { + List records = new ArrayList<>(); + try (Connection connection = connection(); + Statement statement = connection.createStatement(); + ResultSet result = + statement.executeQuery( + "SELECT to_jsonb(row_data)::text FROM (SELECT * FROM " + + quote(schema) + + "." + + quote(table) + + " ORDER BY id) AS row_data")) { + while (result.next()) { + records.add(result.getString(1)); + } + } + return records; + } + + private static void awaitBlockedMigrationLock(String schema) throws Exception { + long deadline = System.nanoTime() + Duration.ofSeconds(10).toNanos(); + while (System.nanoTime() < deadline) { + try (Connection connection = connection(); + PreparedStatement statement = + connection.prepareStatement( + "SELECT count(*) FROM pg_locks AS waiting_lock " + + "JOIN pg_class AS locked_relation ON locked_relation.oid = waiting_lock.relation " + + "JOIN pg_namespace AS locked_schema ON locked_schema.oid = locked_relation.relnamespace " + + "WHERE waiting_lock.pid <> pg_backend_pid() " + + "AND waiting_lock.locktype = 'relation' " + + "AND waiting_lock.mode = 'AccessExclusiveLock' " + + "AND NOT waiting_lock.granted " + + "AND locked_schema.nspname = ? " + + "AND locked_relation.relname = 'player_reports'")) { + statement.setString(1, schema); + try (ResultSet result = statement.executeQuery()) { + if (result.next() && result.getLong(1) > 0L) { + return; + } + } + } + Thread.sleep(25L); + } + throw new AssertionError("Flyway migration did not block on the concurrent writer"); + } + + private static DataSource dataSource() { + return new org.springframework.jdbc.datasource.DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + } + + private static Connection connection() throws SQLException { + return DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + } + + private static String inSchema(String schema, String sql) { + return sql.replace("INTO ", "INTO " + quote(schema) + ".") + .replace("FROM ", "FROM " + quote(schema) + "."); + } + + private static String quote(String identifier) { + return "\"" + identifier.replace("\"", "\"\"") + "\""; + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/data/TestDataSeederTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/data/TestDataSeederTest.java index 6f816ce3ef..b7a2f831af 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/data/TestDataSeederTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/data/TestDataSeederTest.java @@ -7,7 +7,6 @@ import java.util.Optional; import net.firedevops.firemud.loggingadmin.repository.LogEventRepository; -import net.firedevops.firemud.loggingadmin.repository.PlayerReportRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -16,43 +15,33 @@ class TestDataSeederTest { @Mock LogEventRepository logEventRepository; - @Mock PlayerReportRepository playerReportRepository; private TestDataSeeder seeder; @BeforeEach void setup() { MockitoAnnotations.openMocks(this); - seeder = new TestDataSeeder(logEventRepository, playerReportRepository); + seeder = new TestDataSeeder(logEventRepository); } @Test void runSeedsCanonicalRowsWhenMissing() throws Exception { when(logEventRepository.findFirstByTenantIdAndTypeAndMessage(1L, "INFO", "Service started")) .thenReturn(Optional.empty()); - when(playerReportRepository.findFirstByTenantIdAndReporterAccountIdAndTargetAccountIdAndType( - 1L, 1L, 2L, "bug")) - .thenReturn(Optional.empty()); seeder.run(new DefaultApplicationArguments(new String[] {})); verify(logEventRepository).save(any()); - verify(playerReportRepository).save(any()); } @Test void runReassertsCanonicalRowsWhenTheyAlreadyExist() throws Exception { when(logEventRepository.findFirstByTenantIdAndTypeAndMessage(1L, "INFO", "Service started")) .thenReturn(Optional.of(new net.firedevops.firemud.loggingadmin.entity.LogEvent())); - when(playerReportRepository.findFirstByTenantIdAndReporterAccountIdAndTargetAccountIdAndType( - 1L, 1L, 2L, "bug")) - .thenReturn(Optional.of(new net.firedevops.firemud.loggingadmin.entity.PlayerReport())); seeder.run(new DefaultApplicationArguments(new String[] {})); verify(logEventRepository).save(any()); - verify(playerReportRepository).save(any()); verify(logEventRepository, never()).count(); - verify(playerReportRepository, never()).count(); } } diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/dto/CreateReportRequestTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/dto/CreateReportRequestTest.java new file mode 100644 index 0000000000..026ef11fb3 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/dto/CreateReportRequestTest.java @@ -0,0 +1,48 @@ +package net.firedevops.firemud.loggingadmin.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +class CreateReportRequestTest { + private static final String ACCOUNT = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + + @Test + void acceptsCanonicalReporterAndOptionalTarget() { + assertThat(new CreateReportRequest(1L, ACCOUNT, null, "BUG", "detail").targetAccountId()) + .isNull(); + assertThat(new CreateReportRequest(1L, ACCOUNT, ACCOUNT, "BUG", "detail").reporterAccountId()) + .isEqualTo(ACCOUNT); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource( + strings = { + "1", + "00000000-0000-0000-0000-000000000000", + "B8D093F7-CB70-40ED-9FAC-3C82D4BF28F1", + " b8d093f7-cb70-40ed-9fac-3c82d4bf28f1" + }) + void rejectsNonCanonicalReporter(String reporter) { + assertThatThrownBy(() -> new CreateReportRequest(1L, reporter, null, "BUG", "detail")) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + "1", + "00000000-0000-0000-0000-000000000000", + "B8D093F7-CB70-40ED-9FAC-3C82D4BF28F1" + }) + void rejectsNonCanonicalPresentTarget(String target) { + assertThatThrownBy(() -> new CreateReportRequest(1L, ACCOUNT, target, "BUG", "detail")) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportServiceImplTest.java index 5d086866e2..bad2ddff4a 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportServiceImplTest.java @@ -20,7 +20,14 @@ void createReportFailsClosedWithoutTouchingPlayerReportsRepository() { UnsupportedOperationException exception = assertThrows( UnsupportedOperationException.class, - () -> service.createReport(new CreateReportRequest(1L, 2L, 3L, "BUG", "bad"))); + () -> + service.createReport( + new CreateReportRequest( + 1L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "e830a76a-a786-43de-9416-5840fa6e0578", + "BUG", + "bad"))); assertEquals( "Report creation is unavailable until the shared mutation gate is implemented", diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/LoggingAdminClient.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/LoggingAdminClient.java index 708d67ec0e..563235ccdf 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/LoggingAdminClient.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/LoggingAdminClient.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.security.GrpcClientAuth; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.loggingadmin.v1.CreateReportRequest; import net.firedevops.firemud.loggingadmin.v1.CreateReportResponse; @@ -65,6 +66,7 @@ protected ReportServiceGrpc.ReportServiceBlockingStub buildStub(io.grpc.ManagedC * @param description details of the violation */ public void reportChatViolation(long tenantId, String accountId, String description) { + JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); CreateReportRequest request = CreateReportRequest.newBuilder() .setTenantId(Long.toString(tenantId)) diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/SocialInternalGrpcClientAuthTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/SocialInternalGrpcClientAuthTest.java index de78a0acbc..1d2830d5f5 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/SocialInternalGrpcClientAuthTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/SocialInternalGrpcClientAuthTest.java @@ -8,6 +8,7 @@ import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import io.grpc.CallOptions; @@ -105,6 +106,29 @@ void loggingAdminClientUsesUnknownServiceFallbackWhenRuntimeIdentityUnavailable( assertInternalServiceToken(channel, "unknown-service"); } + @Test + void loggingAdminClientRejectsNoncanonicalAccountsBeforeChannelAccess() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + LoggingAdminClient client = + new LoggingAdminClient( + new ServiceEndpointsProperties(), + plaintextGrpcProperties(), + channelFactory, + jwtUtil, + runtimeIdentityProvider()); + + for (String invalid : + List.of( + "42", + "invalid", + "00000000-0000-0000-0000-000000000000", + "A0000000-0000-0000-0000-000000000042")) { + assertThatThrownBy(() -> client.reportChatViolation(7L, invalid, "Filtered profanity")) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(channelFactory); + } + @Test void loggingAdminClientPropagatesApplicationErrors() throws Exception { CapturingChannel channel = From 31dd5637fabf44766772c59caf094ed836a6a1e1 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 14 Nov 2026 01:46:48 +1300 Subject: [PATCH 02/17] Prove exact-self Social presence policy across caller roles --- .../impl/SocialGroupsGrpcServiceTest.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/SocialGroupsGrpcServiceTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/SocialGroupsGrpcServiceTest.java index 64f9eb5a45..b92facafa5 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/SocialGroupsGrpcServiceTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/SocialGroupsGrpcServiceTest.java @@ -44,6 +44,8 @@ import net.firedevops.firemud.socialgroups.v1.SendMessageResponse; import net.firedevops.firemud.socialgroups.v1.UpdateFriendPresencePolicyResponse; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; class SocialGroupsGrpcServiceTest { @@ -1245,6 +1247,73 @@ public void onCompleted() {} } } + @ParameterizedTest + @ValueSource(strings = {"ordinary", "tenantAdmin", "platformAdmin"}) + void presencePolicyRequiresExactSelfDespiteCallerRoles(String role) { + FriendService friend = Mockito.mock(FriendService.class); + var service = + new SocialGroupsGrpcService( + Mockito.mock(PingService.class), + Mockito.mock(ChatService.class), + Mockito.mock(GuildService.class), + friend, + Mockito.mock(MailService.class), + new SocialAccessGuard(), + new SimpleMeterRegistry()); + SessionContext.setContext( + accountUuid(1L), + role.equals("platformAdmin") ? List.of(role) : List.of(), + role.equals("tenantAdmin") ? Map.of("7", List.of(role)) : Map.of()); + try { + AtomicReference get = new AtomicReference<>(); + service.getFriendPresencePolicy( + net.firedevops.firemud.socialgroups.v1.GetFriendPresencePolicyRequest.newBuilder() + .setTenantId("7") + .setAccountId(accountUuid(2L)) + .build(), + new StreamObserver<>() { + public void onNext(GetFriendPresencePolicyResponse value) { + get.set(value); + } + + public void onError(Throwable error) { + throw new AssertionError(error); + } + + public void onCompleted() {} + }); + assertNotNull(get.get()); + assertEquals("PERMISSION_DENIED", get.get().getError().getCode()); + + AtomicReference update = new AtomicReference<>(); + service.updateFriendPresencePolicy( + net.firedevops.firemud.socialgroups.v1.UpdateFriendPresencePolicyRequest.newBuilder() + .setTenantId("7") + .setAccountId(accountUuid(2L)) + .setVisibilityPolicy( + net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC) + .build(), + new StreamObserver<>() { + public void onNext(UpdateFriendPresencePolicyResponse value) { + update.set(value); + } + + public void onError(Throwable error) { + throw new AssertionError(error); + } + + public void onCompleted() {} + }); + assertNotNull(update.get()); + assertEquals("PERMISSION_DENIED", update.get().getError().getCode()); + assertEquals(false, update.get().getSuccess()); + verifyNoInteractions(friend); + } finally { + SessionContext.clear(); + } + } + @Test void numericFriendViewerFailsBeforeAuthorizationOrServiceDispatch() { FriendService friend = Mockito.mock(FriendService.class); From f4c03e7156f28a4dab045ae8f0acab0a0f9b59e7 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 14 Nov 2026 05:44:57 +1300 Subject: [PATCH 03/17] Qualify moderation UUID refusal and nil report target --- ...tUuidMigrationPostgresIntegrationTest.java | 75 +++++++++++++++++++ .../service/impl/ReportGrpcServiceTest.java | 36 +++++++++ 2 files changed, 111 insertions(+) diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java index 2bcd713099..ff42b019ac 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java @@ -3,8 +3,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.sql.Connection; +import java.sql.Statement; import java.util.List; import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; @@ -109,6 +116,73 @@ void populatedLegacyRowsBlockMigrationWithoutChangingRowsOrMigrationHistory() { .isEqualTo("bigint"); } + @Test + void concurrentModerationWriterBlocksMigrationThenItsCommittedRowForcesRefusal() + throws Exception { + List historyBefore = migrationHistory(); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try (Connection writer = dataSource.getConnection()) { + writer.setAutoCommit(false); + int writerPid; + String rowBefore; + try (Statement statement = writer.createStatement()) { + statement.setQueryTimeout(5); + try (var result = statement.executeQuery("SELECT pg_backend_pid()")) { + result.next(); + writerPid = result.getInt(1); + } + statement.executeUpdate( + "INSERT INTO moderation_actions (tenant_id, account_id, action, reason) VALUES (17, 9007199254740993, 'ban', 'concurrent retained action')"); + try (var result = + statement.executeQuery("SELECT row_to_json(m)::text FROM moderation_actions m")) { + result.next(); + rowBefore = result.getString(1); + } + } + Future migration = executor.submit(() -> flyway("1003").migrate()); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + boolean blocked = false; + try (Connection observer = dataSource.getConnection(); + var query = + observer.prepareStatement( + "SELECT EXISTS (SELECT 1 FROM pg_locks l WHERE l.relation = 'public.moderation_actions'::regclass AND l.mode = 'AccessExclusiveLock' AND NOT l.granted AND ? = ANY(pg_blocking_pids(l.pid)))")) { + query.setQueryTimeout(2); + query.setInt(1, writerPid); + while (System.nanoTime() < deadline && !migration.isDone()) { + try (var result = query.executeQuery()) { + result.next(); + blocked = result.getBoolean(1); + } + if (blocked) { + break; + } + Thread.sleep(25); + } + } + assertThat(blocked).as("V1003 must wait on the uncommitted moderation writer").isTrue(); + assertThat(migration.isDone()).isFalse(); + writer.commit(); + assertThatThrownBy(() -> migration.get(10, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasStackTraceContaining("Cannot migrate populated legacy moderation Account references"); + assertThat(migrationHistory()).isEqualTo(historyBefore); + assertThat( + jdbc.queryForList( + "SELECT row_to_json(m)::text FROM moderation_actions m", String.class)) + .containsExactly(rowBefore); + assertThat( + jdbc.queryForObject( + "SELECT data_type FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'moderation_actions' AND column_name = 'account_id'", + String.class)) + .isEqualTo("bigint"); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(25, TimeUnit.SECONDS)) + .as("bounded migration task must finish before the fixture is reused") + .isTrue(); + } + } + private List migrationHistory() { return jdbc.queryForList( "SELECT row_to_json(h)::text FROM flyway_schema_history h ORDER BY installed_rank", @@ -118,6 +192,7 @@ private List migrationHistory() { private Flyway flyway(String target) { return Flyway.configure() .dataSource(dataSource) + .initSql("SET lock_timeout = '15s'; SET statement_timeout = '20s'") .locations("classpath:db/migration") .placeholders(Map.of("serviceSchema", "public")) .target(MigrationVersion.fromVersion(target)) diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java index 1f20af7626..7f58b5333b 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java @@ -165,6 +165,42 @@ public void onCompleted() {} assertEquals("Malformed claim: targetAccountId", ref.get().getError().getMessage()); } + @Test + void createReportRejectsNilTargetAccountIdBeforeDispatch() { + SessionContext.setContext( + "", List.of(), Map.of(), true, "social-groups-service", "test-instance"); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + ReportGrpcService service = new ReportGrpcService(meterRegistry); + + AtomicReference ref = new AtomicReference<>(); + service.createReport( + CreateReportRequest.newBuilder() + .setTenantId("1") + .setReporterAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") + .setTargetAccountId("00000000-0000-0000-0000-000000000000") + .setType("BUG") + .setDescription("bad") + .build(), + new StreamObserver<>() { + @Override + public void onNext(CreateReportResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertNotNull(ref.get()); + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + assertEquals("Malformed claim: targetAccountId", ref.get().getError().getMessage()); + } + @Test void createReportRejectsMissingCallerBeforePersistence() { SessionContext.clear(); From 3072ea3fb440ad6b6ac6483ea33b821bfe73567f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:44:25 +1300 Subject: [PATCH 04/17] test(gateway): supply native peer in account receiving fixture --- ...untCheckoutReceivingConfigurationTest.java | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java index 49a04ab100..20b4508e9b 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java @@ -3,10 +3,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; +import io.netty.channel.Channel; +import java.net.InetSocketAddress; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -34,6 +39,8 @@ import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.WebFilter; import reactor.core.publisher.Mono; +import reactor.netty.Connection; +import reactor.netty.http.server.HttpServerRequest; class AccountCheckoutReceivingConfigurationTest { @TempDir Path temporaryDirectory; @@ -153,7 +160,7 @@ void authenticatedAccountInvalidArgumentMapsToSafeBadRequest() { var responseHolder = new AtomicReference>(); trust .filter( - MockServerWebExchange.from(request), + MockServerWebExchange.from(withNativeSocketPeer(request)), exchange -> controller.login(exchange).doOnNext(responseHolder::set).then()) .block(); var response = responseHolder.get(); @@ -229,6 +236,17 @@ void receivingRateLimitUnavailableReturnsServiceUnavailableAndIgnoresOtherPaths( assertThat(login.getResponse().getHeaders().getCacheControl()).contains("no-store"); } + private static MockServerHttpRequest withNativeSocketPeer(MockServerHttpRequest request) { + HttpServerRequest nativeRequest = + mock(HttpServerRequest.class, withSettings().extraInterfaces(Connection.class)); + Channel channel = mock(Channel.class); + when(((Connection) nativeRequest).channel()).thenReturn(channel); + when(channel.remoteAddress()).thenReturn(new InetSocketAddress("192.0.2.10", 443)); + MockServerHttpRequest requestWithNativePeer = spy(request); + doReturn(nativeRequest).when(requestWithNativePeer).getNativeRequest(); + return requestWithNativePeer; + } + private static AccountCheckoutReceivingProperties receivingProperties() { var properties = new AccountCheckoutReceivingProperties(); properties.setEnabled(true); From fa2a1ef6fdc87ed4d112731b8630e02a2d70f46a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:42:14 +1300 Subject: [PATCH 05/17] Restore executed UUID migration proof guards --- .github/scripts/run-gradle-module-checks.sh | 76 ++++- .../validation-and-runtime-proof.md | 1 + .../platform-operations-and-delivery.md | 2 +- .../tests/gradle-proof-tooling-contract.sh | 172 +++++++++++ .../tests/test_gradle_compile_failure.py | 182 ++++++++++++ dev-tools/validation/inspect-test-results.sh | 267 +++++++++++++++++- 6 files changed, 695 insertions(+), 5 deletions(-) diff --git a/.github/scripts/run-gradle-module-checks.sh b/.github/scripts/run-gradle-module-checks.sh index a9b7aef77d..4e074f4bbf 100644 --- a/.github/scripts/run-gradle-module-checks.sh +++ b/.github/scripts/run-gradle-module-checks.sh @@ -15,6 +15,62 @@ if [[ $# -lt 1 || $# -gt 2 || ! "$MODULE" =~ ^[a-z0-9]+(-[a-z0-9]+)*$ || \ fi declare -a CHECK_ARGS=(-PfullCheck) +# These required physical suites must execute, not restore cached JUnit results. +if [[ "$MODULE" == "logging-admin-service" || "$MODULE" == "social-groups-service" ]]; then + CHECK_ARGS+=(--no-build-cache --no-configuration-cache ":${MODULE}:integrationTest" --rerun) + # A skipped/no-source task must not satisfy this invocation from old XML. + # Invalidate only generated JUnit reports for this module before Gradle runs. + test_results="$ROOT_DIR/services/$MODULE/build/test-results" + for proof_dir in "$ROOT_DIR/services" "$ROOT_DIR/services/$MODULE" \ + "$ROOT_DIR/services/$MODULE/build" "$test_results"; do + if [[ -L "$proof_dir" ]]; then + echo "Required database proof refuses a symlinked result path" >&2 + exit 1 + fi + done + if [[ -d "$test_results" ]]; then + if [[ -n "$(find "$test_results" -type l -print -quit)" ]]; then + echo "Required database proof refuses symlinked generated results" >&2 + exit 1 + fi + find "$test_results" -type f -name 'TEST-*.xml' -delete + fi +fi + +verify_required_database_proof() { + case "$MODULE" in + logging-admin-service) + local moderation="net.firedevops.firemud.loggingadmin.ModerationAccountUuidMigrationPostgresIntegrationTest" + local report="net.firedevops.firemud.loggingadmin.ReportAccountUuidMigrationPostgresIntegrationTest" + bash "$ROOT_DIR/dev-tools/validation/inspect-test-results.sh" --strict \ + --require-suite "$moderation" \ + --require-suite "$report" \ + --require-case "$moderation#emptySchemaMigratesAndKeepsExactUuidWithoutChangingPolicyFields()" \ + --require-case "$moderation#populatedLegacyRowsBlockMigrationWithoutChangingRowsOrMigrationHistory()" \ + --require-case "$moderation#concurrentModerationWriterBlocksMigrationThenItsCommittedRowForcesRefusal()" \ + --require-case "$report#freshSchemaMigratesWithCanonicalAccountUuidsAndNumericLocalIdentifiers()" \ + --require-case "$report#emptyAffectedTablesUpgradeFromV1007AndGenericLogAccountIdRemainsNumeric()" \ + --require-case "$report#existingCanonicalModerationRowsAreUntouchedByReportOnlyMigration()" \ + --require-case "$report#retainedPlayerReportRefusesWithoutChangingRowsOrMigrationHistory()" \ + --require-case "$report#migrationWaitsForConcurrentWriterAndRefusesAfterItsRowCommits()" \ + "$MODULE" + ;; + social-groups-service) + local suite="integration.net.firedevops.firemud.socialgroups.repository.SocialAccountUuidMigrationPostgresIntegrationTest" + bash "$ROOT_DIR/dev-tools/validation/inspect-test-results.sh" --strict \ + --require-suite "$suite" \ + --require-case "$suite#emptyLegacyFrontierConvergesAndTypedRepositoriesRoundTripCanonicalAccountUuids()" \ + --require-case "$suite#[1] table = \"guilds\"" \ + --require-case "$suite#[2] table = \"guild_members\"" \ + --require-case "$suite#[3] table = \"chat_messages\"" \ + --require-case "$suite#[4] table = \"friend_links\"" \ + --require-case "$suite#[5] table = \"mail_messages\"" \ + --require-case "$suite#[6] table = \"account_friend_links\"" \ + --require-case "$suite#concurrentWriterCommitsBeforeEmptyCheckAndItsEvidenceIsPreserved()" \ + "$MODULE" + ;; + esac +} if [[ ( "$MODULE" == "account-service" || "$MODULE" == "game-session-service" || "$MODULE" == "world-management-service" ) && "$PARTITION" != "full" ]]; then SERVICE_DIR="$ROOT_DIR/services/$MODULE" PARTITION_DIR="$SERVICE_DIR/build/slow-service-ci-partition" @@ -64,11 +120,24 @@ trap 'rm -f -- "$CHECK_LOG"' EXIT if [[ -z "$CHECK_LOG" ]]; then printf 'FIREMUD_STALL_ACTIVATION status=disabled-capture-unavailable\n' >&2 echo "Compile-failure log unavailable; running the original check without capture" >&2 - exec bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ + if [[ "$MODULE" != "logging-admin-service" && "$MODULE" != "social-groups-service" ]]; then + # Preserve the existing exec/process boundary for every unaffected module. + exec bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ + --runner "$ROOT_DIR/gradlew" -- \ + --max-workers=2 \ + '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' \ + ":${MODULE}:check" "${CHECK_ARGS[@]}" --profile + fi + if bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ --runner "$ROOT_DIR/gradlew" -- \ --max-workers=2 \ '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' \ - ":${MODULE}:check" "${CHECK_ARGS[@]}" --profile + ":${MODULE}:check" "${CHECK_ARGS[@]}" --profile; then + verify_required_database_proof + exit 0 + else + exit "$?" + fi fi declare -a CAPTURE_ARGS=() stall_activation=disabled-scope @@ -109,4 +178,7 @@ if (( check_status > 0 && check_status < 128 )); then --output "$ROOT_DIR/build/reports/compile-failure/$MODULE" || \ echo "Compile-failure evidence collection unavailable; preserving check exit $check_status" >&2 fi +if (( check_status == 0 )); then + verify_required_database_proof +fi exit "$check_status" diff --git a/design/developer-workflows/validation-and-runtime-proof.md b/design/developer-workflows/validation-and-runtime-proof.md index aa4303a71c..dcc47379a0 100644 --- a/design/developer-workflows/validation-and-runtime-proof.md +++ b/design/developer-workflows/validation-and-runtime-proof.md @@ -77,3 +77,4 @@ If an owned process survives KILL, for example because of uninterruptible kernel ## Diagnostics - If a heavy Gradle run becomes quiet after test execution, use `dev-tools/validation/inspect-test-results.sh ` to inspect fresh parsed XML. It is diagnostic evidence, not proof that the task completed cleanly. +- The CI module runner separately requires executed Logging and Social UUID migration proof after a successful full check, with build and configuration caches disabled for those modules. It invalidates that module's generated JUnit XML before Gradle starts and forces its `integrationTest --rerun`, so a skipped/no-source task or retained prior XML cannot satisfy the current invocation. Its explicit `--strict --require-suite ... --require-case ...` inspector mode rejects missing, duplicate, malformed, empty, skipped, failed or errored required reports/cases. Logging uses the published moderation V1003 and report V1008 suites; Social requires every retained-table parameter as well as empty-storage and concurrent-writer cases. This selected-case evidence does not replace the Gradle exit status, prove an unsupported owner capability, or establish live activation. Ordinary inspector calls retain their diagnostic-only behavior. diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index da9d3a1d50..4bdd1f23cf 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -94,7 +94,7 @@ The tracker separates implemented fail-closed ingress stubs from supported durab Ordinary moderation Account UUID storage and the matching PLAY policy receiver landed through #2972. Its forward V1003 migration takes an access-exclusive lock and refuses any populated legacy moderation table before alteration; it supplies no inferred Account mapping, backfill or deletion. Retained data requires an explicit owner-backed disposition before that migration can proceed. Moderation mutations remain fail-closed; storage preparation is not fixed-category enforcement or production activation proof. The [Logging & Admin data model](../../architecture/microservices/logging-admin-service/runtime-and-data.md#data-model) owns the target representation. -Report receiving now uses canonical Account UUID request validation and UUID report DTO/entity/repository fields. New forward V1008 converts only empty report storage after an access-exclusive lock and refuses retained numeric rows without changing their values or earlier migration history. It does not rewrite V1003 or infer Account mappings. Synthetic report seeding is removed; generic log identifiers remain numeric. ReportAccountUuidMigrationPostgresIntegrationTest covers fresh and V1007 upgrades, unaffected moderation data, retained-report refusal and concurrent-writer refusal. Execution proof is still required before readiness; this source preparation neither enables report mutation nor retires #2976 or changes #2933 dependencies. +Report receiving now uses canonical Account UUID request validation and UUID report DTO/entity/repository fields. New forward V1008 converts only empty report storage after an access-exclusive lock and refuses retained numeric rows without changing their values or earlier migration history. It does not rewrite V1003 or infer Account mappings. Synthetic report seeding is removed; generic log identifiers remain numeric. ReportAccountUuidMigrationPostgresIntegrationTest covers fresh and V1007 upgrades, unaffected moderation data, retained-report refusal and concurrent-writer refusal. Focused qualification on receiving source `2148415` passes all 339 Logging unit cases and eight native PostgreSQL migration cases (three moderation and five report), with zero failures, errors or skips, plus enabled main/unit/integration static analysis and Java formatting. The physical cases prove each published migration domain’s empty-storage convergence, retained-row refusal and concurrent-writer fencing; the report upgrade also preserves existing canonical moderation rows. This is not the donor’s former combined two-table migration transaction: V1003 remains published history and V1008 is report-only. No Account identity mapping, live report mutation, fresh-image activation, #2976 retirement or #2933 dependency change is implied. ## Canonical Design Sources diff --git a/dev-tools/tests/gradle-proof-tooling-contract.sh b/dev-tools/tests/gradle-proof-tooling-contract.sh index 624f41e1ef..e0e7e9b1bc 100644 --- a/dev-tools/tests/gradle-proof-tooling-contract.sh +++ b/dev-tools/tests/gradle-proof-tooling-contract.sh @@ -89,6 +89,177 @@ grep -q "Most recent XML on disk:" <<<"$inspection_output" grep -q "Failing XML files:" <<<"$inspection_output" grep -q "Diagnostic only:" <<<"$inspection_output" +# Generic strict-mode fixtures; these names are parser samples, not current Account CI coverage. +JOIN_SUITE="net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest" +EXCHANGE_SUITE="integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest" +JOIN_CASE="$JOIN_SUITE#positiveMembershipSnapshotRejectsScalarAndWrongTenantVersionMaps()" +EXCHANGE_CASE="$EXCHANGE_SUITE#claimOnlyTransactionRollsBackPendingExchange()" + +inspect_strict() { + bash "$INSPECTOR" --root "$1" --strict \ + --require-suite "$JOIN_SUITE" \ + --require-suite "$EXCHANGE_SUITE" \ + --require-case "$JOIN_CASE" \ + --require-case "$EXCHANGE_CASE" \ + account-service +} + +new_strict_fixture() { + mkdir -p "$1/services/account-service/build/test-results/integrationTest" +} + +STRICT_GREEN_ROOT="$TMP_DIR/strict-green" +new_strict_fixture "$STRICT_GREEN_ROOT" +cat >"$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + + STRICT_OUTPUT_SENTINEL + +XML +cat >"$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" < + + +XML +strict_green_output="$(inspect_strict "$STRICT_GREEN_ROOT")" +grep -q '^Strict JUnit proof: passed$' <<<"$strict_green_output" +grep -Fq "Suite $JOIN_SUITE: tests=2 skipped=0 failures=0 errors=0 outcome=passed" <<<"$strict_green_output" +grep -Fq "Case $JOIN_CASE: executions=1 outcome=passed" <<<"$strict_green_output" +grep -Fq "Case $EXCHANGE_CASE: executions=1 outcome=passed" <<<"$strict_green_output" +if grep -q "STRICT_OUTPUT_SENTINEL" <<<"$strict_green_output"; then + echo "Strict inspection leaked test output." >&2 + exit 1 +fi + +STRICT_MISSING_SUITE_ROOT="$TMP_DIR/strict-missing-suite" +new_strict_fixture "$STRICT_MISSING_SUITE_ROOT" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" \ + "$STRICT_MISSING_SUITE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" +if missing_suite_output="$(inspect_strict "$STRICT_MISSING_SUITE_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a missing suite." >&2 + exit 1 +fi +grep -Fq "Missing required suite: $EXCHANGE_SUITE" <<<"$missing_suite_output" + +STRICT_NO_REPORTS_ROOT="$TMP_DIR/strict-no-reports" +new_strict_fixture "$STRICT_NO_REPORTS_ROOT" +if no_reports_output="$(inspect_strict "$STRICT_NO_REPORTS_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted an empty report directory." >&2 + exit 1 +fi +grep -Fq "No JUnit XML reports were found." <<<"$no_reports_output" + +STRICT_MISSING_CASE_ROOT="$TMP_DIR/strict-missing-case" +new_strict_fixture "$STRICT_MISSING_CASE_ROOT" +cat >"$STRICT_MISSING_CASE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_MISSING_CASE_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if missing_case_output="$(inspect_strict "$STRICT_MISSING_CASE_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a missing case." >&2 + exit 1 +fi +grep -Fq "Missing required case: $JOIN_CASE" <<<"$missing_case_output" + +STRICT_ZERO_TESTS_ROOT="$TMP_DIR/strict-zero-tests" +new_strict_fixture "$STRICT_ZERO_TESTS_ROOT" +cat >"$STRICT_ZERO_TESTS_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_ZERO_TESTS_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if zero_tests_output="$(inspect_strict "$STRICT_ZERO_TESTS_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted an empty required suite." >&2 + exit 1 +fi +grep -Fq "Required suite has zero tests: $JOIN_SUITE" <<<"$zero_tests_output" + +STRICT_SKIPPED_ROOT="$TMP_DIR/strict-skipped" +new_strict_fixture "$STRICT_SKIPPED_ROOT" +cat >"$STRICT_SKIPPED_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_SKIPPED_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if skipped_output="$(inspect_strict "$STRICT_SKIPPED_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a skipped suite." >&2 + exit 1 +fi +grep -Fq "Required suite is failing, errored, or skipped: $JOIN_SUITE" <<<"$skipped_output" +grep -Fq "Case $JOIN_CASE: executions=1 outcome=skipped" <<<"$skipped_output" + +STRICT_FAILING_ROOT="$TMP_DIR/strict-failing" +new_strict_fixture "$STRICT_FAILING_ROOT" +cat >"$STRICT_FAILING_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + SENSITIVE_FAILURE_SENTINEL + + SENSITIVE_STDOUT_SENTINEL + +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_FAILING_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if failing_output="$(inspect_strict "$STRICT_FAILING_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a failing suite." >&2 + exit 1 +fi +grep -Fq "Required suite is failing, errored, or skipped: $JOIN_SUITE" <<<"$failing_output" +grep -Fq "Case $JOIN_CASE: executions=1 outcome=failure" <<<"$failing_output" +if grep -q "SENSITIVE_" <<<"$failing_output"; then + echo "Strict inspection leaked failure details." >&2 + exit 1 +fi + +STRICT_DUPLICATE_SUITE_ROOT="$TMP_DIR/strict-duplicate-suite" +new_strict_fixture "$STRICT_DUPLICATE_SUITE_ROOT" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" \ + "$STRICT_DUPLICATE_SUITE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" \ + "$STRICT_DUPLICATE_SUITE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join-copy.xml" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_DUPLICATE_SUITE_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if duplicate_suite_output="$(inspect_strict "$STRICT_DUPLICATE_SUITE_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a duplicate suite report." >&2 + exit 1 +fi +grep -Fq "Duplicate required suite: $JOIN_SUITE (2 report(s))" <<<"$duplicate_suite_output" + +STRICT_DUPLICATE_CASE_ROOT="$TMP_DIR/strict-duplicate-case" +new_strict_fixture "$STRICT_DUPLICATE_CASE_ROOT" +cat >"$STRICT_DUPLICATE_CASE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + + +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_DUPLICATE_CASE_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if duplicate_case_output="$(inspect_strict "$STRICT_DUPLICATE_CASE_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted duplicate requested case execution." >&2 + exit 1 +fi +grep -Fq "Duplicate required case: $JOIN_CASE (2 execution(s))" <<<"$duplicate_case_output" + +STRICT_MALFORMED_ROOT="$TMP_DIR/strict-malformed" +new_strict_fixture "$STRICT_MALFORMED_ROOT" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" \ + "$STRICT_MALFORMED_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_MALFORMED_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +printf '"$STRICT_MALFORMED_ROOT/services/account-service/build/test-results/integrationTest/TEST-malformed.xml" +if malformed_output="$(inspect_strict "$STRICT_MALFORMED_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted malformed JUnit XML." >&2 + exit 1 +fi +grep -Fq "malformed reports: 1" <<<"$malformed_output" + bootstrap_validation_output="$( FIREMUD_SMOKE_COMPOSE_SERVICES=$'gateway\ngame-session-service\n' \ FIREMUD_SMOKE_NO_CACHE_SERVICES='gateway game-session-service' \ @@ -110,5 +281,6 @@ set -e grep -q "Use Docker Compose service ids here" <<<"$bootstrap_invalid_output" python3 -m unittest discover -s "$ROOT_DIR/dev-tools/tests" -p '*gradle*test*.py' +python3 -m unittest discover -s "$ROOT_DIR/dev-tools/tests" -p 'test_gradle_compile_failure.py' echo "gradle proof tooling contract checks passed" diff --git a/dev-tools/tests/test_gradle_compile_failure.py b/dev-tools/tests/test_gradle_compile_failure.py index 5c500b07bf..deb8be70b8 100644 --- a/dev-tools/tests/test_gradle_compile_failure.py +++ b/dev-tools/tests/test_gradle_compile_failure.py @@ -12,6 +12,7 @@ import time import unittest from pathlib import Path +from typing import ClassVar from unittest.mock import Mock, patch ROOT = Path(__file__).resolve().parents[2] @@ -1133,5 +1134,186 @@ def test_reused_scratch_name_never_publishes_existing_evidence(self): self.assertEqual(1, len(self.calls())) + +class RequiredDatabaseProofTests(unittest.TestCase): + """Execute the current runner and real inspector; Gradle itself is inert.""" + + LOGGING_MODERATION = 'net.firedevops.firemud.loggingadmin.ModerationAccountUuidMigrationPostgresIntegrationTest' + LOGGING_REPORT = 'net.firedevops.firemud.loggingadmin.ReportAccountUuidMigrationPostgresIntegrationTest' + SOCIAL = 'integration.net.firedevops.firemud.socialgroups.repository.SocialAccountUuidMigrationPostgresIntegrationTest' + REQUIRED: ClassVar[dict[str, dict[str, list[str]]]] = { + 'logging-admin-service': { + LOGGING_MODERATION: [ + 'emptySchemaMigratesAndKeepsExactUuidWithoutChangingPolicyFields()', + 'populatedLegacyRowsBlockMigrationWithoutChangingRowsOrMigrationHistory()', + 'concurrentModerationWriterBlocksMigrationThenItsCommittedRowForcesRefusal()', + ], + LOGGING_REPORT: [ + 'freshSchemaMigratesWithCanonicalAccountUuidsAndNumericLocalIdentifiers()', + 'emptyAffectedTablesUpgradeFromV1007AndGenericLogAccountIdRemainsNumeric()', + 'existingCanonicalModerationRowsAreUntouchedByReportOnlyMigration()', + 'retainedPlayerReportRefusesWithoutChangingRowsOrMigrationHistory()', + 'migrationWaitsForConcurrentWriterAndRefusesAfterItsRowCommits()', + ], + }, + 'social-groups-service': { + SOCIAL: [ + 'emptyLegacyFrontierConvergesAndTypedRepositoriesRoundTripCanonicalAccountUuids()', + '[1] table = "guilds"', '[2] table = "guild_members"', + '[3] table = "chat_messages"', '[4] table = "friend_links"', + '[5] table = "mail_messages"', '[6] table = "account_friend_links"', + 'concurrentWriterCommitsBeforeEmptyCheckAndItsEvidenceIsPreserved()', + ], + }, + } + + def setUp(self): + (ROOT / 'build').mkdir(exist_ok=True) + self.temp = tempfile.TemporaryDirectory(dir=ROOT / 'build', prefix='required-pg-proof-') + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + + def fixture(self, module, mutation=None, fallback=False, check_exit=0): + import xml.etree.ElementTree as element_tree + + root = self.root / f'{module}-{mutation}-{fallback}-{check_exit}' + root.mkdir() + for relative in ['.github/scripts/run-gradle-module-checks.sh', + 'dev-tools/validation/inspect-test-results.sh']: + target = root / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / relative, target) + validation = root / 'dev-tools/validation' + (validation / 'run-gradle-with-dependency-recovery.sh').write_text( + '#!/bin/bash\nrunner="$2"; shift 3; exec "$runner" "$@"\n') + (validation / 'collect-gradle-compile-failure.py').write_text( + 'import sys\n' + "if '--capture-log' in sys.argv: sys.stdout.buffer.write(sys.stdin.buffer.read())\n") + runner = root / 'gradlew' + runner.write_text('#!/bin/bash\nprintf "%s\\n" "$*" >> calls\n' + + (f'cp generated-reports/TEST-*.xml services/{module}/build/test-results/integrationTest/ 2>/dev/null || true\n' + if mutation != 'stale-only' else '') + + f'exit {check_exit}\n') + runner.chmod(0o755) + reports = root / f'services/{module}/build/test-results/integrationTest' + reports.mkdir(parents=True) + documents = [] + for suite, names in self.REQUIRED[module].items(): + document = element_tree.Element('testsuite', name=suite, tests=str(len(names)), + failures='0', errors='0', skipped='0') + for name in names: + element_tree.SubElement(document, 'testcase', classname=suite, name=name) + element_tree.SubElement(document, 'system-out').text = 'STRICT_OUTPUT_SECRET' + documents.append(document) + # Seed old green reports before every run. Only the Gradle fixture may + # regenerate proof, so an up-to-date/skipped/no-source result must refuse. + for index, item in enumerate(documents): + element_tree.ElementTree(item).write(reports / f'TEST-{index}.xml') + generated_reports = root / 'generated-reports' + generated_reports.mkdir() + document = documents[-1] + case = document.find('testcase') + if mutation == 'missing-case': + document.remove(case) + document.set('tests', str(len(document.findall('testcase')))) + elif mutation == 'duplicate-case': + case.set('name', document.findall('testcase')[1].get('name')) + elif mutation in ('skipped', 'child-skipped', 'failure', 'error'): + tag = 'skipped' if 'skipped' in mutation else mutation + element_tree.SubElement(case, tag).text = 'PRIVATE_FAILURE_CONTENT' + if mutation != 'child-skipped': + document.set({'skipped': 'skipped', 'failure': 'failures', 'error': 'errors'}[tag], '1') + elif mutation == 'counter-skipped': + document.set('skipped', '1') + elif mutation == 'zero-tests': + for testcase in document.findall('testcase'): + document.remove(testcase) + document.set('tests', '0') + elif mutation == 'wrong-count': + document.set('tests', '999') + elif mutation == 'missing-counter': + del document.attrib['tests'] + elif mutation == 'wrong-class': + case.set('classname', 'unrelated.Suite') + for index, item in enumerate(documents): + if mutation == 'no-reports' or (mutation == 'missing-suite' and index == 0): + continue + element_tree.ElementTree(item).write(generated_reports / f'TEST-{index}.xml') + if mutation == 'duplicate-suite': + shutil.copyfile(generated_reports / 'TEST-0.xml', generated_reports / 'TEST-duplicate.xml') + elif mutation == 'malformed': + (generated_reports / 'TEST-malformed.xml').write_text('&2 -Usage: inspect-test-results.sh [--root ] +Usage: + inspect-test-results.sh [--root ] + inspect-test-results.sh --strict [--root ] \ + --require-suite ... \ + --require-case ... Summarize parsed JUnit XML currently on disk under services//build/test-results. This is diagnostic only; it helps explain quiet Gradle tails but does not prove the original Gradle invocation completed cleanly. + +Strict mode fails closed unless every named suite has exactly one non-empty, +green report and every named test case executed exactly once without a skip, +failure, or error. EOF exit 1 } +STRICT_MODE=0 +REQUIRED_SUITES=() +REQUIRED_CASES=() + while (($# > 0)); do case "$1" in --root) @@ -21,6 +33,20 @@ while (($# > 0)); do ROOT_DIR="$2" shift 2 ;; + --strict) + STRICT_MODE=1 + shift + ;; + --require-suite) + [[ $# -ge 2 ]] || usage + REQUIRED_SUITES+=("$2") + shift 2 + ;; + --require-case) + [[ $# -ge 2 ]] || usage + REQUIRED_CASES+=("$2") + shift 2 + ;; --help|-h) usage ;; @@ -32,6 +58,39 @@ done [[ $# -eq 1 ]] || usage +if [[ "$STRICT_MODE" == "1" ]]; then + ((${#REQUIRED_SUITES[@]} > 0 && ${#REQUIRED_CASES[@]} > 0)) || usage + + for ((i = 0; i < ${#REQUIRED_SUITES[@]}; i++)); do + suite_name="${REQUIRED_SUITES[$i]}" + [[ -n "$suite_name" && ! "$suite_name" =~ [[:cntrl:]] && "$suite_name" != *'#'* ]] || usage + for ((j = 0; j < i; j++)); do + [[ "$suite_name" != "${REQUIRED_SUITES[$j]}" ]] || usage + done + done + + for ((i = 0; i < ${#REQUIRED_CASES[@]}; i++)); do + case_name="${REQUIRED_CASES[$i]}" + [[ "$case_name" == *'#'* && "${case_name#*#}" != *'#'* && ! "$case_name" =~ [[:cntrl:]] ]] || usage + case_suite="${case_name%%#*}" + case_test="${case_name#*#}" + [[ -n "$case_test" ]] || usage + suite_is_required=0 + for required_suite in "${REQUIRED_SUITES[@]}"; do + if [[ "$case_suite" == "$required_suite" ]]; then + suite_is_required=1 + break + fi + done + [[ "$suite_is_required" == "1" ]] || usage + for ((j = 0; j < i; j++)); do + [[ "$case_name" != "${REQUIRED_CASES[$j]}" ]] || usage + done + done +elif ((${#REQUIRED_SUITES[@]} > 0 || ${#REQUIRED_CASES[@]} > 0)); then + usage +fi + SERVICE_NAME="$1" SERVICE_DIR="$ROOT_DIR/services/$SERVICE_NAME" @@ -40,7 +99,7 @@ if [[ ! -d "$SERVICE_DIR" ]]; then exit 1 fi -python3 - "$SERVICE_DIR" <<'PY' +python3 - "$SERVICE_DIR" "$STRICT_MODE" "${REQUIRED_SUITES[@]}" --required-cases "${REQUIRED_CASES[@]}" <<'PY' from __future__ import annotations import datetime as dt @@ -50,9 +109,213 @@ from collections import defaultdict from pathlib import Path service_dir = Path(sys.argv[1]) +strict_mode = sys.argv[2] == "1" +case_separator = sys.argv.index("--required-cases", 3) +required_suites = sys.argv[3:case_separator] +required_cases = sys.argv[case_separator + 1 :] service_name = service_dir.name result_root = service_dir / "build" / "test-results" + +def strict_inspection() -> None: + xml_files = sorted(result_root.glob("**/TEST-*.xml")) if result_root.exists() else [] + malformed_reports = 0 + parsed_suite_count = 0 + parsed_test_count = 0 + suite_reports: dict[str, list[dict[str, object]]] = defaultdict(list) + required_suite_set = set(required_suites) + + def non_negative_count(value: str | None) -> int | None: + if value is None or not value.isascii() or not value.isdecimal(): + return None + try: + count = int(value) + except ValueError: + return None + return count if count >= 0 else None + + for xml_file in xml_files: + try: + root = ET.parse(xml_file).getroot() + except (ET.ParseError, OSError, ValueError): + malformed_reports += 1 + continue + + if root.tag == "testsuite": + suites = [root] + elif root.tag == "testsuites": + suites = list(root.findall(".//testsuite")) + else: + malformed_reports += 1 + continue + + if not suites: + malformed_reports += 1 + continue + + file_is_malformed = False + file_suites: list[dict[str, object]] = [] + for suite in suites: + suite_name = suite.attrib.get("name") + tests = non_negative_count(suite.attrib.get("tests")) + failures = non_negative_count(suite.attrib.get("failures")) + errors = non_negative_count(suite.attrib.get("errors")) + skipped = non_negative_count(suite.attrib.get("skipped")) + disabled = non_negative_count(suite.attrib.get("disabled", "0")) + testcases = list(suite.findall("./testcase")) + + if ( + not suite_name + or tests is None + or failures is None + or errors is None + or skipped is None + or disabled is None + or tests != len(testcases) + ): + file_is_malformed = True + + parsed_cases: list[dict[str, object]] = [] + for testcase in testcases: + classname = testcase.attrib.get("classname") + name = testcase.attrib.get("name") + if not classname or not name: + file_is_malformed = True + continue + parsed_cases.append( + { + "identity": f"{classname}#{name}", + "failed": bool(testcase.findall("./failure")), + "errored": bool(testcase.findall("./error")), + "skipped": bool(testcase.findall("./skipped")), + } + ) + + suite_info: dict[str, object] = { + "name": suite_name, + "tests": tests, + "failures": failures, + "errors": errors, + "skipped": skipped, + "disabled": disabled, + "cases": parsed_cases, + } + file_suites.append(suite_info) + + if file_is_malformed: + malformed_reports += 1 + continue + + parsed_suite_count += len(file_suites) + parsed_test_count += sum(int(suite["tests"]) for suite in file_suites) + for suite in file_suites: + suite_name = str(suite["name"]) + if suite_name in required_suite_set: + suite_reports[suite_name].append(suite) + + problems: list[str] = [] + suite_status: dict[str, tuple[str, dict[str, object] | None]] = {} + for suite_name in required_suites: + matches = suite_reports.get(suite_name, []) + if not matches: + suite_status[suite_name] = ("missing", None) + problems.append(f"Missing required suite: {suite_name}") + continue + if len(matches) != 1: + suite_status[suite_name] = ("duplicate", None) + problems.append(f"Duplicate required suite: {suite_name} ({len(matches)} report(s))") + continue + + suite = matches[0] + suite_status[suite_name] = ("passed", suite) + if int(suite["tests"]) == 0: + suite_status[suite_name] = ("zero tests", suite) + problems.append(f"Required suite has zero tests: {suite_name}") + elif ( + int(suite["failures"]) > 0 + or int(suite["errors"]) > 0 + or int(suite["skipped"]) > 0 + or int(suite["disabled"]) > 0 + or any( + bool(case["failed"]) or bool(case["errored"]) or bool(case["skipped"]) + for case in suite["cases"] + ) + ): + suite_status[suite_name] = ("failed or skipped", suite) + problems.append(f"Required suite is failing, errored, or skipped: {suite_name}") + + for case_spec in required_cases: + case_suite, _ = case_spec.split("#", 1) + suite = suite_status[case_suite][1] + matching_cases = ( + [case for case in suite["cases"] if case["identity"] == case_spec] + if suite is not None + else [] + ) + if not matching_cases: + problems.append(f"Missing required case: {case_spec}") + continue + if len(matching_cases) != 1: + problems.append(f"Duplicate required case: {case_spec} ({len(matching_cases)} execution(s))") + continue + case = matching_cases[0] + if bool(case["failed"]) or bool(case["errored"]) or bool(case["skipped"]): + problems.append(f"Required case did not pass: {case_spec}") + + print("Strict JUnit proof: passed" if not problems and malformed_reports == 0 else "Strict JUnit proof: failed") + print( + f"Reports: {len(xml_files)}; suites: {parsed_suite_count}; tests: {parsed_test_count}; " + f"malformed reports: {malformed_reports}" + ) + + for suite_name in required_suites: + status, suite = suite_status[suite_name] + if suite is None: + print(f"Suite {suite_name}: outcome={status}") + else: + print( + f"Suite {suite_name}: tests={suite['tests']} skipped={int(suite['skipped']) + int(suite['disabled'])} " + f"failures={suite['failures']} errors={suite['errors']} outcome={status}" + ) + + for case_spec in required_cases: + case_suite, _ = case_spec.split("#", 1) + suite = suite_status[case_suite][1] + matching_cases = ( + [case for case in suite["cases"] if case["identity"] == case_spec] + if suite is not None + else [] + ) + if not matching_cases: + outcome = "missing" + elif len(matching_cases) != 1: + outcome = "duplicate" + elif bool(matching_cases[0]["failed"]): + outcome = "failure" + elif bool(matching_cases[0]["errored"]): + outcome = "error" + elif bool(matching_cases[0]["skipped"]): + outcome = "skipped" + else: + outcome = "passed" + print(f"Case {case_spec}: executions={len(matching_cases)} outcome={outcome}") + + if malformed_reports > 0: + problems.append(f"Malformed report(s): {malformed_reports}") + for problem in problems: + print(f"- {problem}") + + if not xml_files: + print("No JUnit XML reports were found.") + raise SystemExit(1) + if problems: + raise SystemExit(1) + + +if strict_mode: + strict_inspection() + raise SystemExit(0) + if not result_root.exists(): print(f"Service: {service_name}") print("No build/test-results directory exists yet.") From f1fb74d28988660d5703a1f8a96758e0abc3dcec Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:58:11 +1300 Subject: [PATCH 06/17] Adapt recovery fixture to strict proof and retain Redis recurrence --- design/project-management/ai-observations.md | 1 + .../gradle-dependency-recovery-contract.sh | 40 ++++++++++++++++++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 75cb8eca99..81ded0fb68 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -55,6 +55,7 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-03` (Pacific/Auckland): Physical issuer retirement lost a fresh Redis connection before mutation. - #3382 substantive Validation run [41474380442](https://github.com/benhook1013/FireMUD/actions/runs/41474380442), Game Session partition 1, passed 85 of 86 physical cases; `retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound` failed at its release step because a newly opened Lettuce connection disconnected before `ACL WHOAMI`. No Redis mutation was dispatched by that attempt. The unchanged complete case passed locally in proof160 (93.841s); this does not establish the remote cause or completed remote improvement from the separately qualified PostgreSQL fixture pool. Source inspection found no intentional in-test shutdown or ACL change. Next: on a natural recurrence, retain Redis container health/logs and the exact turnover iteration alongside connection events; preserve fail-closed handling and the full history-bound proof. Reported to Overseer; no reconnect, blind mutation retry, assertion reduction or production workaround was added. + - Recurrence on `2026-11-17` (UTC): #3439 [Validation 44102622792](https://github.com/benhook1013/FireMUD/actions/runs/44102622792), Game Session partition 1, reports the same pre-mutation `ACL WHOAMI` disconnection in issuer physical retirement and `originRecoveryUsesTheTwoBackgroundSlotsAndTheFourOperationCeiling` (126 of 128 physical cases passed). Both unchanged complete suites then passed 25 local PostgreSQL/Redis cases in 6m17s with zero failures, errors or skips. The exact remote connection cause remains unproved; this is not a fixed-transport or passing-remote-suite claim. Failed CI logs and fresh raw local XML are retained. No production reconnect, retry, timeout, ACL or assertion relaxation was introduced; preserve the existing container/lifecycle evidence follow-up. - `2026-11-03` (Pacific/Auckland): GitHub job-log connector closes transport during CI failure inspection. - Repeated per-job connector requests failed with `Transport closed` for #3386 Validation and #3388 World/Python jobs while other metadata reads worked. One later #3388 per-job request succeeded during an active workflow, without explaining the failures; whole-run `gh run view --log` still refused before completion. Both #3389 Account jobs `125829036896` / `125829037055` recurred. Read-only per-job `gh api` log retrieval recovered their bytes into private files; any ANSI-capable retrieval must write directly to the private file rather than a terminal. Cause remains unknown. Next: preserve exact request/transport diagnostics on recurrence and repair the connector; do not rerun CI or replace controller operations to recover logs. diff --git a/dev-tools/tests/gradle-dependency-recovery-contract.sh b/dev-tools/tests/gradle-dependency-recovery-contract.sh index 6311ba52c9..7fce1fcb53 100644 --- a/dev-tools/tests/gradle-dependency-recovery-contract.sh +++ b/dev-tools/tests/gradle-dependency-recovery-contract.sh @@ -763,18 +763,54 @@ write_buildsrc_wrapper() { exit 1 fi echo buildsrc-refresh-result +if [[ "${BUILDSRC_REFRESH_EXIT:-0}" -eq 0 && -f "$CASE_DIR/emit-required-logging-proof.py" ]]; then + python3 "$CASE_DIR/emit-required-logging-proof.py" +fi exit "${BUILDSRC_REFRESH_EXIT:-0}"' } new_case captured-buildsrc-429 +# Successful recovery still owes the real module runner's required current proof. +# Emit XML only inside the inert successful Gradle invocation, after stale XML invalidation. +cp "$ROOT_DIR/dev-tools/validation/inspect-test-results.sh" \ + "$CASE_DIR/dev-tools/validation/inspect-test-results.sh" +cat > "$CASE_DIR/emit-required-logging-proof.py" <<'PROOF' +import os +from pathlib import Path +import xml.etree.ElementTree as ET + +suites = { + "net.firedevops.firemud.loggingadmin.ModerationAccountUuidMigrationPostgresIntegrationTest": [ + "emptySchemaMigratesAndKeepsExactUuidWithoutChangingPolicyFields()", + "populatedLegacyRowsBlockMigrationWithoutChangingRowsOrMigrationHistory()", + "concurrentModerationWriterBlocksMigrationThenItsCommittedRowForcesRefusal()", + ], + "net.firedevops.firemud.loggingadmin.ReportAccountUuidMigrationPostgresIntegrationTest": [ + "freshSchemaMigratesWithCanonicalAccountUuidsAndNumericLocalIdentifiers()", + "emptyAffectedTablesUpgradeFromV1007AndGenericLogAccountIdRemainsNumeric()", + "existingCanonicalModerationRowsAreUntouchedByReportOnlyMigration()", + "retainedPlayerReportRefusesWithoutChangingRowsOrMigrationHistory()", + "migrationWaitsForConcurrentWriterAndRefusesAfterItsRowCommits()", + ], +} +reports = Path(os.environ["CASE_DIR"]) / "services/logging-admin-service/build/test-results/integrationTest" +reports.mkdir(parents=True, exist_ok=True) +for index, (suite, cases) in enumerate(suites.items()): + root = ET.Element("testsuite", name=suite, tests=str(len(cases)), + failures="0", errors="0", skipped="0") + for case in cases: + ET.SubElement(root, "testcase", classname=suite, name=case) + ET.ElementTree(root).write(reports / f"TEST-{index}.xml") +PROOF write_buildsrc_429_cause write_buildsrc_wrapper run_case logging-admin-service 0 assert_call_count 2 -assert_call 1 "--max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :logging-admin-service:check -PfullCheck --profile --info --console=plain" -assert_call 2 "--refresh-dependencies --max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :logging-admin-service:check -PfullCheck --profile --info --console=plain" +assert_call 1 "--max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :logging-admin-service:check -PfullCheck --no-build-cache --no-configuration-cache :logging-admin-service:integrationTest --rerun --profile --info --console=plain" +assert_call 2 "--refresh-dependencies --max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :logging-admin-service:check -PfullCheck --no-build-cache --no-configuration-cache :logging-admin-service:integrationTest --rerun --profile --info --console=plain" [[ "$(cat "$CASE_DIR/sleeps")" == 2 ]] || fail "buildSrc HTTP 429 did not use one short delay" assert_output_contains "buildsrc-refresh-result" +assert_output_contains "Strict JUnit proof: passed" # Auth, policy and conflict responses remain final, including mixed failures # where the other dependency really did encounter a retryable HTTP 429. From c3a7166d67baac671318d7171085c685aa7069e9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:00:39 +1300 Subject: [PATCH 07/17] Close Game Design test contexts at container class boundaries --- design/project-management/ai-observations.md | 3 +++ .../data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java | 2 ++ .../gamedesign/GameDesignApplicationIntegrationTest.java | 2 ++ .../firemud/gamedesign/data/TestDataSeederIntegrationTest.java | 2 ++ .../VersionAssetArtifactRepositoryIntegrationTest.java | 2 ++ .../service/CompleteLaunchBindingServiceIntegrationTest.java | 2 ++ .../service/LaunchDescriptorServiceIntegrationTest.java | 2 ++ .../PublishAttemptServiceTransactionIntegrationTest.java | 2 ++ .../service/SettingsAuthorityServiceIntegrationTest.java | 2 ++ 9 files changed, 19 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 81ded0fb68..a14139e833 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -69,3 +69,6 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-04` (Pacific/Auckland): Game Session mapped PostgreSQL connection refused despite healthy container. - Local #3386 proof423 passed 100 actual cases but failed `CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest` in its existing 60-second JDBC-readiness guard before migration. The captured container was running, not OOM-killed, listening on 5432, and returned `1` from internal `SELECT 1`; Docker reported the expected IPv4/IPv6 port bindings, while JDBC to resolved `127.0.0.1:49634` refused connections. Full failure, container diagnostics and XML are retained. This does not identify the daemon or host forwarding cause. Next: on recurrence capture host-side mapped-port listeners and routing beside the existing bounded container diagnostics before teardown; preserve the original failure and qualify the affected fixture independently. Do not weaken readiness, skip Docker proof or add production retries. + +- `2026-11-17` (UTC): Game Design full CI reached its 30-minute job envelope after completing integration tests. + - On #3439 at `f1fb74d289`, Validation run `44121153249` job `134172790844` completed the integration-test task and continued through coverage/static analysis before cancellation at the configured 30-minute limit. No failed-test marker was found in the retained log. Background Hikari reconnections to a stopped class-scoped PostgreSQL container are a distinct test-context lifecycle issue; correcting that cleanup does not establish the cause or recovery of the complete job timeout. Next: retain the next natural exact-head module timing and terminal proof, then evaluate its execution/partition envelope without disabling tests, weakening checks or silently increasing the limit. diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java index bef6b7876e..c6aae5cca4 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java @@ -66,6 +66,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.PlatformTransactionManager; import org.testcontainers.containers.PostgreSQLContainer; @@ -73,6 +74,7 @@ import org.testcontainers.junit.jupiter.Testcontainers; @Testcontainers(disabledWithoutDocker = true) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @SpringBootTest( classes = GameDesignServiceApplication.class, properties = { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/GameDesignApplicationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/GameDesignApplicationIntegrationTest.java index 42e30de139..2ff9655d55 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/GameDesignApplicationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/GameDesignApplicationIntegrationTest.java @@ -20,6 +20,7 @@ import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.annotation.Import; import org.springframework.http.HttpHeaders; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.testcontainers.containers.PostgreSQLContainer; @@ -27,6 +28,7 @@ import org.testcontainers.junit.jupiter.Testcontainers; @Testcontainers(disabledWithoutDocker = true) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, classes = GameDesignServiceApplication.class, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index a924b10f07..4112cc55c1 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -75,6 +75,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronization; @@ -85,6 +86,7 @@ import tools.jackson.databind.ObjectMapper; @Testcontainers(disabledWithoutDocker = true) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @SpringBootTest( classes = GameDesignServiceApplication.class, properties = { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java index 2cb21f484c..1b596c26ef 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java @@ -13,6 +13,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.testcontainers.containers.PostgreSQLContainer; @@ -20,6 +21,7 @@ import org.testcontainers.junit.jupiter.Testcontainers; @Testcontainers(disabledWithoutDocker = true) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @SpringBootTest( classes = GameDesignServiceApplication.class, properties = { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java index 3d60831180..b614a2580d 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java @@ -58,6 +58,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.transaction.PlatformTransactionManager; @@ -71,6 +72,7 @@ /** PostgreSQL proof for the immutable descriptor/release pair read from one owner snapshot. */ @Testcontainers(disabledWithoutDocker = true) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @SpringBootTest( classes = GameDesignServiceApplication.class, properties = { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 5667af98f1..8733102117 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -56,6 +56,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.util.ReflectionTestUtils; @@ -67,6 +68,7 @@ import tools.jackson.databind.ObjectMapper; @Testcontainers(disabledWithoutDocker = true) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @SpringBootTest( classes = GameDesignServiceApplication.class, properties = { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index c62ea5bb7d..0d14be6cd8 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -63,6 +63,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; @@ -81,6 +82,7 @@ * public-ingress denial. */ @Testcontainers(disabledWithoutDocker = true) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @SpringBootTest( classes = GameDesignServiceApplication.class, properties = { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java index a1ea37a2a8..04cd38fc4b 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java @@ -18,6 +18,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.transaction.PlatformTransactionManager; @@ -27,6 +28,7 @@ import org.testcontainers.junit.jupiter.Testcontainers; @Testcontainers(disabledWithoutDocker = true) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @SpringBootTest( classes = GameDesignServiceApplication.class, properties = { From a900ac414df4da5bb7b7ce876791d1de2b4fb7c8 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 18 Nov 2026 08:23:07 +1300 Subject: [PATCH 08/17] Enforce final ONLINE and RECENT friend disclosure Receive bounded donor #2975 privacy filtering without widening ALL/detail behavior. Preserve roster totals and remove presence-count ratios from filtered text. Qualified exact tree with Java25/Gradle9.9: 97 focused tests passed (16 new disclosure cases), canonical formatting and compilation. Cloud test JVM used supported Mockito startup agent; no production build configuration change. Full donor and runtime qualification remain incomplete. --- .../command/text/FriendsCommandHandler.java | 23 +- .../TextPlayerOutputRenderer.java | 10 + .../text/FriendsCommandHandlerTest.java | 10 +- .../text/FriendsFilteredDisclosureTest.java | 208 ++++++++++++++++++ 4 files changed, 247 insertions(+), 4 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsFilteredDisclosureTest.java 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 56d2c3adb3..9dc69824d5 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 @@ -481,15 +481,32 @@ private FriendPresenceViewOutput toView(ListFriendsResponse response, FriendList return toEntry(ordinal, entry); }) .toList(); + boolean disclosureFiltered = + filter == FriendListFilter.ONLINE || filter == FriendListFilter.RECENT; boolean canonicalFiltered = filter == FriendListFilter.ALL || response.getFilter() == mapRosterFilter(filter) || response.getMatchCount() > 0 || response.getTotalCount() > 0; - List mapped = - canonicalFiltered ? allEntries : allEntries.stream().filter(filter::matches).toList(); + List mapped; + if (disclosureFiltered) { + mapped = + allEntries.stream() + .filter( + entry -> + "PUBLIC".equals(entry.visibilityPolicy()) + || "FRIENDS_ONLY".equals(entry.visibilityPolicy())) + .filter(filter::matches) + .toList(); + } else { + mapped = + canonicalFiltered ? allEntries : allEntries.stream().filter(filter::matches).toList(); + } int totalCount = response.getTotalCount() > 0 ? response.getTotalCount() : allEntries.size(); - int matchCount = response.getMatchCount() > 0 ? response.getMatchCount() : mapped.size(); + int matchCount = + disclosureFiltered + ? mapped.size() + : response.getMatchCount() > 0 ? response.getMatchCount() : mapped.size(); return new FriendPresenceViewOutput(filter.name(), totalCount, matchCount, mapped); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java index 0c6bf6e041..d4f25fcf32 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java @@ -457,6 +457,13 @@ private String renderFriendsView(FriendPresenceViewOutput output) { if (output.friends().isEmpty() && "ALL".equalsIgnoreCase(output.filter())) { return "Friends [0]: no linked friends. Use FRIENDS ADD ."; } + boolean disclosureFiltered = + "ONLINE".equalsIgnoreCase(output.filter()) || "RECENT".equalsIgnoreCase(output.filter()); + if (output.friends().isEmpty() && disclosureFiltered) { + return "Friends " + + output.filter().toUpperCase(java.util.Locale.ROOT) + + ": no matching friends."; + } if (output.friends().isEmpty()) { return "Friends " + output.filter().toUpperCase(java.util.Locale.ROOT) @@ -481,6 +488,9 @@ private String renderFriendsView(FriendPresenceViewOutput output) { if ("ALL".equalsIgnoreCase(output.filter())) { return body; } + if (disclosureFiltered) { + return "Friends " + output.filter().toUpperCase(java.util.Locale.ROOT) + ":\n" + body; + } return "Friends " + output.filter().toUpperCase(java.util.Locale.ROOT) + " [" 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 018ecb9cc1..72d8e4ef96 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 @@ -394,6 +394,10 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { FriendPresenceEntry.newBuilder() .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) + .setVisibilityPolicy( + net.firedevops.firemud.socialgroups.v1 + .FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC) .setCharacterName("Sora") .build()) .build()) @@ -416,7 +420,7 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Friends ONLINE [1/2]:") + .contains("Friends ONLINE:") .contains("1) Sora [acct #" + FRIEND_ACCOUNT_ID + "] - online"); Mockito.verify(socialGroupsClient) .listFriends(1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); @@ -558,6 +562,10 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { FriendPresenceEntry.newBuilder() .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(false) + .setVisibilityPolicy( + net.firedevops.firemud.socialgroups.v1 + .FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_FRIENDS_ONLY) .setLastSeenAtMs( Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) .build()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsFilteredDisclosureTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsFilteredDisclosureTest.java new file mode 100644 index 0000000000..c98c4f9516 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsFilteredDisclosureTest.java @@ -0,0 +1,208 @@ +package net.firedevops.firemud.gamesession.command.text; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.ObjectMapper; +import net.firedevops.firemud.gamesession.client.EntityManagementClient; +import net.firedevops.firemud.gamesession.client.SocialGroupsClient; +import net.firedevops.firemud.gamesession.presentation.FriendPresenceViewOutput; +import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; +import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; +import net.firedevops.firemud.gamesession.service.SessionContext; +import net.firedevops.firemud.socialgroups.v1.FriendPresenceEntry; +import net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy; +import net.firedevops.firemud.socialgroups.v1.FriendRosterEntry; +import net.firedevops.firemud.socialgroups.v1.FriendRosterFilter; +import net.firedevops.firemud.socialgroups.v1.ListFriendsResponse; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.mockito.Mockito; + +class FriendsFilteredDisclosureTest { + private static final String CALLER_ACCOUNT_ID = "a0000000-0000-4000-8000-000000000041"; + private static final String OTHER_FRIEND_ACCOUNT_ID = "c0000000-0000-4000-8000-000000000088"; + + private static final SessionContext GAMEPLAY_CONTEXT = + new SessionContext( + 7L, + 1L, + CALLER_ACCOUNT_ID, + "demo@example.com", + 99L, + "Emberline", + 7L, + "R-1", + null, + null, + 7L, + "demo", + "production", + 1L, + "SHARED"); + + private FriendsCommandHandler newHandler( + SocialGroupsClient socialGroupsClient, + EntityManagementClient entityManagementClient, + ScriptEventPublisher scriptEventPublisher) { + return new FriendsCommandHandler( + socialGroupsClient, entityManagementClient, scriptEventPublisher); + } + + @ParameterizedTest + @CsvSource({ + "ONLINE,PRIVATE", "RECENT,PRIVATE", + "ONLINE,MISSING", "RECENT,MISSING", + "ONLINE,UNKNOWN", "RECENT,UNKNOWN" + }) + void nonDisclosableMatchesCannotRevealPresence(String filter, String policy) throws Exception { + FriendPresenceViewOutput view = + render( + filter, roster(filter, 1, entry(2, OTHER_FRIEND_ACCOUNT_ID, filter, policy, "Secret"))); + + assertThat(view.filter()).isEqualTo(filter); + assertThat(view.totalCount()).isEqualTo(20); + assertThat(view.matchCount()).isZero(); + assertThat(view.friends()).isEmpty(); + String json = new ObjectMapper().writeValueAsString(view); + assertThat(json).doesNotContain("Secret", OTHER_FRIEND_ACCOUNT_ID, "1744336000000"); + assertThat(new ObjectMapper().readTree(json).path("matchCount").asInt()).isZero(); + assertThat(text(view)) + .isEqualTo("Friends " + filter + ": no matching friends.") + .doesNotContain("[", "Secret", OTHER_FRIEND_ACCOUNT_ID); + } + + @ParameterizedTest + @CsvSource({ + "ONLINE,PUBLIC,true", "RECENT,PUBLIC,true", + "ONLINE,FRIENDS_ONLY,true", "RECENT,FRIENDS_ONLY,true", + "ONLINE,PUBLIC,false", "RECENT,FRIENDS_ONLY,false" + }) + void mixedRowsKeepOnlyDisclosedMatchesAndOriginalOrdinals( + String filter, String policy, boolean matchingMetadata) throws Exception { + String visible = "d0000000-0000-4000-8000-000000000099"; + String wrongState = "e0000000-0000-4000-8000-000000000100"; + ListFriendsResponse response = + roster( + matchingMetadata ? filter : "ALL", + 19, + entry(2, OTHER_FRIEND_ACCOUNT_ID, filter, "PRIVATE", "Secret"), + entry(7, visible, filter, policy, "Visible"), + entry(9, wrongState, "ONLINE".equals(filter) ? "RECENT" : "ONLINE", policy, "Wrong")); + FriendPresenceViewOutput view = render(filter, response); + + assertThat(view.totalCount()).isEqualTo(20); + assertThat(view.matchCount()).isEqualTo(1); + assertThat(view.friends()) + .singleElement() + .satisfies( + value -> { + assertThat(value.ordinal()).isEqualTo(7); + assertThat(value.friendAccountId()).isEqualTo(visible); + }); + String json = new ObjectMapper().writeValueAsString(view); + assertThat(json) + .contains(visible) + .doesNotContain("Secret", "Wrong", OTHER_FRIEND_ACCOUNT_ID, wrongState); + assertThat(new ObjectMapper().readTree(json).path("friends").size()).isEqualTo(1); + assertThat(text(view)) + .startsWith("Friends " + filter + ":\n7) Visible") + .doesNotContain("[19/20]", "[1/20]", "Secret", "Wrong"); + } + + @ParameterizedTest + @CsvSource({"ALL", "PRIVATE", "SHARED", "OFFLINE"}) + void unrelatedFiltersKeepExistingMetadataAndEmptyText(String filter) { + FriendPresenceViewOutput view = render(filter, roster(filter, 19)); + assertThat(view.totalCount()).isEqualTo(20); + assertThat(view.matchCount()).isEqualTo(19); + assertThat(view.friends()).isEmpty(); + assertThat(text(view)) + .isEqualTo( + "ALL".equals(filter) + ? "Friends [0]: no linked friends. Use FRIENDS ADD ." + : "Friends " + filter + " [0/20]: no matching friends."); + } + + private FriendPresenceViewOutput render(String filter, ListFriendsResponse response) { + SocialGroupsClient social = Mockito.mock(SocialGroupsClient.class); + FriendRosterFilter requested = rosterFilter(filter); + if ("ALL".equals(filter)) { + when(social.listFriends(1L, CALLER_ACCOUNT_ID)).thenReturn(response); + } else { + when(social.listFriends(1L, CALLER_ACCOUNT_ID, requested)).thenReturn(response); + } + FriendsCommandHandler handler = + newHandler( + social, + Mockito.mock(EntityManagementClient.class), + Mockito.mock(ScriptEventPublisher.class)); + TextCommandInterpretationResult result = + handler.handle( + new TextCommand( + TextCommandType.FRIENDS, java.util.List.of(filter), "FRIENDS " + filter), + GAMEPLAY_CONTEXT); + assertThat(result.commandResult().accepted()).isTrue(); + if ("ALL".equals(filter)) { + Mockito.verify(social).listFriends(1L, CALLER_ACCOUNT_ID); + } else { + Mockito.verify(social).listFriends(1L, CALLER_ACCOUNT_ID, requested); + } + return (FriendPresenceViewOutput) result.outputs().getFirst().payload(); + } + + private static FriendRosterFilter rosterFilter(String filter) { + return switch (filter) { + case "ONLINE" -> FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE; + case "RECENT" -> FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT; + case "PRIVATE" -> FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE; + case "SHARED" -> FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED; + case "OFFLINE" -> FriendRosterFilter.FRIEND_ROSTER_FILTER_OFFLINE; + default -> FriendRosterFilter.FRIEND_ROSTER_FILTER_ALL; + }; + } + + private static ListFriendsResponse roster( + String filter, int count, FriendRosterEntry... entries) { + return ListFriendsResponse.newBuilder() + .setFilter(rosterFilter(filter)) + .setTotalCount(20) + .setMatchCount(count) + .addAllFriends(java.util.List.of(entries)) + .build(); + } + + private static FriendRosterEntry entry( + int ordinal, String id, String state, String policy, String name) { + var presence = + FriendPresenceEntry.newBuilder() + .setFriendAccountId(id) + .setOnline("ONLINE".equals(state)) + .setLastSeenAtMs(1_744_336_000_000L) + .setCharacterName(name); + switch (policy) { + case "PUBLIC" -> + presence.setVisibilityPolicy( + FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC); + case "FRIENDS_ONLY" -> + presence.setVisibilityPolicy( + FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_FRIENDS_ONLY); + case "PRIVATE" -> + presence.setVisibilityPolicy( + FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); + case "UNKNOWN" -> presence.setVisibilityPolicyValue(999); + default -> {} + } + return FriendRosterEntry.newBuilder() + .setOrdinal(ordinal) + .setFriendAccountId(id) + .setPresence(presence) + .build(); + } + + private static String text(FriendPresenceViewOutput view) { + return new TextPlayerOutputRenderer( + new net.firedevops.firemud.gamesession.config.PresentationProperties()) + .render(net.firedevops.firemud.gamesession.presentation.PlayerOutput.view(view)); + } +} From 82eb126926b0ea2c1b76b2750dfe838aae679d75 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 18 Nov 2026 08:36:23 +1300 Subject: [PATCH 09/17] Correlate profile updates with verified Account owner echoes Receive bounded donor #2975 profile response identity contract across proto, Account producer and Social consumer. Preserve fail-closed identity checks; errors emit no owner echo. Account must roll out to all replicas before enforcing Social; rollback Social first. Legacy success-only responses fail closed even after a persisted write. No runtime activation performed. Canonical exact-toolchain generated compilation/formatting and 183 focused tests passed; independent source/result review accepted. Full donor accounting and runtime qualification remain incomplete. --- .../account-service/api-contracts.md | 2 + protos/account/v1/account_service.proto | 3 + .../service/impl/AccountGrpcService.java | 7 ++- .../service/impl/AccountGrpcServiceTest.java | 42 ++++++++++++++ .../socialgroups/client/AccountClient.java | 5 +- .../client/AccountClientTest.java | 57 +++++++++++++++++++ 6 files changed, 114 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 4d3906bd93..a38bcdeabd 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -239,6 +239,8 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `GetProfile` – retrieves the caller's profile relationship through canonical `GET /tenants/{tenantId}/profiles/{accountId}`, classified `tenant_regular`. Caller subject, scoped-role, and membership-generation validation follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. - `UpdateProfile` – modifies the caller's profile relationship through canonical `PUT /tenants/{tenantId}/profiles/{accountId}` under the same `tenant_regular` authorization and caller-subject binding. Membership authority follows [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the local API triggers notification emails. The response projection returns `PRIVATE` for a retained legacy `HIDDEN_STAFF` value without rewriting the stored row; normative policy remains in [ADR 0046](../../decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). The legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. +Successful gRPC `UpdateProfile` responses echo `account_id` and `tenant_id` from the verified persisted profile. Social accepts success only when both echoes exactly match the requested canonical Account UUID and tenant selector; missing or mismatched echoes fail closed. Error responses do not echo an identity. Deploy the echo-producing Account version to every replica before deploying the enforcing Social consumer, or deploy them together with traffic held until both are ready. For rollback, roll back Social first. A new Social consumer paired with an old Account producer rejects the old success-only response even though the write may already have persisted; do not treat that combination as supported rolling compatibility. + - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. - `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response. Each refusal is bound to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 0d5cc807cb..e129987d53 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -304,6 +304,9 @@ message UpdateProfileRequest { message UpdateProfileResponse { bool success = 1; shared.v1.ErrorDetail error = 2; + // Successful writes echo the exact persisted Account UUID and tenant selector. + string account_id = 3; + string tenant_id = 4; } message ExportAccountRequest { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index a0addcc784..67dec7e57c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -978,7 +978,12 @@ public void updateProfile( || !Long.valueOf(tenantId).equals(dto.tenantId())) { throw new IllegalStateException("Profile authority returned a different owner"); } - UpdateProfileResponse response = UpdateProfileResponse.newBuilder().setSuccess(true).build(); + UpdateProfileResponse response = + UpdateProfileResponse.newBuilder() + .setSuccess(true) + .setAccountId(dto.accountId()) + .setTenantId(dto.tenantId().toString()) + .build(); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 3aae3e801b..cf50309102 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -2844,6 +2844,8 @@ void updateProfileResolvesUuidOwnerAfterCallerCheck(String policyName) { observer)); assertTrue(observer.response().getSuccess()); + assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); + assertEquals("1", observer.response().getTenantId()); org.mockito.ArgumentCaptor requestCaptor = org.mockito.ArgumentCaptor.forClass( @@ -2857,6 +2859,46 @@ void updateProfileResolvesUuidOwnerAfterCallerCheck(String policyName) { requestCaptor.getValue().presenceVisibilityPolicy()); } + @ParameterizedTest + @ValueSource(strings = {"null", "account", "tenant"}) + void updateProfileRejectsInvalidAuthorityOwnerWithoutEcho(String mismatch) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + UUID accountUuid = UUID.fromString(ACCOUNT_UUID); + Mockito.when(accountService.resolveAccountStorageId(accountUuid)).thenReturn(2L); + var result = + "null".equals(mismatch) + ? null + : new net.firedevops.firemud.accountservice.dto.ProfileDto( + 1L, + "tenant".equals(mismatch) ? 2L : 1L, + "account".equals(mismatch) ? "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa" : ACCOUNT_UUID, + "demo", + "bio", + ProfilePresenceVisibilityPolicy.PRIVATE); + Mockito.when(accountService.updateProfile(Mockito.any())).thenReturn(result); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + RecordingObserver observer = new RecordingObserver<>(); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); + assertFalse(observer.response().getSuccess()); + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals("", observer.response().getAccountId()); + assertEquals("", observer.response().getTenantId()); + Mockito.verify(accountService).updateProfile(Mockito.any()); + } + @Test void updateProfileErrorReturnsDetail() { PingService pingService = Mockito.mock(PingService.class); diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/AccountClient.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/AccountClient.java index 66ea9ad302..58aaf0d525 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/AccountClient.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/AccountClient.java @@ -169,7 +169,10 @@ public boolean updatePresenceVisibilityPolicy( snapshot.displayName(), snapshot.bio(), visibilityPolicy.name()) .toJson()) .build()); - return response.getSuccess() && !response.hasError(); + return response.getSuccess() + && !response.hasError() + && accountId.equals(response.getAccountId()) + && Long.toString(tenantId).equals(response.getTenantId()); } catch (Exception ex) { logger.warn( "Failed to update account presence visibility policy tenantId={} accountId={} policy={}", diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java index 255cd39820..2d31fb0c5a 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java @@ -31,6 +31,8 @@ import net.firedevops.firemud.socialgroups.dto.FriendPresenceVisibilityPolicyValue; import net.firedevops.firemud.socialgroups.test.AccountUuidFixtures; 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.slf4j.LoggerFactory; @@ -275,6 +277,8 @@ void missingPersistedProfilePolicyStaysPrivateAndCanonicalSelfUpdatePreservesPro .thenReturn( net.firedevops.firemud.account.v1.UpdateProfileResponse.newBuilder() .setSuccess(true) + .setAccountId(accountUuid(1L)) + .setTenantId("11") .build()); var client = newClient(stub); assertThat(client.getPresenceVisibilityPolicy(11L, accountUuid(1L))) @@ -382,6 +386,57 @@ void laterPolicyBatchFailureRedactsEarlierSuccessfulBatch() throws Exception { assertThat(calls.get()).isEqualTo(2); } + @ParameterizedTest + @ValueSource( + strings = { + "account", + "empty-account", + "numeric-account", + "nil-account", + "tenant", + "empty-tenant", + "noncanonical-tenant", + "legacy-response" + }) + void successfulProfileUpdateRequiresExactOwnerEcho(String mismatch) throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.getProfile(any())) + .thenReturn( + net.firedevops.firemud.account.v1.GetProfileResponse.newBuilder() + .setProfileJson( + "{\"tenantId\":11,\"accountId\":\"" + + accountUuid(2L) + + "\",\"displayName\":\"Name\",\"bio\":\"Bio\",\"presenceVisibilityPolicy\":\"PUBLIC\"}") + .build()); + var response = + net.firedevops.firemud.account.v1.UpdateProfileResponse.newBuilder() + .setSuccess(true) + .setAccountId(accountUuid(2L)) + .setTenantId("11"); + switch (mismatch) { + case "account" -> response.setAccountId(accountUuid(3L)); + case "empty-account" -> response.clearAccountId(); + case "numeric-account" -> response.setAccountId("2"); + case "nil-account" -> response.setAccountId("00000000-0000-0000-0000-000000000000"); + case "tenant" -> response.setTenantId("12"); + case "empty-tenant" -> response.clearTenantId(); + case "noncanonical-tenant" -> response.setTenantId("011"); + case "legacy-response" -> { + response.clearAccountId(); + response.clearTenantId(); + } + default -> throw new IllegalArgumentException(mismatch); + } + when(stub.updateProfile(any())).thenReturn(response.build()); + var client = newClient(stub); + assertThat( + client.updatePresenceVisibilityPolicy( + 11L, accountUuid(2L), FriendPresenceVisibilityPolicyValue.PRIVATE)) + .isFalse(); + verify(stub).updateProfile(any()); + } + private static PresenceVisibilityPolicyEntry policyEntry(String accountId, String policy) { return PresenceVisibilityPolicyEntry.newBuilder() .setAccountId(accountId) @@ -405,6 +460,8 @@ void uuidProfileResponseRemainsReadableWithCanonicalRequestSelectors() throws Ex .thenReturn( net.firedevops.firemud.account.v1.UpdateProfileResponse.newBuilder() .setSuccess(true) + .setAccountId(accountUuid(2L)) + .setTenantId("11") .build()); AccountClient client = newClient(stub); assertThat(client.getPresenceVisibilityPolicy(11L, accountUuid(2L))) From c5636448d1777776d4b2072dbf1303ea1d9e4384 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 18 Nov 2026 08:46:53 +1300 Subject: [PATCH 10/17] Align cross-service friend fixture with disclosure contract Explicitly mark synthetic Sora presence PUBLIC and expect count-free ONLINE heading. Test-only correction; no weakening of production privacy filtering. Independent source review, canonical formatting and compileCrossServiceTestJava pass. Docker-backed cross-service execution is pending natural CI because cloud has no Docker runtime. --- .../CommunicationWebSocketCrossServiceTest.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) 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 207129bfd2..30b49562f1 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 @@ -226,7 +226,7 @@ void websocketFriendsOnlineFiltersCanonicalRoster() throws Exception { runCommunicationSequence( sessionId, "FRIENDS ONLINE", - "Friends ONLINE [1/1]:\n" + "Friends ONLINE:\n" + "1) Sora [acct #" + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); @@ -234,7 +234,7 @@ void websocketFriendsOnlineFiltersCanonicalRoster() throws Exception { assertThat(responses) .anyMatch( response -> - response.contains("Friends ONLINE [1/1]:") + response.contains("Friends ONLINE:") && response.contains( "1) Sora [acct #" + SORA_ACCOUNT_UUID @@ -645,6 +645,9 @@ private static synchronized void ensureTestServicesStarted() throws Exception { .addPresences( FriendPresenceEntry.newBuilder() .setFriendAccountId(SORA_ACCOUNT_UUID) + .setVisibilityPolicy( + FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC) .setOnline(true) .setCharacterId(ChatTestFixtures.PLAYER_SORA) .setCharacterName("Sora") From 22616e77a17e52887ef4568c2c5b7cb3ecb3a545 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:19:55 +1300 Subject: [PATCH 11/17] Validate Social friend roster selectors before owner reads --- .../service/impl/FriendServiceImpl.java | 6 ++--- .../service/impl/FriendServiceImplTest.java | 24 +++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java index 946b15a328..c6ad3f7460 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java @@ -81,10 +81,9 @@ public void removeFriend(long tenantId, String accountId, String friendAccountId @Timed(value = "friend.get") public Optional getFriend( long tenantId, String accountId, String friendAccountId) { + JwtClaims.requireCanonicalAccountUuid(friendAccountId, "friendAccountId"); return listFriends(tenantId, accountId, FriendRosterFilter.ALL).friends().stream() - .filter( - entry -> - entry.friendAccountId() != null && entry.friendAccountId().equals(friendAccountId)) + .filter(entry -> friendAccountId.equals(entry.friendAccountId())) .findFirst(); } @@ -147,6 +146,7 @@ public FriendRosterViewDto listFriends( private FriendRosterSnapshot loadFriendRoster( long tenantId, String accountId, FriendRosterFilter filter) { + JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); FriendRosterFilter effectiveFilter = filter; List links = accountFriendLinkRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java index f6fe1ceab5..e235ddeda1 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java @@ -9,6 +9,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.time.Instant; @@ -31,6 +32,9 @@ import net.firedevops.firemud.socialgroups.repository.AccountFriendLinkRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; class FriendServiceImplTest { @@ -449,6 +453,26 @@ void removeFriendRejectsSelfLink() { Mockito.anyLong(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); } + @ParameterizedTest + @NullAndEmptySource + @ValueSource( + strings = { + "42", + "invalid-account", + "00000000-0000-0000-0000-000000000000", + "ABCDEFAB-1234-4234-8234-ABCDEFABCDEF", + " 12345678-1234-4234-8234-123456789abc " + }) + void rejectsInvalidAccountSelectorsBeforeReadingFriendRoster(String malformed) { + String valid = accountUuid(2L); + assertThrows(IllegalArgumentException.class, () -> service.getFriend(11L, malformed, valid)); + assertThrows(IllegalArgumentException.class, () -> service.getFriend(11L, valid, malformed)); + assertThrows( + IllegalArgumentException.class, + () -> service.listFriends(11L, malformed, FriendRosterFilter.ALL)); + verifyNoInteractions(accountRepository, accountClient, gameSessionClient); + } + @Test void getFriendReturnsCanonicalRosterEntryWithEmbeddedPresence() { AccountFriendLink link = new AccountFriendLink(); From f973efe72cfca4ceda18c5e37466e775185fda04 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:31:39 +1300 Subject: [PATCH 12/17] Point report receiver status at physical migration proof --- .../player-experience-commands-and-communication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index 89261a30cd..e0cdbd9604 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -136,4 +136,4 @@ The service boundaries above summarize current ownership and implementation stat ### Old-stack report receiver preparation -The Social/Logging consolidation receiver carries the verified report UUID preparation from `433d706b` onto its current Account preparation parent, preserving the canonical forward V1008 migration and disabled report writes. Social rejects malformed, numeric, nil and noncanonical report Account identifiers before request or channel access, preserving the existing internal workload identity and downstream unavailable response. Receiving-head focused JVM proof passes 20 cases (14 Logging and six Social), with zero failures/errors. Logging integration-test compilation and affected Java formatting pass using explicit Mockito startup instrumentation. Physical migration execution and remote CI remain pending; this is not report activation or donor retirement. +The Social/Logging consolidation receiver carries the verified report UUID preparation from `433d706b` onto its current Account preparation parent, preserving the canonical forward V1008 migration and disabled report writes. Social rejects malformed, numeric, nil and noncanonical report Account identifiers before request or channel access, preserving the existing internal workload identity and downstream unavailable response. Focused JVM proof at receiving commit `b07e2065` passed 20 cases (14 Logging and six Social), with zero failures or errors. Logging integration-test compilation and affected Java formatting also passed with explicit Mockito startup instrumentation. The [platform implementation tracker](./platform-operations-and-delivery.md#operator-write-boundary-status) records the PostgreSQL proof and its scope for the report and moderation migrations. From 8be9581a097a5bd22c04659a0b67de46871d6e90 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:16:26 +1300 Subject: [PATCH 13/17] Prove retained Logging audit row images survive forward migrations --- ...oggingAdminApplicationIntegrationTest.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index 75cb52b632..10336174cf 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -396,6 +396,13 @@ void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChe + "('tenant', -9, 0, NULL, 'PAYMENT', 'retained negative tenant legacy row', " + "TIMESTAMP '2025-03-01 15:00:03')"); + // V1005 intentionally links the receipts to new projections. The remaining migrations + // must preserve those linked rows and the legacy log rows without rewriting them. + var retainedReceipts = retainedAuditRows(schema, "account_audit_receipts"); + var retainedLogs = retainedAuditRows(schema, "log_events"); + assertThat(retainedReceipts).hasSize(4); + assertThat(retainedLogs).hasSize(9); + Flyway.configure() .dataSource(dataSource) .locations("classpath:db/migration") @@ -405,6 +412,10 @@ void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChe .load() .migrate(); + assertThat(retainedAuditRows(schema, "account_audit_receipts")) + .containsExactlyElementsOf(retainedReceipts); + assertThat(retainedAuditRows(schema, "log_events")).containsExactlyElementsOf(retainedLogs); + assertThat( dsl.fetchSingle( "SELECT COUNT(*) FROM " + schema + ".log_events WHERE message = ?", @@ -832,6 +843,16 @@ private void seedPreProjectionReceipt( minimized ? "NON_REPLAYABLE" : "ACCEPTED"); } + private List retainedAuditRows(String schema, String table) { + return dsl.fetch( + "SELECT jsonb_build_array(to_jsonb(retained), retained.xmin::text)::text FROM " + + schema + + "." + + table + + " AS retained ORDER BY retained.id") + .getValues(0, String.class); + } + private void assertBackfilledReceipt( String schema, String receiptId, From 37212a10d270317f0e826aa4abf120c788379c33 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:43:53 +1300 Subject: [PATCH 14/17] Preserve Social UUID fixture and filtered roster evidence --- .../game-logic-service/api-contracts.md | 2 +- .../test/AccountRuntimeStubServerTest.java | 37 +++++++++--- .../test/AccountRuntimeStubServer.java | 50 +++++++++++----- .../text/FriendsCommandHandlerTest.java | 60 +++++++++++++++++++ 4 files changed, 125 insertions(+), 24 deletions(-) diff --git a/design/architecture/microservices/game-logic-service/api-contracts.md b/design/architecture/microservices/game-logic-service/api-contracts.md index 58ee718b98..f834624212 100644 --- a/design/architecture/microservices/game-logic-service/api-contracts.md +++ b/design/architecture/microservices/game-logic-service/api-contracts.md @@ -67,7 +67,7 @@ The selected-full `GetDraftDesignDigest` adapter reads the exact retained source - `Ping(PingRequest) returns (PingResponse)` is the basic connectivity check defined in [`game_logic_service.proto`](../../../../protos/game-logic/v1/game_logic_service.proto). - `ExecuteCommand(ExecuteCommandRequest) returns (ExecuteCommandResponse)` evaluates a parsed gameplay command and returns the outcome. -- `SendCommunication` is the target gameplay communication contract: it inherits the complete validated `PlayerExecutionContext` from Game Session, classifies a world/gameplay communication type, resolves topology/perception/capability/effect facts, and forwards one bounded plan with stable identity, authorized candidate views, and owner handoffs. The current Game Logic adapter first requires `account_id` to be present, positive, and numeric; malformed, missing, or non-positive account identity returns `INVALID_ARGUMENT` before Entity Management or Social calls. It then projects the flat request to Social & Groups as `tenant_id`, that validated account identity as `sender_id`, mapped communication `type`, normalized text as `content`, the resolved recipient when applicable, and `effect_id`; it never falls back to `character_id` for sender authority. It does not forward `session_id`, room context, target kind/name, or legacy `session_attestation` unchanged. Game Logic owns validating the incoming request fields against the target context, but focused tenant/session/character/target mismatch and projection proof remains an implementation gap. Until that target context is propagated, the live request remains the flat field set documented under [Player execution context](#player-execution-context), including legacy `session_attestation`; those request fields are data to validate against the target context, never caller authority. Account messaging, ordinary group/channel communication, browser social actions, and ordinary account/social mail are Social-owned classes and may use an authenticated in-game adapter without becoming Game Logic actions or exposing private content to tenant-authored scripts. Deliberately world-specific mail is a gameplay communication class under [ADR 0147](../../decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md); [ADR 0148](../../decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md) remains the value and attachment authority. See active ADR 0147, mapped from reviewed archive record `archive-ADR-0134`. +- `SendCommunication` is the target gameplay communication contract: it inherits the complete validated `PlayerExecutionContext` from Game Session, classifies a world/gameplay communication type, resolves topology/perception/capability/effect facts, and forwards one bounded plan with stable identity, authorized candidate views, and owner handoffs. The current Game Logic adapter first requires a canonical lowercase non-nil Account UUID in `account_id`. Malformed, missing or noncanonical identity returns `INVALID_ARGUMENT` before Entity Management or Social calls. It then projects the flat request to Social & Groups as `tenant_id`, that validated account identity as `sender_id`, mapped communication `type`, normalized text as `content`, the resolved recipient when applicable, and `effect_id`; it never falls back to `character_id` for sender authority. It does not forward `session_id`, room context, target kind/name, or legacy `session_attestation` unchanged. Game Logic owns validating the incoming request fields against the target context, but focused tenant/session/character/target mismatch and projection proof remains an implementation gap. Until that target context is propagated, the live request remains the flat field set documented under [Player execution context](#player-execution-context), including legacy `session_attestation`; those request fields are data to validate against the target context, never caller authority. Account messaging, ordinary group/channel communication, browser social actions, and ordinary account/social mail are Social-owned classes and may use an authenticated in-game adapter without becoming Game Logic actions or exposing private content to tenant-authored scripts. Deliberately world-specific mail is a gameplay communication class under [ADR 0147](../../decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md); [ADR 0148](../../decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md) remains the value and attachment authority. See active ADR 0147, mapped from reviewed archive record `archive-ADR-0134`. - `PickupVisibleRoomItem` and `DropCarriedItem` are the player-facing item selector RPCs for the current `GET` and `DROP` command path. Game Session sends the current session/game/room context, raw item reference, and quantity; Game Logic resolves names, visible refs, container identities, and stack-family refs against the appropriate visible holder before delegating the concrete mutation to Entity Management. - `ApplyActorCondition` is the current self-scoped gameplay orchestration path for the first actor-state mutation. It is not the target-state generic cross-actor effect API. - gRPC outcome selection follows the [canonical outcome and transport classification](../../system-architecture-grpc.md#outcome-and-transport-classification): successfully produced gameplay/domain outcomes use the typed response contract, while a failure that prevents producing that result uses canonical non-OK status with bounded details. Exact RPC mappings remain implementation work. 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 d0f92cd423..758ef575b8 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 @@ -141,15 +141,34 @@ void resetRetainsExplicitUuidRegistrationWithoutReauthentication() throws Except AccountProfileJson.parse(profile.getProfileJson(), "PRIVATE") .presenceVisibilityPolicy()) .isEqualTo("FRIENDS_ONLY"); - assertThat( - stub.updateProfile( - UpdateProfileRequest.newBuilder() - .setTenantId("1") - .setAccountId(accountUuid) - .setProfileJson("{\"presenceVisibilityPolicy\":\"PRIVATE\"}") - .build()) - .getSuccess()) - .isTrue(); + var update = + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountUuid) + .setProfileJson("{\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(); + var result = stub.updateProfile(update); + assertThat(result.getSuccess()).isTrue(); + assertThat(result.hasError()).isFalse(); + assertThat(result.getAccountId()).isEqualTo(accountUuid); + assertThat(result.getTenantId()).isEqualTo("1"); + + var noncanonical = + stub.updateProfile( + update.toBuilder() + .setTenantId("01") + .setProfileJson("{\"presenceVisibilityPolicy\":\"PUBLIC\"}") + .build()); + assertThat(noncanonical.getSuccess()).isFalse(); + assertThat(noncanonical.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(noncanonical.getAccountId()).isEmpty(); + assertThat(noncanonical.getTenantId()).isEmpty(); + var retained = + stub.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(accountUuid).build()); + assertThat(AccountProfileJson.parse(retained.getProfileJson(), "FRIENDS_ONLY") + .presenceVisibilityPolicy()) + .isEqualTo("PRIVATE"); } finally { channel.shutdownNow(); } 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 c6a2d9ad96..e525d710e7 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 @@ -455,10 +455,7 @@ public void getProfile( } final long tenantId; try { - tenantId = Long.parseLong(request.getTenantId()); - if (tenantId <= 0L || !Long.toString(tenantId).equals(request.getTenantId())) { - throw new IllegalArgumentException("tenantId must be canonical and positive"); - } + tenantId = requireProfileTenantId(request.getTenantId()); } catch (IllegalArgumentException ex) { responseObserver.onNext( GetProfileResponse.newBuilder() @@ -493,16 +490,27 @@ public void getProfile( @Override public void updateProfile( UpdateProfileRequest request, StreamObserver responseObserver) { + Long accountId = resolveRegisteredAccountId(request.getAccountId()); + if (accountId == null) { + responseObserver.onNext( + UpdateProfileResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("ACCOUNT_NOT_FOUND")) + .build()); + responseObserver.onCompleted(); + return; + } + final long tenantId; + try { + tenantId = requireProfileTenantId(request.getTenantId()); + } catch (IllegalArgumentException ex) { + responseObserver.onNext( + UpdateProfileResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("INVALID_ARGUMENT")) + .build()); + responseObserver.onCompleted(); + return; + } try { - Long accountId = resolveRegisteredAccountId(request.getAccountId()); - if (accountId == null) { - responseObserver.onNext( - UpdateProfileResponse.newBuilder() - .setError(ErrorDetail.newBuilder().setCode("ACCOUNT_NOT_FOUND")) - .build()); - responseObserver.onCompleted(); - return; - } AccountProfileJson profile = AccountProfileJson.parse(request.getProfileJson(), StubProfile.DEFAULT_VISIBILITY_POLICY); StubProfile existing = @@ -515,7 +523,13 @@ public void updateProfile( profile.presenceVisibilityPolicy() == null ? existing.presenceVisibilityPolicy() : profile.presenceVisibilityPolicy())); - responseObserver.onNext(UpdateProfileResponse.newBuilder().setSuccess(true).build()); + // Like profile reads, this echo describes the controlled request fixture. + responseObserver.onNext( + UpdateProfileResponse.newBuilder() + .setSuccess(true) + .setAccountId(accountUuidForTestFixture(accountId)) + .setTenantId(Long.toString(tenantId)) + .build()); responseObserver.onCompleted(); } catch (Exception ex) { responseObserver.onNext(UpdateProfileResponse.newBuilder().setSuccess(false).build()); @@ -523,6 +537,14 @@ public void updateProfile( } } + private static long requireProfileTenantId(String selector) { + long tenantId = Long.parseLong(selector); + if (tenantId <= 0L || !Long.toString(tenantId).equals(selector)) { + throw new IllegalArgumentException("tenantId must be canonical and positive"); + } + return tenantId; + } + private Long resolveRegisteredAccountId(String accountUuid) { try { UUID parsed = UUID.fromString(accountUuid); 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 72d8e4ef96..f8a6fa40f8 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 @@ -33,6 +33,8 @@ import net.firedevops.firemud.socialgroups.v1.RemoveFriendResponse; import net.firedevops.firemud.socialgroups.v1.UpdateFriendPresencePolicyResponse; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; class FriendsCommandHandlerTest { @@ -426,6 +428,64 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { .listFriends(1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); } + @ParameterizedTest + @ValueSource(strings = {"ONLINE", "RECENT"}) + void friendsFilteredRedactedMatchesKeepRosterTotalOutOfPlayerText(String filter) { + FriendRosterFilter rosterFilter = + "ONLINE".equals(filter) + ? FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE + : FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT; + SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); + EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); + FriendsCommandHandler handler = + newHandler( + socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID, rosterFilter)) + .thenReturn( + ListFriendsResponse.newBuilder() + .setFilter(rosterFilter) + .setTotalCount(2) + .setMatchCount(1) + .addFriends( + FriendRosterEntry.newBuilder() + .setOrdinal(2) + .setFriendAccountId(OTHER_FRIEND_ACCOUNT_ID) + .setPresence( + FriendPresenceEntry.newBuilder() + .setFriendAccountId(OTHER_FRIEND_ACCOUNT_ID) + .setOnline("ONLINE".equals(filter)) + .setLastSeenAtMs(1_744_336_000_000L) + .setCharacterName("Secret") + .setVisibilityPolicy( + net.firedevops.firemud.socialgroups.v1 + .FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE) + .build()) + .build()) + .build()); + + TextCommandInterpretationResult result = + handler.handle( + new TextCommand( + TextCommandType.FRIENDS, List.of(filter), "FRIENDS " + filter), + GAMEPLAY_CONTEXT); + + assertThat(result.commandResult().accepted()).isTrue(); + FriendPresenceViewOutput view = + (FriendPresenceViewOutput) result.outputs().getFirst().payload(); + assertThat(view.filter()).isEqualTo(filter); + assertThat(view.totalCount()).isEqualTo(2); + assertThat(view.matchCount()).isZero(); + assertThat(view.friends()).isEmpty(); + assertThat( + new TextPlayerOutputRenderer( + new net.firedevops.firemud.gamesession.config.PresentationProperties()) + .render(result.outputs().getFirst())) + .contains("Friends " + filter + ": no matching friends.") + .doesNotContain("Secret", OTHER_FRIEND_ACCOUNT_ID, "[1/2]", "[0/2]", "[0/0]"); + Mockito.verify(socialGroupsClient).listFriends(1L, CALLER_ACCOUNT_ID, rosterFilter); + } + @Test void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); From 9da58cf97eb4882028b1463b0c6bc8e9e0fc7d7f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:04:35 +1300 Subject: [PATCH 15/17] Apply canonical formatting to received Social UUID proof --- .../firemud/test/AccountRuntimeStubServerTest.java | 5 +++-- .../gamesession/command/text/FriendsCommandHandlerTest.java | 3 +-- 2 files changed, 4 insertions(+), 4 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 758ef575b8..ffb47fd6ba 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 @@ -166,8 +166,9 @@ void resetRetainsExplicitUuidRegistrationWithoutReauthentication() throws Except var retained = stub.getProfile( GetProfileRequest.newBuilder().setTenantId("1").setAccountId(accountUuid).build()); - assertThat(AccountProfileJson.parse(retained.getProfileJson(), "FRIENDS_ONLY") - .presenceVisibilityPolicy()) + assertThat( + AccountProfileJson.parse(retained.getProfileJson(), "FRIENDS_ONLY") + .presenceVisibilityPolicy()) .isEqualTo("PRIVATE"); } finally { channel.shutdownNow(); 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 f8a6fa40f8..3572aaf7f3 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 @@ -466,8 +466,7 @@ void friendsFilteredRedactedMatchesKeepRosterTotalOutOfPlayerText(String filter) TextCommandInterpretationResult result = handler.handle( - new TextCommand( - TextCommandType.FRIENDS, List.of(filter), "FRIENDS " + filter), + new TextCommand(TextCommandType.FRIENDS, List.of(filter), "FRIENDS " + filter), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isTrue(); From dc20e20f3135491905281739c134bec2c811c494 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:28:13 +1300 Subject: [PATCH 16/17] Prove exact retained Logging report history through V1008 --- ...tUuidMigrationPostgresIntegrationTest.java | 49 +++++++++++++------ 1 file changed, 34 insertions(+), 15 deletions(-) diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ReportAccountUuidMigrationPostgresIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ReportAccountUuidMigrationPostgresIntegrationTest.java index 16d5ded0c8..4d49f9d422 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ReportAccountUuidMigrationPostgresIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ReportAccountUuidMigrationPostgresIntegrationTest.java @@ -36,6 +36,12 @@ @SuppressWarnings("resource") class ReportAccountUuidMigrationPostgresIntegrationTest { private static final String MIGRATION_LOCATION = "classpath:db/migration"; + private static final List EXPECTED_VERSIONS = + List.of( + "1", "2", "3", "4", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", + "1008"); + private static final List EXPECTED_PRE_REPORT_VERSIONS = + EXPECTED_VERSIONS.subList(0, EXPECTED_VERSIONS.size() - 1); @Container static final PostgreSQLContainer POSTGRES = @@ -82,7 +88,9 @@ void freshSchemaMigratesWithCanonicalAccountUuidsAndNumericLocalIdentifiers() th schema, "INSERT INTO player_reports (tenant_id, reporter_account_id, type, description) VALUES (1, NULL, 'BUG', 'null reporter')")); // Runtime discovery includes the unchanged service and Saga migration history. - assertThat(history(schema)).hasSize(13); + assertThat(history(schema)) + .extracting(MigrationHistoryEntry::version) + .containsExactlyElementsOf(EXPECTED_VERSIONS); } @Test @@ -107,7 +115,9 @@ void emptyAffectedTablesUpgradeFromV1007AndGenericLogAccountIdRemainsNumeric() t schema, "SELECT account_id FROM log_events WHERE message = 'preserve generic log'")) .isEqualTo(42L); // All earlier service and Saga migrations remain present. - assertThat(history(schema)).hasSize(13); + assertThat(history(schema)) + .extracting(MigrationHistoryEntry::version) + .containsExactlyElementsOf(EXPECTED_VERSIONS); } @Test @@ -118,11 +128,14 @@ void existingCanonicalModerationRowsAreUntouchedByReportOnlyMigration() throws E schema, "INSERT INTO moderation_actions (tenant_id, account_id, action, reason) VALUES (17, 'b8d093f7-cb70-40ed-9fac-3c82d4bf28f1', 'warning', 'retained action')"); List rowsBefore = rows(schema, "moderation_actions"); - List historyBefore = history(schema); + List historyBefore = history(schema); migrateToLatest(schema); assertThat(rows(schema, "moderation_actions")).isEqualTo(rowsBefore); - assertThat(history(schema).subList(0, historyBefore.size())).isEqualTo(historyBefore); - assertThat(history(schema)).hasSize(historyBefore.size() + 1); + List historyAfter = history(schema); + assertThat(historyAfter) + .extracting(MigrationHistoryEntry::version) + .containsExactlyElementsOf(EXPECTED_VERSIONS); + assertThat(historyAfter.subList(0, historyBefore.size())).isEqualTo(historyBefore); } @Test @@ -132,12 +145,15 @@ void retainedPlayerReportRefusesWithoutChangingRowsOrMigrationHistory() throws E execute( schema, "INSERT INTO player_reports (tenant_id, reporter_account_id, target_account_id, type, description) VALUES (41, 43, 47, 'BUG', 'retained report')"); - List historyBefore = history(schema); + List historyBefore = history(schema); List rowsBefore = rows(schema, "player_reports"); FlywayException failure = assertThrows(FlywayException.class, () -> migrateToLatest(schema)); assertThat(failure).hasStackTraceContaining("Account-owned recovery is required"); + assertThat(historyBefore) + .extracting(MigrationHistoryEntry::version) + .containsExactlyElementsOf(EXPECTED_PRE_REPORT_VERSIONS); assertThat(history(schema)).isEqualTo(historyBefore); assertThat(rows(schema, "player_reports")).isEqualTo(rowsBefore); assertThat(columnType(schema, "player_reports", "reporter_account_id")).isEqualTo("int8"); @@ -167,7 +183,7 @@ void retainedPlayerReportRefusesWithoutChangingRowsOrMigrationHistory() throws E void migrationWaitsForConcurrentWriterAndRefusesAfterItsRowCommits() throws Exception { String schema = createSchema(); migrateToVersion(schema, "1007"); - List historyBefore = history(schema); + List historyBefore = history(schema); ExecutorService executor = Executors.newSingleThreadExecutor(); try (Connection writer = connection()) { @@ -195,8 +211,10 @@ void migrationWaitsForConcurrentWriterAndRefusesAfterItsRowCommits() throws Exce ExecutionException failure = assertThrows(ExecutionException.class, () -> migration.get(10, TimeUnit.SECONDS)); assertThat(failure).hasStackTraceContaining("Account-owned recovery is required"); + assertThat(historyBefore) + .extracting(MigrationHistoryEntry::version) + .containsExactlyElementsOf(EXPECTED_PRE_REPORT_VERSIONS); assertThat(history(schema)).isEqualTo(historyBefore); - assertThat(history(schema)).hasSize(12); assertThat(columnType(schema, "player_reports", "reporter_account_id")).isEqualTo("int8"); assertThat(scalarLong(schema, "SELECT count(*) FROM player_reports")).isEqualTo(1L); assertThat( @@ -273,8 +291,8 @@ private static long scalarLong(String schema, String sql) throws SQLException { } } - private static List history(String schema) throws SQLException { - List entries = new ArrayList<>(); + private static List history(String schema) throws SQLException { + List entries = new ArrayList<>(); try (Connection connection = connection(); Statement statement = connection.createStatement(); ResultSet result = @@ -284,16 +302,17 @@ private static List history(String schema) throws SQLException { "SELECT version, checksum, success FROM flyway_schema_history ORDER BY installed_rank"))) { while (result.next()) { entries.add( - result.getString("version") - + ":" - + result.getString("checksum") - + ":" - + result.getBoolean("success")); + new MigrationHistoryEntry( + result.getString("version"), + result.getString("checksum"), + result.getBoolean("success"))); } } return entries; } + private record MigrationHistoryEntry(String version, String checksum, boolean successful) {} + private static List rows(String schema, String table) throws SQLException { List records = new ArrayList<>(); try (Connection connection = connection(); From fee1cbcf9e8328ddb7b52549bdcf9de06032b6a0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:45:06 +1300 Subject: [PATCH 17/17] fix(grpc): admit platform keepalive pings on every gRPC server Platform channels ping every 30s, including while idle, but servers kept Spring gRPC's 5-minute permit time. Idle connections therefore got GOAWAY too_many_pings and the next call could fail UNAVAILABLE. The bounded server factory now caps the permit time at GrpcChannelFactory's KEEP_ALIVE_TIME and always permits idle pings. Co-Authored-By: Claude Opus 5.5 --- ...monGrpcRequestBoundsAutoConfiguration.java | 15 +++++++++-- .../common/grpc/GrpcChannelFactory.java | 9 ++++++- .../config/GrpcServerKeepAlivePermitTest.java | 25 +++++++++++++++++++ 3 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/config/GrpcServerKeepAlivePermitTest.java diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java index 5ba13301fc..86842d6b7d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java @@ -10,6 +10,7 @@ import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.TrustManagerFactory; import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.SmartInitializingSingleton; @@ -132,12 +133,22 @@ private static void configureProperties( duration(keepAlive.getMaxIdle(), builder::maxConnectionIdle); duration(keepAlive.getMaxAge(), builder::maxConnectionAge); duration(keepAlive.getMaxAgeGrace(), builder::maxConnectionAgeGrace); - duration(keepAlive.getPermitTime(), builder::permitKeepAliveTime); - builder.permitKeepAliveWithoutCalls(keepAlive.isPermitWithoutCalls()); + duration(platformPermitTime(keepAlive.getPermitTime()), builder::permitKeepAliveTime); + // Platform channels ping while idle, so servers always admit idle pings. + builder.permitKeepAliveWithoutCalls(true); builder.maxInboundMetadataSize( Math.toIntExact(properties.getMaxInboundMetadataSize().toBytes())); } + /** + * Returns the configured permit time, capped at the platform channel ping interval. The framework + * default of five minutes would refuse platform pings on idle connections. + */ + static Duration platformPermitTime(Duration configured) { + Duration client = GrpcChannelFactory.KEEP_ALIVE_TIME; + return configured == null || configured.compareTo(client) > 0 ? client : configured; + } + private static void duration(Duration duration, BiConsumer apply) { if (duration != null) { apply.accept(duration.toNanos(), TimeUnit.NANOSECONDS); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java index f1827d0f35..261e069754 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java @@ -6,12 +6,19 @@ import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import java.io.File; import java.io.InputStream; +import java.time.Duration; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; /** Builds outbound gRPC channels with FireMUD's standard TLS and keepalive behavior. */ public class GrpcChannelFactory { + /** + * Interval at which platform channels ping, including while idle. Platform gRPC servers must + * admit pings at this rate or they answer with GOAWAY {@code too_many_pings}. + */ + public static final Duration KEEP_ALIVE_TIME = Duration.ofSeconds(30); + public ManagedChannel buildChannel( String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) throws SSLException { @@ -110,7 +117,7 @@ private void configureKeepAlive(ManagedChannelBuilder builder, boolean keepAl return; } builder - .keepAliveTime(30, TimeUnit.SECONDS) + .keepAliveTime(KEEP_ALIVE_TIME.toNanos(), TimeUnit.NANOSECONDS) .keepAliveTimeout(5, TimeUnit.SECONDS) .keepAliveWithoutCalls(true); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/config/GrpcServerKeepAlivePermitTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/config/GrpcServerKeepAlivePermitTest.java new file mode 100644 index 0000000000..bf376024ba --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/config/GrpcServerKeepAlivePermitTest.java @@ -0,0 +1,25 @@ +package net.firedevops.firemud.common.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Duration; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.Test; + +class GrpcServerKeepAlivePermitTest { + + @Test + void serversAdmitThePlatformChannelPingInterval() { + Duration client = GrpcChannelFactory.KEEP_ALIVE_TIME; + + // Unset and the framework's five-minute default both fall back to the client interval. + assertThat(CommonGrpcRequestBoundsAutoConfiguration.platformPermitTime(null)).isEqualTo(client); + assertThat(CommonGrpcRequestBoundsAutoConfiguration.platformPermitTime(Duration.ofMinutes(5))) + .isEqualTo(client); + // A configured permit time at or below the client interval is kept. + assertThat(CommonGrpcRequestBoundsAutoConfiguration.platformPermitTime(client)) + .isEqualTo(client); + assertThat(CommonGrpcRequestBoundsAutoConfiguration.platformPermitTime(Duration.ofSeconds(10))) + .isEqualTo(Duration.ofSeconds(10)); + } +}