From 2424670551579c3a208a25a191064f8ed60d4edc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 17:39:13 +1300 Subject: [PATCH 1/5] Prove canonical Account UUID policy batch values --- .../firemud/socialgroups/client/AccountClientTest.java | 3 +++ 1 file changed, 3 insertions(+) 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 1a1c514207..6702c10ee3 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 @@ -81,6 +81,9 @@ void batchesPresenceVisibilityPolicyReadsAtTheAccountServiceLimit() throws Excep assertThat(requests.getAllValues()) .extracting(ListPresenceVisibilityPoliciesRequest::getAccountIdsCount) .containsExactly(100, 1); + assertThat(requests.getAllValues()) + .extracting(request -> List.copyOf(request.getAccountIdsList())) + .containsExactly(accountIds.subList(0, 100), accountIds.subList(100, 101)); assertThat(requests.getAllValues()) .extracting(ListPresenceVisibilityPoliciesRequest::getTenantId) .containsOnly("11"); From 3a87f037c0921b7eaf2020e736865f0636e7d1f8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 19:50:02 +1300 Subject: [PATCH 2/5] Extract Logging UUID receiver into its approved stacked child --- .../logging-admin-service/api-contracts.md | 2 +- .../logging-admin-service/runtime-and-data.md | 2 - ...r-experience-commands-and-communication.md | 2 +- .../loggingadmin/data/TestDataSeeder.java | 43 +++ .../dto/ApplyModerationActionRequest.java | 9 +- .../loggingadmin/dto/CreateReportRequest.java | 15 +- .../loggingadmin/dto/ModerationActionDto.java | 3 +- .../firemud/loggingadmin/dto/ReportDto.java | 5 +- .../loggingadmin/entity/ModerationAction.java | 3 +- .../loggingadmin/entity/PlayerReport.java | 5 +- .../ModerationActionRepository.java | 5 +- .../repository/PlayerReportRepository.java | 3 +- .../service/ModerationService.java | 3 +- .../service/impl/LoggingAdminGrpcService.java | 6 +- .../service/impl/ModerationServiceImpl.java | 5 +- .../service/impl/ReportGrpcService.java | 8 +- ...nonical_moderation_report_account_uuid.sql | 42 --- ...ngAccountUuidMigrationIntegrationTest.java | 348 ------------------ .../ModerationActionControllerTest.java | 10 +- .../loggingadmin/data/TestDataSeederTest.java | 34 +- .../impl/LoggingAdminGrpcServiceAuthTest.java | 28 +- .../impl/ModerationServiceImplTest.java | 18 +- .../service/impl/ReportGrpcServiceTest.java | 31 +- .../service/impl/ReportServiceImplTest.java | 7 +- 24 files changed, 131 insertions(+), 506 deletions(-) delete mode 100644 services/logging-admin-service/src/main/resources/db/migration/V6__canonical_moderation_report_account_uuid.sql delete mode 100644 services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAccountUuidMigrationIntegrationTest.java diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 9641b402fe..ee96fbba8d 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -182,7 +182,7 @@ grpcurl -cacert "$FIREMUD_GRPC_CA_CERT_PATH" \ -cert "$FIREMUD_GRPC_CERT_CHAIN_PATH" \ -key "$FIREMUD_GRPC_PRIVATE_KEY_PATH" \ -H 'Authorization: Bearer ' \ - -d '{"tenant_id":"1","reporter_account_id":"550e8400-e29b-41d4-a716-446655440000","target_account_id":"6ba7b810-9dad-41d1-80b4-00c04fd430c8","type":"BUG","description":"example"}' \ + -d '{"tenant_id":"1","reporter_account_id":"1","target_account_id":"2","type":"BUG","description":"example"}' \ "$FIREMUD_LOGGING_ADMIN_GRPC_TARGET" \ logging_admin.v1.ReportService/CreateReport ``` 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 ec337a59cc..64181030c2 100644 --- a/design/architecture/microservices/logging-admin-service/runtime-and-data.md +++ b/design/architecture/microservices/logging-admin-service/runtime-and-data.md @@ -115,8 +115,6 @@ For plugin operations, Automation remains the activation/lifecycle owner and Gam ## Data Model -Account subjects in moderation-policy reads and report references are canonical non-nil UUIDs, distinct from tenant and private row selectors. Forward migration V6 converts the Account columns in `moderation_actions` and `player_reports` only after locking both tables and proving both empty; any retained row refuses the transaction unchanged and requires Account-owned authoritative recovery. Published V1–V5 remain unchanged. This storage/caller correction does not enable moderation or report mutation, and the startup seeder must not fabricate Account subjects for sample rows. The generic `log_events.account_id` and separate audit/recovery contracts are not converted by this migration. - - `log_events` is the current service-owned PostgreSQL domain table and also holds the Account audit projection defined in [Account Audit Ingress and Receipt](./api-contracts.md#account-audit-ingress-and-receipt). Audit projections retain explicit `platform` or `tenant` scope; platform rows have no `tenantId` and are excluded from tenant queries. `LogQueryServiceImpl` queries tenant-scope rows by exact `tenantId` and case-insensitive message containment and returns only stored messages. No current implementation mirrors this table into Elasticsearch or proves the profile-aware emitter-to-query path; selected-profile indexed, compatible-backend, or console/journal querying remains target-state under [Logging & Monitoring](../../system-architecture-logging-monitoring.md#log-pipeline-queryability-contract). - `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_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. 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 a0fb932c2f..7dc233635b 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 @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player-facing commands, commu ## Current Status -Shared ordinary Account JWT identity uses the exact canonical Account UUID in [#2969](https://github.com/benhook1013/FireMUD/pull/2969), the shared-auth child of #2929. The Social child after [#2932](https://github.com/benhook1013/FireMUD/pull/2932) converges account-bearing Social storage/API selectors and Account, Game Session, and Logging caller boundaries without numeric aliases or guessed retained mappings. Exact UUID self access and authenticated sender-bound mail replace the interim numeric-caller containment only in this child; genuine tenant-role checks and all removed Gateway routes remain separate and unchanged. Account bulk policies resolve persisted provenance and membership, while profile reads/updates verify exact Account UUID and tenant echoes. Social V10 and Logging V6 lock their complete affected table sets and refuse retained data unchanged; retained-data recovery remains Account-owned and unimplemented. Local generation, affected compilation, unit tests, formatting/analyzers, and packaged JAR checks pass. Migration tests compile but skip without Docker; real PostgreSQL cutover, fresh-image and live-delivery proof remain required. Game Session filters ONLINE/RECENT roster matches after final privacy redaction, with negative proof that backend match metadata cannot disclose suppressed presence through inclusion. No successful Social deployment, cross-pod delivery, moderation/report activation, or end-to-end authentication is claimed, and this correction does not close EA-2.1/EA-2.2/EA-2.3 target gaps. +Shared ordinary Account JWT identity uses the exact canonical Account UUID in [#2969](https://github.com/benhook1013/FireMUD/pull/2969), the shared-auth child of #2929. The Social front after [#2932](https://github.com/benhook1013/FireMUD/pull/2932) converges account-bearing Social storage/API selectors and Account, Game Session, and Social-to-Logging caller boundaries without numeric aliases or guessed retained mappings. Its immediately stacked Logging receiver child carries the moderation/report UUID receiver and storage changes; the Social front alone does not provide that receiver capability. Exact UUID self access and authenticated sender-bound mail replace the interim numeric-caller containment only in the Social front; genuine tenant-role checks and all removed Gateway routes remain separate and unchanged. Account bulk policies resolve persisted provenance and membership, while profile reads/updates verify exact Account UUID and tenant echoes. Social V10 locks all six affected tables and refuses retained data unchanged; the Logging child's V6 independently fences both affected moderation/report tables. Retained-data recovery remains Account-owned and unimplemented. Local generation, affected compilation, unit tests, formatting/analyzers, and packaged JAR checks cover the composed candidate; each extracted stage requires its own proof. Migration tests compile but skip without Docker; real PostgreSQL cutover, fresh-image and live-delivery proof remain required. Game Session filters ONLINE/RECENT roster matches after final privacy redaction, with negative proof that backend match metadata cannot disclose suppressed presence through inclusion. Moderation/report operations remain unavailable in both stages; installing the receiver child does not activate them. No successful Social deployment, cross-pod delivery, moderation/report activation, or end-to-end authentication is claimed, and this correction does not close EA-2.1/EA-2.2/EA-2.3 target gaps. Game Logic now forwards the canonical sender UUID, but its legacy gameplay recipient field still denotes a character selector. That field must not be guessed into an Account UUID: numeric recipients fail closed at Social until the separately owned typed-recipient/owner-delivery convergence is implemented. Existing gameplay-connected communication tests use the regression Social stub; they are not positive proof of real Social `WHISPER`/`TELL` delivery. Owner-local restrictions, authenticated full-request replay, and type-specific retention remain unfinished independently of this UUID repair. 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 395caf5496..b1b5ed7a11 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,7 +4,11 @@ import java.time.Instant; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.loggingadmin.entity.LogEvent; +import net.firedevops.firemud.loggingadmin.entity.ModerationAction; +import net.firedevops.firemud.loggingadmin.entity.PlayerReport; import net.firedevops.firemud.loggingadmin.repository.LogEventRepository; +import net.firedevops.firemud.loggingadmin.repository.ModerationActionRepository; +import net.firedevops.firemud.loggingadmin.repository.PlayerReportRepository; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -23,13 +27,19 @@ 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; + private final ModerationActionRepository moderationActionRepository; @Override @Transactional public void run(ApplicationArguments args) { ensureStartupLogEvent(); + ensureSamplePlayerReport(); + ensureSampleModerationAction(); } private void ensureStartupLogEvent() { @@ -45,4 +55,37 @@ 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); + } + + private void ensureSampleModerationAction() { + ModerationAction action = + moderationActionRepository + .findFirstByTenantIdAndAccountIdAndActionAndReason( + DEMO_TENANT_ID, DEMO_TARGET_ACCOUNT_ID, "warning", "initial seed") + .orElseGet(ModerationAction::new); + action.setTenantId(DEMO_TENANT_ID); + action.setAccountId(DEMO_TARGET_ACCOUNT_ID); + action.setAction("warning"); + action.setReason("initial seed"); + if (action.getCreatedAt() == null) { + action.setCreatedAt(Instant.now()); + } + moderationActionRepository.save(action); + } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ApplyModerationActionRequest.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ApplyModerationActionRequest.java index 5df68cb41f..05e0e3b9e8 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ApplyModerationActionRequest.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ApplyModerationActionRequest.java @@ -4,15 +4,10 @@ import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; import jakarta.validation.constraints.Size; -import net.firedevops.firemud.common.security.JwtClaims; public record ApplyModerationActionRequest( @NotNull @Positive Long tenantId, - @NotNull @NotBlank String accountId, + @NotNull @Positive Long accountId, @NotNull @Positive Long sessionId, @NotBlank @Size(max = 20) String action, - @Size(max = 255) String reason) { - public ApplyModerationActionRequest { - accountId = JwtClaims.requireAccountId(accountId, "accountId"); - } -} + @Size(max = 255) String reason) {} 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 5ea997ad61..0d31f1cfb2 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,21 +1,12 @@ 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 @NotBlank String reporterAccountId, - String targetAccountId, + @NotNull @Positive Long reporterAccountId, + @Positive Long targetAccountId, @NotNull @Size(max = 20) String type, - @NotNull @Size(max = 255) String description) { - public CreateReportRequest { - reporterAccountId = JwtClaims.requireAccountId(reporterAccountId, "reporterAccountId"); - if (targetAccountId != null) { - targetAccountId = JwtClaims.requireAccountId(targetAccountId, "targetAccountId"); - } - } -} + @NotNull @Size(max = 255) String description) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ModerationActionDto.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ModerationActionDto.java index 6dc02d3e81..071837b2a6 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ModerationActionDto.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ModerationActionDto.java @@ -4,12 +4,11 @@ import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; import java.time.Instant; -import java.util.UUID; public record ModerationActionDto( Long id, @NotNull Long tenantId, - @NotNull UUID accountId, + @NotNull Long accountId, @NotBlank @Size(max = 20) String action, @Size(max = 255) String reason, Instant createdAt, 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 966caff1cc..bb9348b6d2 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,13 +3,12 @@ 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 UUID reporterAccountId, - UUID targetAccountId, + @NotNull Long reporterAccountId, + Long 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/ModerationAction.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/ModerationAction.java index 83a6009475..970b601281 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/ModerationAction.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/ModerationAction.java @@ -1,14 +1,13 @@ package net.firedevops.firemud.loggingadmin.entity; import java.time.Instant; -import java.util.UUID; import lombok.Data; @Data public class ModerationAction { private Long id; private Long tenantId; - private UUID accountId; + private Long accountId; private String action; private String reason; private 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 a38bd5c614..23d940ead6 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,16 +1,15 @@ 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 UUID reporterAccountId; + private Long reporterAccountId; - private UUID targetAccountId; + private Long 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/ModerationActionRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/ModerationActionRepository.java index 9b43674998..61d2544f42 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/ModerationActionRepository.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/ModerationActionRepository.java @@ -8,7 +8,6 @@ import java.time.Instant; import java.util.List; import java.util.Optional; -import java.util.UUID; import net.firedevops.firemud.loggingadmin.entity.ModerationAction; import net.firedevops.firemud.loggingadmin.jooq.tables.records.ModerationActionsRecord; import org.jooq.DSLContext; @@ -32,7 +31,7 @@ public long count() { } public Optional findFirstByTenantIdAndAccountIdAndActionAndReason( - Long tenantId, UUID accountId, String action, String reason) { + Long tenantId, Long accountId, String action, String reason) { return dsl.selectFrom(MODERATION_ACTIONS) .where( MODERATION_ACTIONS @@ -47,7 +46,7 @@ public Optional findFirstByTenantIdAndAccountIdAndActionAndRea } public List findActivePolicyActions( - Long tenantId, UUID accountId, List actions, Instant now) { + Long tenantId, Long accountId, List actions, Instant now) { return dsl.selectFrom(MODERATION_ACTIONS) .where( MODERATION_ACTIONS 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 7c02f937c3..3f91fa1cd3 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,7 +6,6 @@ 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; @@ -29,7 +28,7 @@ public long count() { } public Optional findFirstByTenantIdAndReporterAccountIdAndTargetAccountIdAndType( - Long tenantId, UUID reporterAccountId, UUID targetAccountId, String type) { + Long tenantId, Long reporterAccountId, Long targetAccountId, String type) { return dsl.selectFrom(PLAYER_REPORTS) .where( PLAYER_REPORTS diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/ModerationService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/ModerationService.java index 26f8dbd40d..e605242021 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/ModerationService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/ModerationService.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.loggingadmin.service; -import java.util.UUID; import net.firedevops.firemud.loggingadmin.dto.ApplyModerationActionRequest; import net.firedevops.firemud.loggingadmin.dto.ModerationActionDto; import net.firedevops.firemud.loggingadmin.dto.ModerationPolicyDecisionDto; @@ -8,5 +7,5 @@ public interface ModerationService { ModerationActionDto applyAction(ApplyModerationActionRequest request); - ModerationPolicyDecisionDto evaluatePolicy(long tenantId, UUID accountId, String scope); + ModerationPolicyDecisionDto evaluatePolicy(long tenantId, long accountId, String scope); } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java index d151caca53..64b37f367c 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java @@ -11,12 +11,10 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; -import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; @@ -411,7 +409,7 @@ public void applyModerationAction( try { AdminRoleGuard.requireAdminRole(); RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"); - JwtClaims.requireAccountId(request.getAccountId(), "accountId"); + RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"); RequestIdValidation.requirePositiveLong(request.getSessionId(), "sessionId"); ApplyModerationActionResponse response = ApplyModerationActionResponse.newBuilder() @@ -475,7 +473,7 @@ public void evaluateModerationPolicy( var decision = moderationService.evaluatePolicy( RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - UUID.fromString(JwtClaims.requireAccountId(request.getAccountId(), "accountId")), + RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), request.getScope()); EvaluateModerationPolicyResponse.Builder response = EvaluateModerationPolicyResponse.newBuilder() diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java index 20aa946e3f..1bf0431092 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java @@ -5,7 +5,6 @@ import java.time.Instant; import java.util.List; import java.util.Locale; -import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.loggingadmin.dto.ApplyModerationActionRequest; import net.firedevops.firemud.loggingadmin.dto.ModerationActionDto; @@ -46,7 +45,7 @@ public ModerationActionDto applyAction(ApplyModerationActionRequest request) { "Applying moderation action {} to account {}", request.action(), request.accountId()); ModerationAction entity = new ModerationAction(); entity.setTenantId(request.tenantId()); - entity.setAccountId(UUID.fromString(request.accountId())); + entity.setAccountId(request.accountId()); entity.setAction(request.action()); entity.setReason(request.reason()); entity.setCreatedAt(Instant.now()); @@ -55,7 +54,7 @@ public ModerationActionDto applyAction(ApplyModerationActionRequest request) { @Override @Timed(value = "moderation.evaluatePolicy") - public ModerationPolicyDecisionDto evaluatePolicy(long tenantId, UUID accountId, String scope) { + public ModerationPolicyDecisionDto evaluatePolicy(long tenantId, long accountId, String scope) { List blockingActions = blockingActionsFor(scope); if (blockingActions.isEmpty()) { throw new IllegalArgumentException("Unknown moderation policy scope: " + scope); diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java index 7d36d901ba..1be828872d 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java @@ -6,7 +6,6 @@ import io.micrometer.core.instrument.MeterRegistry; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.security.AdminAuthorizationException; -import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.loggingadmin.v1.CreateReportRequest; @@ -39,10 +38,9 @@ public void createReport( try { requireSocialGroupsInternalService(); RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"); - JwtClaims.requireAccountId(request.getReporterAccountId(), "reporterAccountId"); - if (!request.getTargetAccountId().isEmpty()) { - JwtClaims.requireAccountId(request.getTargetAccountId(), "targetAccountId"); - } + RequestIdValidation.requirePositiveLong(request.getReporterAccountId(), "reporterAccountId"); + RequestIdValidation.parseOptionalPositiveLong( + request.getTargetAccountId(), "targetAccountId"); CreateReportResponse response = CreateReportResponse.newBuilder() .setError( diff --git a/services/logging-admin-service/src/main/resources/db/migration/V6__canonical_moderation_report_account_uuid.sql b/services/logging-admin-service/src/main/resources/db/migration/V6__canonical_moderation_report_account_uuid.sql deleted file mode 100644 index 448e08893d..0000000000 --- a/services/logging-admin-service/src/main/resources/db/migration/V6__canonical_moderation_report_account_uuid.sql +++ /dev/null @@ -1,42 +0,0 @@ --- Preserve the published numeric schema and every retained policy/report row. --- Without Account-owned authoritative recovery, no old identity may be recast. --- The complete affected table set is fenced before any emptiness check or DDL. --- [jooq ignore start] -LOCK TABLE moderation_actions, player_reports IN ACCESS EXCLUSIVE MODE; - -DO $$ -BEGIN - IF EXISTS (SELECT 1 FROM moderation_actions) - OR EXISTS (SELECT 1 FROM player_reports) THEN - RAISE EXCEPTION 'Account-owned recovery is required before migrating retained moderation or report identities to UUID' - USING ERRCODE = '23514', - CONSTRAINT = 'moderation_report_account_uuid_requires_empty_tables'; - END IF; -END; -$$; --- [jooq ignore stop] - --- These tables are locked and proved empty. NULL is only a type-conversion --- expression, never a persisted replacement identity or fabricated mapping. --- jOOQ cannot parse USING; the simple declarations below expose the same types. --- [jooq ignore start] -ALTER TABLE moderation_actions - ALTER COLUMN account_id TYPE UUID USING CAST(NULL AS UUID); -ALTER TABLE player_reports - ALTER COLUMN reporter_account_id TYPE UUID USING CAST(NULL AS UUID), - ALTER COLUMN target_account_id TYPE UUID USING CAST(NULL AS UUID); --- [jooq ignore stop] - -ALTER TABLE moderation_actions ALTER COLUMN account_id TYPE UUID; -ALTER TABLE player_reports ALTER COLUMN reporter_account_id TYPE UUID; -ALTER TABLE player_reports ALTER COLUMN target_account_id TYPE UUID; - -ALTER TABLE moderation_actions - ADD CONSTRAINT moderation_actions_account_uuid_non_nil - CHECK (account_id <> '00000000-0000-0000-0000-000000000000'::UUID); -ALTER TABLE player_reports - ADD CONSTRAINT player_reports_reporter_uuid_non_nil - CHECK (reporter_account_id <> '00000000-0000-0000-0000-000000000000'::UUID), - ADD CONSTRAINT player_reports_target_uuid_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/LoggingAccountUuidMigrationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAccountUuidMigrationIntegrationTest.java deleted file mode 100644 index 7091b24ee1..0000000000 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAccountUuidMigrationIntegrationTest.java +++ /dev/null @@ -1,348 +0,0 @@ -package integration.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 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 LoggingAccountUuidMigrationIntegrationTest { - private static final String MIGRATION_LOCATION = "classpath:db/migration"; - - @Container - static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); - - @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"); - assertThat(history(schema)).hasSize(6); - } - - @Test - void emptyAffectedTablesUpgradeFromV5AndGenericLogAccountIdRemainsNumeric() throws Exception { - String schema = createSchema(); - migrateToVersion(schema, "5"); - 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); - assertThat(history(schema)).hasSize(6); - } - - @Test - void retainedModerationActionRefusesWithoutChangingRowsOrMigrationHistory() throws Exception { - String schema = createSchema(); - migrateToVersion(schema, "5"); - execute( - schema, - "INSERT INTO moderation_actions (tenant_id, account_id, action, reason) VALUES (17, 29, 'warning', 'retained action')"); - List historyBefore = history(schema); - List rowsBefore = rows(schema, "moderation_actions"); - - FlywayException failure = assertThrows(FlywayException.class, () -> migrateToLatest(schema)); - - assertThat(failure).hasStackTraceContaining("Account-owned recovery is required"); - assertThat(history(schema)).isEqualTo(historyBefore); - assertThat(rows(schema, "moderation_actions")).isEqualTo(rowsBefore); - assertThat(columnType(schema, "moderation_actions", "account_id")).isEqualTo("int8"); - assertThat( - scalarLong( - schema, - "SELECT tenant_id FROM moderation_actions WHERE reason = 'retained action'")) - .isEqualTo(17L); - assertThat( - scalarLong(schema, "SELECT count(*) FROM moderation_actions WHERE action = 'warning'")) - .isEqualTo(1L); - assertThat( - scalarLong( - schema, - "SELECT account_id FROM moderation_actions WHERE reason = 'retained action'")) - .isEqualTo(29L); - assertThat(scalarLong(schema, "SELECT count(*) FROM player_reports")).isZero(); - assertThat(columnType(schema, "log_events", "account_id")).isEqualTo("int8"); - } - - @Test - void retainedPlayerReportRefusesWithoutChangingRowsOrMigrationHistory() throws Exception { - String schema = createSchema(); - migrateToVersion(schema, "5"); - 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, "5"); - 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 moderation_actions (tenant_id, account_id, action, reason) VALUES (7, 11, 'warning', '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(5); - assertThat(columnType(schema, "moderation_actions", "account_id")).isEqualTo("int8"); - assertThat(scalarLong(schema, "SELECT count(*) FROM moderation_actions")).isEqualTo(1L); - assertThat( - scalarLong( - schema, - "SELECT account_id FROM moderation_actions WHERE reason = '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 IN ('moderation_actions', '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/controller/ModerationActionControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java index c8ee64d576..5bbf3e9517 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java @@ -37,7 +37,6 @@ }) @WithFiremudPrivilegedHttpAuthTestProperties class ModerationActionControllerTest { - private static final String ACCOUNT_UUID = "550e8400-e29b-41d4-a716-446655440000"; @Autowired private MockMvc mockMvc; private final ObjectMapper objectMapper = new ObjectMapper(); @@ -52,8 +51,7 @@ void clear() { @Test void applyRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Exception { - ApplyModerationActionRequest req = - new ApplyModerationActionRequest(1L, ACCOUNT_UUID, 9L, "ban", ""); + ApplyModerationActionRequest req = new ApplyModerationActionRequest(1L, 2L, 9L, "ban", ""); String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc @@ -75,8 +73,7 @@ void applyRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Excepti @Test void applyRejectsCrossTenantScopedAdmin() throws Exception { - ApplyModerationActionRequest req = - new ApplyModerationActionRequest(1L, ACCOUNT_UUID, 9L, "ban", ""); + ApplyModerationActionRequest req = new ApplyModerationActionRequest(1L, 2L, 9L, "ban", ""); String token = accountToken(jwtUtil, Map.of("scopedRoles", Map.of("8", List.of("moderator")))); mockMvc @@ -90,8 +87,7 @@ void applyRejectsCrossTenantScopedAdmin() throws Exception { @Test void applyRejectsZeroSessionIdBeforeDispatch() throws Exception { - ApplyModerationActionRequest req = - new ApplyModerationActionRequest(1L, ACCOUNT_UUID, 0L, "ban", ""); + ApplyModerationActionRequest req = new ApplyModerationActionRequest(1L, 2L, 0L, "ban", ""); String token = accountToken(jwtUtil, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc 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 3bd665aa24..711431faf8 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 @@ -1,12 +1,14 @@ package net.firedevops.firemud.loggingadmin.data; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.Optional; import net.firedevops.firemud.loggingadmin.repository.LogEventRepository; +import net.firedevops.firemud.loggingadmin.repository.ModerationActionRepository; +import net.firedevops.firemud.loggingadmin.repository.PlayerReportRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -15,34 +17,54 @@ class TestDataSeederTest { @Mock LogEventRepository logEventRepository; + @Mock PlayerReportRepository playerReportRepository; + @Mock ModerationActionRepository moderationActionRepository; private TestDataSeeder seeder; @BeforeEach void setup() { MockitoAnnotations.openMocks(this); - seeder = new TestDataSeeder(logEventRepository); + seeder = + new TestDataSeeder(logEventRepository, playerReportRepository, moderationActionRepository); } @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()); + when(moderationActionRepository.findFirstByTenantIdAndAccountIdAndActionAndReason( + 1L, 2L, "warning", "initial seed")) + .thenReturn(Optional.empty()); + seeder.run(new DefaultApplicationArguments(new String[] {})); - verify(logEventRepository).findFirstByTenantIdAndTypeAndMessage(1L, "INFO", "Service started"); verify(logEventRepository).save(any()); - verifyNoMoreInteractions(logEventRepository); + verify(playerReportRepository).save(any()); + verify(moderationActionRepository).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())); + when(moderationActionRepository.findFirstByTenantIdAndAccountIdAndActionAndReason( + 1L, 2L, "warning", "initial seed")) + .thenReturn(Optional.of(new net.firedevops.firemud.loggingadmin.entity.ModerationAction())); + seeder.run(new DefaultApplicationArguments(new String[] {})); verify(logEventRepository).save(any()); - verify(logEventRepository).findFirstByTenantIdAndTypeAndMessage(1L, "INFO", "Service started"); - verifyNoMoreInteractions(logEventRepository); + verify(playerReportRepository).save(any()); + verify(moderationActionRepository).save(any()); + verify(logEventRepository, never()).count(); + verify(playerReportRepository, never()).count(); + verify(moderationActionRepository, never()).count(); } } diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index d745490dae..6594d3a002 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -69,8 +69,6 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; class LoggingAdminGrpcServiceAuthTest { - private static final String ACCOUNT_UUID = "550e8400-e29b-41d4-a716-446655440000"; - @AfterEach void tearDown() { SessionContext.clear(); @@ -571,7 +569,7 @@ void applyModerationActionRejectsZeroSessionIdBeforeDispatch() { service.applyModerationAction( ApplyModerationActionRequest.newBuilder() .setTenantId("1") - .setAccountId(ACCOUNT_UUID) + .setAccountId("2") .setSessionId("0") .setAction("ban") .setReason("bad") @@ -611,7 +609,7 @@ void applyModerationActionRejectsAuthorizedCallerWhileMutationGateIsUnavailable( service.applyModerationAction( ApplyModerationActionRequest.newBuilder() .setTenantId("1") - .setAccountId(ACCOUNT_UUID) + .setAccountId("2") .setSessionId("9") .setAction("ban") .setReason("bad") @@ -673,7 +671,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertFalse(ref.get().getAllowed()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("Malformed claim: accountId", ref.get().getError().getMessage()); + assertEquals("accountId must be positive", ref.get().getError().getMessage()); verifyNoInteractions(moderationService); } @@ -682,7 +680,7 @@ void evaluateModerationPolicyAllowsAllowlistedInternalService() { SessionContext.setContext( "", List.of(), Map.of(), true, "game-session-service", "test-instance"); ModerationService moderationService = Mockito.mock(ModerationService.class); - when(moderationService.evaluatePolicy(1L, UUID.fromString(ACCOUNT_UUID), "CHAT_SEND")) + when(moderationService.evaluatePolicy(1L, 2L, "CHAT_SEND")) .thenReturn(new ModerationPolicyDecisionDto(true, "", "allowed", null)); LoggingAdminGrpcService service = new LoggingAdminGrpcService( @@ -695,7 +693,7 @@ void evaluateModerationPolicyAllowsAllowlistedInternalService() { service.evaluateModerationPolicy( EvaluateModerationPolicyRequest.newBuilder() .setTenantId("1") - .setAccountId(ACCOUNT_UUID) + .setAccountId("2") .setScope("CHAT_SEND") .build(), new StreamObserver<>() { @@ -714,7 +712,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertFalse(ref.get().hasError()); assertEquals(true, ref.get().getAllowed()); - verify(moderationService).evaluatePolicy(1L, UUID.fromString(ACCOUNT_UUID), "CHAT_SEND"); + verify(moderationService).evaluatePolicy(1L, 2L, "CHAT_SEND"); } @Test @@ -722,7 +720,7 @@ void evaluateModerationPolicyAllowsSocialGroupsInternalService() { SessionContext.setContext( "", List.of(), Map.of(), true, "social-groups-service", "test-instance"); ModerationService moderationService = Mockito.mock(ModerationService.class); - when(moderationService.evaluatePolicy(1L, UUID.fromString(ACCOUNT_UUID), "CHAT_SEND")) + when(moderationService.evaluatePolicy(1L, 2L, "CHAT_SEND")) .thenReturn(new ModerationPolicyDecisionDto(true, "", "allowed", null)); LoggingAdminGrpcService service = new LoggingAdminGrpcService( @@ -735,7 +733,7 @@ void evaluateModerationPolicyAllowsSocialGroupsInternalService() { service.evaluateModerationPolicy( EvaluateModerationPolicyRequest.newBuilder() .setTenantId("1") - .setAccountId(ACCOUNT_UUID) + .setAccountId("2") .setScope("CHAT_SEND") .build(), new StreamObserver<>() { @@ -754,7 +752,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertFalse(ref.get().hasError()); assertEquals(true, ref.get().getAllowed()); - verify(moderationService).evaluatePolicy(1L, UUID.fromString(ACCOUNT_UUID), "CHAT_SEND"); + verify(moderationService).evaluatePolicy(1L, 2L, "CHAT_SEND"); } @Test @@ -772,7 +770,7 @@ void evaluateModerationPolicyRejectsMissingCallerBeforeDispatch() { service.evaluateModerationPolicy( EvaluateModerationPolicyRequest.newBuilder() .setTenantId("1") - .setAccountId(ACCOUNT_UUID) + .setAccountId("2") .setScope("CHAT_SEND") .build(), new StreamObserver<>() { @@ -808,7 +806,7 @@ void evaluateModerationPolicyRejectsAuthenticatedEndUserBeforeDispatch() { service.evaluateModerationPolicy( EvaluateModerationPolicyRequest.newBuilder() .setTenantId("1") - .setAccountId(ACCOUNT_UUID) + .setAccountId("2") .setScope("CHAT_SEND") .build(), new StreamObserver<>() { @@ -844,7 +842,7 @@ void evaluateModerationPolicyRejectsNonAllowlistedInternalServiceBeforeDispatch( service.evaluateModerationPolicy( EvaluateModerationPolicyRequest.newBuilder() .setTenantId("1") - .setAccountId(ACCOUNT_UUID) + .setAccountId("2") .setScope("CHAT_SEND") .build(), new StreamObserver<>() { @@ -880,7 +878,7 @@ void evaluateModerationPolicyRejectsInternalCallerWithMissingServiceNameBeforeDi service.evaluateModerationPolicy( EvaluateModerationPolicyRequest.newBuilder() .setTenantId("1") - .setAccountId(ACCOUNT_UUID) + .setAccountId("2") .setScope("CHAT_SEND") .build(), new StreamObserver<>() { diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java index a76d43c138..23fa8db66f 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java @@ -7,7 +7,6 @@ import java.time.Instant; import java.util.List; -import java.util.UUID; import net.firedevops.firemud.loggingadmin.dto.ApplyModerationActionRequest; import net.firedevops.firemud.loggingadmin.dto.ModerationActionDto; import net.firedevops.firemud.loggingadmin.dto.ModerationPolicyDecisionDto; @@ -16,14 +15,11 @@ import net.firedevops.firemud.loggingadmin.repository.ModerationActionRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; class ModerationServiceImplTest { - private static final UUID ACCOUNT_ID = UUID.fromString("550e8400-e29b-41d4-a716-446655440000"); - @Mock ModerationActionRepository repository; @Mock ModerationActionMapper mapper; @@ -36,22 +32,19 @@ void setup() { @Test void applyActionSavesEntity() throws Exception { - ApplyModerationActionRequest req = - new ApplyModerationActionRequest(1L, ACCOUNT_ID.toString(), 9L, "ban", "test"); + ApplyModerationActionRequest req = new ApplyModerationActionRequest(1L, 2L, 9L, "ban", "test"); ModerationAction saved = new ModerationAction(); saved.setId(1L); saved.setCreatedAt(Instant.now()); when(repository.save(any())).thenReturn(saved); ModerationActionDto dto = - new ModerationActionDto(1L, 1L, ACCOUNT_ID, "ban", "test", saved.getCreatedAt(), null); + new ModerationActionDto(1L, 1L, 2L, "ban", "test", saved.getCreatedAt(), null); when(mapper.toDto(saved)).thenReturn(dto); ModerationActionDto result = service.applyAction(req); assertEquals(dto, result); - ArgumentCaptor actionCaptor = ArgumentCaptor.forClass(ModerationAction.class); - verify(repository).save(actionCaptor.capture()); - assertEquals(ACCOUNT_ID, actionCaptor.getValue().getAccountId()); + verify(repository).save(any(ModerationAction.class)); } @Test @@ -61,13 +54,12 @@ void evaluatePolicyBlocksGameplayAdmissionForActiveBan() { action.setReason("abuse"); when(repository.findActivePolicyActions( org.mockito.Mockito.eq(1L), - org.mockito.Mockito.eq(ACCOUNT_ID), + org.mockito.Mockito.eq(2L), org.mockito.Mockito.anyList(), org.mockito.Mockito.any())) .thenReturn(List.of(action)); - ModerationPolicyDecisionDto decision = - service.evaluatePolicy(1L, ACCOUNT_ID, "GAMEPLAY_ADMISSION"); + ModerationPolicyDecisionDto decision = service.evaluatePolicy(1L, 2L, "GAMEPLAY_ADMISSION"); assertEquals(false, decision.allowed()); assertEquals("gameplay_ban", decision.action()); 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 0d1c188852..4e3d815e4b 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 @@ -16,9 +16,6 @@ import org.junit.jupiter.api.Test; class ReportGrpcServiceTest { - private static final String REPORTER_UUID = "550e8400-e29b-41d4-a716-446655440000"; - private static final String TARGET_UUID = "6ba7b810-9dad-41d1-80b4-00c04fd430c8"; - @AfterEach void tearDown() { SessionContext.clear(); @@ -35,8 +32,8 @@ void createReportRejectsWhileMutationGateIsUnavailable() { service.createReport( CreateReportRequest.newBuilder() .setTenantId("1") - .setReporterAccountId(REPORTER_UUID) - .setTargetAccountId(TARGET_UUID) + .setReporterAccountId("2") + .setTargetAccountId("3") .setType("BUG") .setDescription("bad") .build(), @@ -73,8 +70,8 @@ void createReportDoesNotDelegateToPersistenceWhileMutationGateIsUnavailable() { service.createReport( CreateReportRequest.newBuilder() .setTenantId("1") - .setReporterAccountId(REPORTER_UUID) - .setTargetAccountId(TARGET_UUID) + .setReporterAccountId("2") + .setTargetAccountId("3") .setType("BUG") .setDescription("bad") .build(), @@ -98,7 +95,7 @@ public void onCompleted() {} } @Test - void createReportRejectsNumericReporterAccountIdBeforeDispatch() { + void createReportRejectsZeroReporterAccountIdBeforeDispatch() { SessionContext.setContext( "", List.of(), Map.of(), true, "social-groups-service", "test-instance"); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); @@ -108,7 +105,7 @@ void createReportRejectsNumericReporterAccountIdBeforeDispatch() { service.createReport( CreateReportRequest.newBuilder() .setTenantId("1") - .setReporterAccountId("2") + .setReporterAccountId("0") .setType("BUG") .setDescription("bad") .build(), @@ -129,11 +126,11 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("Malformed claim: reporterAccountId", ref.get().getError().getMessage()); + assertEquals("reporterAccountId must be positive", ref.get().getError().getMessage()); } @Test - void createReportRejectsNilTargetAccountIdBeforeDispatch() { + void createReportRejectsZeroTargetAccountIdBeforeDispatch() { SessionContext.setContext( "", List.of(), Map.of(), true, "social-groups-service", "test-instance"); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); @@ -143,8 +140,8 @@ void createReportRejectsNilTargetAccountIdBeforeDispatch() { service.createReport( CreateReportRequest.newBuilder() .setTenantId("1") - .setReporterAccountId(REPORTER_UUID) - .setTargetAccountId("00000000-0000-0000-0000-000000000000") + .setReporterAccountId("2") + .setTargetAccountId("0") .setType("BUG") .setDescription("bad") .build(), @@ -165,7 +162,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("Invalid claim: targetAccountId", ref.get().getError().getMessage()); + assertEquals("targetAccountId must be positive", ref.get().getError().getMessage()); } @Test @@ -177,7 +174,7 @@ void createReportRejectsMissingCallerBeforePersistence() { service.createReport( CreateReportRequest.newBuilder() .setTenantId("1") - .setReporterAccountId(REPORTER_UUID) + .setReporterAccountId("2") .setType("BUG") .setDescription("bad") .build(), @@ -209,7 +206,7 @@ void createReportRejectsAuthenticatedEndUserBeforePersistence() { service.createReport( CreateReportRequest.newBuilder() .setTenantId("1") - .setReporterAccountId(REPORTER_UUID) + .setReporterAccountId("2") .setType("BUG") .setDescription("bad") .build(), @@ -242,7 +239,7 @@ void createReportRejectsWrongInternalServiceBeforePersistence() { service.createReport( CreateReportRequest.newBuilder() .setTenantId("1") - .setReporterAccountId(REPORTER_UUID) + .setReporterAccountId("2") .setType("BUG") .setDescription("bad") .build(), 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 ce641c7bae..5d086866e2 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 @@ -11,9 +11,6 @@ import org.junit.jupiter.api.Test; class ReportServiceImplTest { - private static final String REPORTER_UUID = "550e8400-e29b-41d4-a716-446655440000"; - private static final String TARGET_UUID = "6ba7b810-9dad-41d1-80b4-00c04fd430c8"; - @Test void createReportFailsClosedWithoutTouchingPlayerReportsRepository() { PlayerReportRepository repository = mock(PlayerReportRepository.class); @@ -23,9 +20,7 @@ void createReportFailsClosedWithoutTouchingPlayerReportsRepository() { UnsupportedOperationException exception = assertThrows( UnsupportedOperationException.class, - () -> - service.createReport( - new CreateReportRequest(1L, REPORTER_UUID, TARGET_UUID, "BUG", "bad"))); + () -> service.createReport(new CreateReportRequest(1L, 2L, 3L, "BUG", "bad"))); assertEquals( "Report creation is unavailable until the shared mutation gate is implemented", From 3c6dc4d05a0e6ff39f816ccb52b1feda3e28e0c5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 20:40:20 +1300 Subject: [PATCH 3/5] Bind Social UUID migration fixture to runtime schema --- .../SocialAccountUuidMigrationIntegrationTest.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialAccountUuidMigrationIntegrationTest.java b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialAccountUuidMigrationIntegrationTest.java index 9c8c41a701..46f21c6bd6 100644 --- a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialAccountUuidMigrationIntegrationTest.java +++ b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialAccountUuidMigrationIntegrationTest.java @@ -69,7 +69,8 @@ void freshAndEmptyV9UpgradeConvergeAllAccountColumnsWithoutChangingOtherIdentity assertThat(constraints(upgraded)).containsAll(constraintsBefore); assertThat(rows(upgraded, HISTORY_TABLE, "installed_rank").subList(0, historyBefore.size())) .containsExactlyElementsOf(historyBefore); - assertThat(rows(upgraded, HISTORY_TABLE, "installed_rank")).hasSize(historyBefore.size() + 1); + // Full runtime migration discovery adds V10 and Saga V1000–V1002 after V9. + assertThat(rows(upgraded, HISTORY_TABLE, "installed_rank")).hasSize(historyBefore.size() + 4); } @ParameterizedTest @@ -269,7 +270,8 @@ private static Flyway flyway(Database database, String target) { .schemas(database.schema()) .defaultSchema(database.schema()) .table(HISTORY_TABLE) - .locations("classpath:db/migration"); + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", database.schema())); if (target != null) { config.target(MigrationVersion.fromVersion(target)); } From 4d50b2e545b2ab34847922d898ca56b8b5d8b38b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:24:24 +1300 Subject: [PATCH 4/5] Allow Validation for stacked pull requests --- .github/workflows/ci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8ffe77bb8f..7a90f08063 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: From 65dc371eeba4e455361b5d3ceba117ab544fd8d4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:36:23 +1300 Subject: [PATCH 5/5] Carry forward reviewed CI safety corrections --- .github/workflows/ci.yml | 2 +- .../workflows/publish-pr-runtime-images.yml | 4 +- .github/workflows/security.yml | 3 +- .github/workflows/smoke.yml | 51 +++++++++++- .github/workflows/static-analysis-summary.yml | 3 +- .../preview/resolve-preview-image-tag.sh | 2 +- .../tests/ci-validation-summary-contract.sh | 12 +++ .../pr-required-gate-context-contract.sh | 83 +++++++++++++++++++ .../tests/pr-retarget-workflow-contract.sh | 79 +++++++++++++++++- .../pr-runtime-image-publication-contract.sh | 29 ++++++- dev-tools/tests/security-summary-contract.sh | 51 ++++++++++++ .../tests/static-analysis-summary-contract.sh | 11 ++- 12 files changed, 314 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7a90f08063..15afae6f35 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1255,7 +1255,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) {