From 1e3f4d8cca15dd4f293898510330f251d70e103c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 13:01:14 +1200 Subject: [PATCH 01/28] Include equipment slot groups in Entity draft digest v2 --- .../api-contracts.md | 2 +- .../runtime-and-data.md | 2 +- .../EntityDraftDesignDigestServiceImpl.java | 138 ++++++++++-------- ...ntityDraftDesignDigestServiceImplTest.java | 87 +++++++++++ .../service/impl/PublishGateServiceImpl.java | 2 +- .../impl/PublishGateServiceImplTest.java | 112 +++++++++++++- ...ordedParticipantDigestServiceImplTest.java | 70 +++++++++ 7 files changed, 343 insertions(+), 70 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index a64502c116..1eafebaff4 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -81,7 +81,7 @@ Implementation Notes: - The current implementation hashes the version-scoped entity-definition rows for the requested `(tenantId, versionId)` and returns synthetic `appliedCommitId = "version:"` until the later applied-revision ledger lands. - Current version-scoped digest inputs include `items`, `npcs`, and `crafting_recipes`; later entity-template families must join this same `(tenantId, versionId)` digest contract when introduced. -- The current item projection omits `equipmentSlotGroupKey`, although runtime equipment admission consumes that authored value when checking an item against an equipment slot definition. A change to the slot-group constraint can therefore leave the Entity participant digest unchanged. The target manifest includes the normalized optional field and bumps `digestSchemaVersion` (from `1` to `2`); proof must show cross-version slot-group changes alter the digest and are caught by the publish gate. +- The current item projection includes optional `equipmentSlotGroupKey`, normalized like runtime equipment admission (null/blank to empty; otherwise trim and uppercase), and reports `digestSchemaVersion=2`. Focused producer proof covers normalized equivalents, distinct slot-group constraints, and tenant/version-scoped reads; Game Design's publish gate accepts Entity v2 and rejects v1 or unsupported evidence. Previously recorded v1 evidence still requires affected-scope replay or recomputation, re-recording, and readback before publish; this code change does not perform a live-data migration. - Included objects: - version-scoped entity-template tables such as item, NPC, equipment, loot-table, and balance-curve definitions keyed by `(tenantId, versionId)`; diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index fadb5030df..343f07ea42 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -19,7 +19,7 @@ This document defines Entity Management’s runtime model, persistence ownership - The live Entity schema does not yet represent the target namespace-stable identity for durable S1/S2 state: `characters` and `actor_resource_states` retain legacy `playable_state_key`, while `inventory`, `character_friend`, `character_equipment`, and durable holder/containment rows omit `playableStateNamespaceId` (and some omit `tenant_id` entirely). The current repositories consequently cannot enforce the target `{tenantId, playableStateNamespaceId, domainObjectId}` identity at the SQL boundary. A convergent migration, legacy-row disposition/backfill evidence, namespace-aware repository predicates, and focused isolation proof remain required; until those are complete, legacy `playable_state_key` rows (including `character_friend` associations reached through them) are not namespace-isolated proof and cutover readers must not treat them as namespace-backed survivor state. This does not change the target contract above. - The live `item_stacks` uniqueness constraint includes nullable holder columns, so PostgreSQL can accept duplicate rows for the same tenant/holder/item/fingerprint when another holder column is `NULL`. Inventory and container mutation paths still use find-then-create/save rather than an atomic conflict-safe operation. With no explicit `stackFamilyKey`, source resolution rejects more than one candidate row; with an explicit family key, the current implementation selects the first matching row and does not reject duplicate matches. Target resolution must enforce exactly one matching stack (or fail closed), alongside holder-kind-specific uniqueness or normalized non-null identity, atomic upsert/locking, and concurrent proof. - The current `characterGraph` helper caches `getWithInventory(characterId)` by character ID alone with a TTL and performs no namespace or authoritative version validation. It is not the target namespace-qualified Class A `character-cache:*` contract; until that contract is implemented and proved, this cache is not correctness authority. -- `EntityDraftDesignDigestServiceImpl` currently emits `digestSchemaVersion=1` without hashing item `equipmentSlotGroupKey`, while `EquipmentServiceImpl` uses that field for slot compatibility admission. The digest is therefore incomplete for equipment semantics: different slot-group constraints may attest the same content digest. Target convergence adds the normalized field, bumps the schema version, and proves cross-version digest isolation plus publish-gate rejection of a changed constraint. +- `EntityDraftDesignDigestServiceImpl` now emits `digestSchemaVersion=2` and hashes normalized item `equipmentSlotGroupKey`, matching `EquipmentServiceImpl` slot compatibility admission. Focused tests cover equivalent optional-key spellings, distinct slot-group constraints, and tenant/version-scoped reads; Game Design's publish gate requires Entity v2 and rejects v1. Existing v1 participant baselines remain invalid: affected `(tenantId, versionId)` evidence must be replayed or recomputed, re-recorded with its applied commit/digest/schema, and read back before publish. No live baseline migration or cross-service publish proof is claimed by this slice. ## Architecture and Design Notes diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java index 29256aa92c..a8d9a6936b 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java @@ -5,6 +5,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Comparator; +import java.util.Locale; import java.util.Map; import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.entitymanagement.entity.CraftingIngredient; @@ -14,6 +15,7 @@ import net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService; import org.springframework.stereotype.Service; import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.SerializationFeature; @Service @SuppressFBWarnings( @@ -21,7 +23,7 @@ justification = "Injected repositories and ObjectMapper are managed dependencies kept internal.") public class EntityDraftDesignDigestServiceImpl implements EntityDraftDesignDigestService { - private static final int DIGEST_SCHEMA_VERSION = 1; + private static final int DIGEST_SCHEMA_VERSION = 2; private final ItemRepository itemRepository; private final NpcRepository npcRepository; @@ -48,66 +50,76 @@ public EntityDraftDesignDigest getDraftDesignDigest(String tenantId, String vers long versionKey = RequestIdValidation.requirePositiveLong(versionId, "versionId"); try { String canonicalJson = - objectMapper.writeValueAsString( - Map.of( - "items", - itemRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - item -> - Map.of( - "id", item.getId(), - "name", item.getName(), - "description", value(item.getDescription()), - "equipmentSlot", value(item.getEquipmentSlot()), - "container", item.isContainer(), - "stackable", item.isStackable(), - "stackCompatibilityMode", item.getStackCompatibilityMode().name(), - "stackVariantKey", value(item.getStackVariantKey()), - "effectPayloadJson", value(item.getEffectPayloadJson()))) - .toList(), - "npcs", - npcRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - npc -> - Map.of( - "id", npc.getId(), - "name", npc.getName(), - "behavior", value(npc.getBehavior()), - "respawnDelaySeconds", npc.getRespawnDelaySeconds())) - .toList(), - "craftingRecipes", - craftingRecipeRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - recipe -> - Map.of( - "id", - recipe.getId(), - "name", - recipe.getName(), - "resultItemId", - recipe.getResultItem().getId(), - "resultQuantity", - recipe.getResultQuantity(), - "ingredients", - recipe.getIngredients().stream() - .sorted( - Comparator.comparing( - (CraftingIngredient ingredient) -> - ingredient.getItem().getId()) - .thenComparingInt(CraftingIngredient::getQuantity)) - .map( - ingredient -> - Map.of( - "itemId", ingredient.getItem().getId(), - "quantity", ingredient.getQuantity())) - .toList())) - .toList())); + objectMapper + .writer(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS) + .writeValueAsString( + Map.of( + "items", + itemRepository + .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) + .stream() + .map( + item -> + Map.ofEntries( + Map.entry("id", item.getId()), + Map.entry("name", item.getName()), + Map.entry("description", value(item.getDescription())), + Map.entry("equipmentSlot", value(item.getEquipmentSlot())), + Map.entry( + "equipmentSlotGroupKey", + normalizeOptionalKey(item.getEquipmentSlotGroupKey())), + Map.entry("container", item.isContainer()), + Map.entry("stackable", item.isStackable()), + Map.entry( + "stackCompatibilityMode", + item.getStackCompatibilityMode().name()), + Map.entry( + "stackVariantKey", value(item.getStackVariantKey())), + Map.entry( + "effectPayloadJson", value(item.getEffectPayloadJson())))) + .toList(), + "npcs", + npcRepository + .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) + .stream() + .map( + npc -> + Map.of( + "id", npc.getId(), + "name", npc.getName(), + "behavior", value(npc.getBehavior()), + "respawnDelaySeconds", npc.getRespawnDelaySeconds())) + .toList(), + "craftingRecipes", + craftingRecipeRepository + .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) + .stream() + .map( + recipe -> + Map.of( + "id", + recipe.getId(), + "name", + recipe.getName(), + "resultItemId", + recipe.getResultItem().getId(), + "resultQuantity", + recipe.getResultQuantity(), + "ingredients", + recipe.getIngredients().stream() + .sorted( + Comparator.comparing( + (CraftingIngredient ingredient) -> + ingredient.getItem().getId()) + .thenComparingInt( + CraftingIngredient::getQuantity)) + .map( + ingredient -> + Map.of( + "itemId", ingredient.getItem().getId(), + "quantity", ingredient.getQuantity())) + .toList())) + .toList())); return new EntityDraftDesignDigest( tenantId, versionId, @@ -123,6 +135,10 @@ private String value(String value) { return value == null ? "" : value; } + private String normalizeOptionalKey(String value) { + return value == null || value.isBlank() ? "" : value.trim().toUpperCase(Locale.ROOT); + } + private String sha256(String value) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java index 573ae28afc..53e0423e42 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java @@ -1,12 +1,15 @@ package net.firedevops.firemud.entitymanagement.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.List; +import net.firedevops.firemud.entitymanagement.entity.Item; import net.firedevops.firemud.entitymanagement.repository.CraftingRecipeRepository; import net.firedevops.firemud.entitymanagement.repository.ItemRepository; import net.firedevops.firemud.entitymanagement.repository.NpcRepository; +import net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService.EntityDraftDesignDigest; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import tools.jackson.databind.ObjectMapper; @@ -66,4 +69,88 @@ void computesDigestFromVersionScopedTemplateRows() { Mockito.verify(itemRepository).findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L); Mockito.verify(itemRepository, Mockito.never()).findByTenantIdOrderByIdAsc(Mockito.anyLong()); } + + @Test + void normalizesMissingAndBlankEquipmentSlotGroupKeysToTheSameDigest() { + var missingDigest = digestForEquipmentSlotGroupKey(null); + var blankDigest = digestForEquipmentSlotGroupKey(" \t "); + + assertEquals(2, missingDigest.digestSchemaVersion()); + assertEquals(missingDigest.contentDigest(), blankDigest.contentDigest()); + } + + @Test + void equipmentSlotGroupConstraintChangesTheDigest() { + var wingsDigest = digestForEquipmentSlotGroupKey(" wings "); + var normalizedWingsDigest = digestForEquipmentSlotGroupKey("WINGS"); + var torsoDigest = digestForEquipmentSlotGroupKey("TORSO"); + + assertEquals(2, wingsDigest.digestSchemaVersion()); + assertEquals(wingsDigest.contentDigest(), normalizedWingsDigest.contentDigest()); + assertNotEquals(wingsDigest.contentDigest(), torsoDigest.contentDigest()); + } + + @Test + void readsItemsWithinTheRequestedTenantAndVersion() { + ItemRepository itemRepository = Mockito.mock(ItemRepository.class); + NpcRepository npcRepository = Mockito.mock(NpcRepository.class); + CraftingRecipeRepository craftingRecipeRepository = + Mockito.mock(CraftingRecipeRepository.class); + Mockito.when(itemRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of(item(11L, "WINGS"))); + Mockito.when(itemRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 8L)) + .thenReturn(List.of(item(11L, "TORSO"))); + Mockito.when(itemRepository.findByTenantIdAndVersionIdOrderByIdAsc(2L, 7L)) + .thenReturn(List.of(item(11L, null))); + for (long tenantId : List.of(1L, 2L)) { + for (long versionId : List.of(7L, 8L)) { + Mockito.when(npcRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantId, versionId)) + .thenReturn(List.of()); + Mockito.when( + craftingRecipeRepository.findByTenantIdAndVersionIdOrderByIdAsc( + tenantId, versionId)) + .thenReturn(List.of()); + } + } + EntityDraftDesignDigestServiceImpl service = + new EntityDraftDesignDigestServiceImpl( + itemRepository, npcRepository, craftingRecipeRepository, new ObjectMapper()); + + var tenantOneVersionSeven = service.getDraftDesignDigest("1", "7"); + var tenantOneVersionEight = service.getDraftDesignDigest("1", "8"); + var tenantTwoVersionSeven = service.getDraftDesignDigest("2", "7"); + + assertNotEquals(tenantOneVersionSeven.contentDigest(), tenantOneVersionEight.contentDigest()); + assertNotEquals(tenantOneVersionSeven.contentDigest(), tenantTwoVersionSeven.contentDigest()); + Mockito.verify(itemRepository).findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L); + Mockito.verify(itemRepository).findByTenantIdAndVersionIdOrderByIdAsc(1L, 8L); + Mockito.verify(itemRepository).findByTenantIdAndVersionIdOrderByIdAsc(2L, 7L); + Mockito.verify(itemRepository, Mockito.never()).findByTenantIdOrderByIdAsc(Mockito.anyLong()); + } + + private static EntityDraftDesignDigest digestForEquipmentSlotGroupKey(String groupKey) { + ItemRepository itemRepository = Mockito.mock(ItemRepository.class); + NpcRepository npcRepository = Mockito.mock(NpcRepository.class); + CraftingRecipeRepository craftingRecipeRepository = + Mockito.mock(CraftingRecipeRepository.class); + Mockito.when(itemRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of(item(11L, groupKey))); + Mockito.when(npcRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of()); + Mockito.when(craftingRecipeRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of()); + EntityDraftDesignDigestServiceImpl service = + new EntityDraftDesignDigestServiceImpl( + itemRepository, npcRepository, craftingRecipeRepository, new ObjectMapper()); + + return service.getDraftDesignDigest("1", "7"); + } + + private static Item item(Long id, String equipmentSlotGroupKey) { + Item item = new Item(); + item.setId(id); + item.setName("Test item"); + item.setEquipmentSlotGroupKey(equipmentSlotGroupKey); + return item; + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java index 33fa500a66..1ad9456b4a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java @@ -25,7 +25,7 @@ public class PublishGateServiceImpl implements PublishGateService { private static final Map SUPPORTED_DIGEST_SCHEMA_VERSIONS = Map.of( PublishParticipantKey.WORLD_MANAGEMENT.name(), 2, - PublishParticipantKey.ENTITY_MANAGEMENT.name(), 1, + PublishParticipantKey.ENTITY_MANAGEMENT.name(), 2, PublishParticipantKey.GAME_LOGIC.name(), 1, PublishParticipantKey.AUTOMATION_SCRIPTING.name(), 4, PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE.name(), 1); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java index 9d5c14380a..751b94f482 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java @@ -48,7 +48,7 @@ void setUp() { } @Test - void collectFullVersionParticipantDigestsPassesWhenParticipantsConverge() { + void collectFullVersionParticipantDigestsAcceptsEntitySchemaTwoWhenParticipantsConverge() { VersionDto version = new VersionDto( 7L, @@ -71,7 +71,7 @@ void collectFullVersionParticipantDigestsPassesWhenParticipantsConverge() { any(PublicationDigestRequestBinding.class))) .thenReturn( new PublishParticipantDigestDto( - "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null)); + "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 2, null, null)); when(gameLogicClient.getDraftDesignDigestForVersion(any(PublicationDigestRequestBinding.class))) .thenReturn( new PublishParticipantDigestDto( @@ -90,6 +90,7 @@ void collectFullVersionParticipantDigestsPassesWhenParticipantsConverge() { assertEquals(5, digests.size()); assertEquals("WORLD_MANAGEMENT", digests.get(0).participantKey()); + assertEquals(2, digests.get(1).digestSchemaVersion()); assertDoesNotThrow(() -> service.assertGatePassed(version, digests)); } @@ -113,7 +114,7 @@ void fullVersionGateFailsClosedForUnsupportedSchema() { new PublishParticipantDigestDto( "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), new PublishParticipantDigestDto( - "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), + "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 2, null, null), new PublishParticipantDigestDto( "GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null), new PublishParticipantDigestDto( @@ -163,6 +164,69 @@ void fullVersionGateChecksEachParticipantAgainstItsOwnDigestSchema() { assertTrue(thrown.getMessage().contains("ENTITY_MANAGEMENT")); } + @Test + void fullVersionGateRejectsLegacyEntitySchemaOne() { + VersionDto version = fullVersion(); + List digests = fullVersionDigests(1, "digest-entity", "version:7"); + + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, () -> service.assertGatePassed(version, digests)); + + assertEquals(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, thrown.failureCode()); + assertTrue(thrown.getMessage().contains("ENTITY_MANAGEMENT")); + } + + @Test + void fullVersionGateRejectsUnsupportedFutureEntitySchemaThree() { + VersionDto version = fullVersion(); + List digests = fullVersionDigests(3, "digest-entity", "version:7"); + + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, () -> service.assertGatePassed(version, digests)); + + assertEquals(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, thrown.failureCode()); + assertTrue(thrown.getMessage().contains("ENTITY_MANAGEMENT")); + } + + @Test + void fullVersionGateRejectsEntityDigestWithoutSchemaEvidence() { + VersionDto version = fullVersion(); + List digests = + fullVersionDigests(null, "digest-entity", "version:7"); + + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, () -> service.assertGatePassed(version, digests)); + + assertEquals(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, thrown.failureCode()); + } + + @Test + void fullVersionGateRejectsEntityDigestWithoutContentEvidence() { + VersionDto version = fullVersion(); + List digests = fullVersionDigests(2, null, "version:7"); + + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, () -> service.assertGatePassed(version, digests)); + + assertEquals(PublishGateFailureCode.MISSING_CONTENT_DIGEST, thrown.failureCode()); + } + + @Test + void fullVersionGateRejectsEntityDigestWithoutAppliedCommitEvidence() { + VersionDto version = fullVersion(); + List digests = fullVersionDigests(2, "digest-entity", null); + + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, () -> service.assertGatePassed(version, digests)); + + assertEquals(PublishGateFailureCode.MISSING_APPLIED_COMMIT, thrown.failureCode()); + } + @Test void fullVersionGateFailsClosedForUnknownParticipantKey() { VersionDto version = @@ -239,7 +303,7 @@ void fullVersionGateFailsClosedForDuplicateParticipantKey() { new PublishParticipantDigestDto( "WORLD_MANAGEMENT", "7", "version:7", "digest-world-2", 2, null, null), new PublishParticipantDigestDto( - "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), + "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 2, null, null), new PublishParticipantDigestDto( "GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null), new PublishParticipantDigestDto( @@ -273,7 +337,7 @@ void fullVersionGateFailsClosedForNullParticipantObservation() { "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), null, new PublishParticipantDigestDto( - "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), + "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 2, null, null), new PublishParticipantDigestDto( "GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null), new PublishParticipantDigestDto( @@ -306,7 +370,7 @@ void fullVersionGateFailsClosedForMissingSchemaVersion() { new PublishParticipantDigestDto( "WORLD_MANAGEMENT", "7", "version:7", "digest-world", null, null, null), new PublishParticipantDigestDto( - "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), + "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 2, null, null), new PublishParticipantDigestDto( "GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null), new PublishParticipantDigestDto( @@ -491,4 +555,40 @@ void scriptPatchGateRejectsWrongBaseScope() { assertEquals(PublishGateFailureCode.PARTICIPANT_SCOPE_MISMATCH, thrown.failureCode()); } + + private VersionDto fullVersion() { + return new VersionDto( + 7L, + "tenant-1", + 8, + VersionLifecycleState.PUBLISHED, + 2L, + null, + null, + false, + "notes", + LocalDateTime.now(), + LocalDateTime.now()); + } + + private List fullVersionDigests( + Integer entitySchemaVersion, String entityContentDigest, String entityAppliedCommitId) { + return List.of( + new PublishParticipantDigestDto( + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", + "7", + entityAppliedCommitId, + entityContentDigest, + entitySchemaVersion, + null, + null), + new PublishParticipantDigestDto( + "GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null), + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 4, null, null), + new PublishParticipantDigestDto( + "GAME_DESIGN_CONTROL_PLANE", "7", "version:7", "digest-design", 1, null, null)); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java index a040dde247..1b97f1b1d4 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java @@ -69,6 +69,76 @@ void assertMatchesRecordedDigestsFailsClosedOnDigestMismatch() { assertEquals(PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, thrown.failureCode()); } + @Test + void entityV2CannotReuseRecordedV1BaselineEvenWhenHashTextMatches() { + RecordedParticipantDigest recorded = new RecordedParticipantDigest(); + recorded.setScopeValue("7"); + recorded.setDigestSchemaVersion(1); + recorded.setContentDigest("same-hash-text"); + when(repository.findByTenantIdAndPublishTypeAndParticipantKeyAndAppliedCommitId( + "tenant-1", + PublishType.FULL_VERSION, + PublishParticipantKey.ENTITY_MANAGEMENT, + null, + "7", + "version:7")) + .thenReturn(Optional.of(recorded)); + + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, + () -> + service.assertMatchesRecordedDigests( + "tenant-1", + PublishType.FULL_VERSION, + List.of( + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", + "7", + "version:7", + "same-hash-text", + 2, + null, + null)))); + + assertEquals(PublishGateFailureCode.RECORDED_DIGEST_SCHEMA_MISMATCH, thrown.failureCode()); + } + + @Test + void entityV2RejectsChangedConstraintDigestAgainstRecordedV2Baseline() { + RecordedParticipantDigest recorded = new RecordedParticipantDigest(); + recorded.setScopeValue("7"); + recorded.setDigestSchemaVersion(2); + recorded.setContentDigest("before-slot-group-change"); + when(repository.findByTenantIdAndPublishTypeAndParticipantKeyAndAppliedCommitId( + "tenant-1", + PublishType.FULL_VERSION, + PublishParticipantKey.ENTITY_MANAGEMENT, + null, + "7", + "version:7")) + .thenReturn(Optional.of(recorded)); + + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, + () -> + service.assertMatchesRecordedDigests( + "tenant-1", + PublishType.FULL_VERSION, + List.of( + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", + "7", + "version:7", + "after-slot-group-change", + 2, + null, + null)))); + + assertEquals(PublishGateFailureCode.RECORDED_CONTENT_DIGEST_MISMATCH, thrown.failureCode()); + } + @Test void recordVerifiedDigestsStoresBaselineAndVerificationWorkflow() { when(repository.findByTenantIdAndPublishTypeAndParticipantKeyAndAppliedCommitId( From 09cc6230c48d1bb356f16ede98a5079cabc5f31e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 14:38:10 +1200 Subject: [PATCH 02/28] Add guarded Entity digest baseline migration job --- .../game-design-service/operations.md | 14 + .../game-design-service/version-control.md | 4 +- ...ame-authoring-publishing-and-activation.md | 2 + ...tity-digest-baseline-migration-contract.sh | 375 ++++++++++ .../entity-digest-baseline-migration-job.yaml | 304 +++++++++ .../firemud/templates/network-policies.yaml | 46 ++ k8s/helm/firemud/values.yaml | 20 + .../firemud/common/grpc/GrpcPeerIdentity.java | 1 + .../common/grpc/GrpcPeerIdentityTest.java | 9 + .../common/security/PublicationReadGuard.java | 9 + .../security/PublicationReadGuardTest.java | 41 ++ .../src/main/resources/application.yml | 2 + ...ntityPublicationReadConfigurationTest.java | 30 + .../GameDesignServiceApplication.java | 25 +- .../EntityDigestBaselineMigrationAudit.java | 37 + ...ntityDigestBaselineMigrationJobRunner.java | 164 +++++ ...igestBaselineMigrationAuditRepository.java | 203 ++++++ .../RecordedParticipantDigestRepository.java | 146 ++++ .../EntityDigestBaselineMigrationService.java | 641 ++++++++++++++++++ ...tyDigestBaselineMigrationWriteService.java | 92 +++ .../V29__entity_digest_baseline_migration.sql | 53 ++ ...igestBaselineMigrationIntegrationTest.java | 423 ++++++++++++ ...yDigestBaselineMigrationJobRunnerTest.java | 60 ++ ...ityDigestBaselineMigrationServiceTest.java | 551 +++++++++++++++ ...gestBaselineMigrationWriteServiceTest.java | 111 +++ 25 files changed, 3361 insertions(+), 2 deletions(-) create mode 100644 dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh create mode 100644 k8s/helm/firemud/templates/entity-digest-baseline-migration-job.yaml create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/EntityPublicationReadConfigurationTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/EntityDigestBaselineMigrationAudit.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/EntityDigestBaselineMigrationAuditRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V29__entity_digest_baseline_migration.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index ec5eba5173..970db559bf 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -28,4 +28,18 @@ The target publication boundary treats object-store export as a durable candidat ## Local Development Notes +### Historical Entity digest baseline migration + +**Current implementation status:** The one-shot Game Design maintenance Job and guarded owner-local v1→v2 baseline transition are implemented, but no retained row set or live certificate/consumer/readback outcome has been verified by this document. The Job is disabled in ordinary Helm releases and must be invoked only from a trusted operator context, using a reviewed immutable Game Design image digest. It is not a public API, a general admin role, or a PR-controlled executor. Its dedicated `game-design-baseline-migrator` Kubernetes service account has no Kubernetes API verbs, and its separate client certificate may read only Entity Management's bound `GetDraftDesignDigest` RPC. No Game Design, Account, or Game Session mutation API is delegated to that identity. The Job only writes Game Design's own baseline and audit tables through its guarded service operation; it never accesses Entity's database. + +Use a controlled pre-v1 publication window for the affected Entity v1 full-version scopes. Drain in-flight publication and prevent new publication on those scopes before comparing rows or deploying the writer. Deploy the migration-capable Game Design reader/reconciler image first so retained stored v1 and v2 baseline shapes can be inspected; its publish gate still requires v2 and never compares v1 content with v2 content. Then deploy Entity's v2 producer image. Because #2872 already has a v2-only gate, deploying it alone may temporarily block affected v1 publication; this is an accepted fail-closed maintenance window, not seamless dual-reader availability. Verify actual service image digests and deployment order before proceeding; if the image topology cannot maintain that sequence, stop instead of relaxing the gate. The current Entity applied-commit token is synthetic `version:` and does not prove durable applied-revision convergence. + +Before invoking a Job, verify the exact Kubernetes context and namespace, the authorized operator identity and approved maintenance window, both current service image digests, database backup/recovery posture, completed in-flight publication drain, and the dedicated migrator certificate's issuer, `Ready` state, URI SAN, trust chain, projected Secret, and actual mTLS acceptance at Entity. The hosted trust/controller admission policy must include this narrowly named identity before requesting the leaf; a rendered Certificate or Secret name alone is not issuance or served-identity proof. The trusted operator must create an immutable expected-source ConfigMap or Secret from a read-only exact database row, including baseline ID, tenant, `FULL_VERSION`, `ENTITY_MANAGEMENT`, null base version, version scope, applied commit, digest, schema `1`, and both workflow IDs and timestamps. Do not place this manifest, credentials, or raw retained row values in a PR or CI artifact. Check that the source object is immutable before applying the Job. The Job's `targetNamespace`, tenant/version, operation ID, actor identity, and expected-source object are all fixed for that invocation; a changed command gets a new operation ID, never a reinterpretation of the old one. + +The chart's `previewStack.entityDigestBaselineMigration` values are disabled by default. From the trusted operator revision, supply an image pinned as `repository@sha256:`, exact `targetNamespace`, the dedicated `firemud-grpc-game-design-baseline-migrator` Secret, and `mode`. `enumerate` returns at most 500 Entity schema-v1 full-version rows after one baseline ID; repeat with its returned keyset cursor until an empty page proves no more rows at the quiesced snapshot. `preflight` classifies one exact tenant/version as v1, v2, absent, ambiguous, or unsupported, and refuses a missing or script-only Version. `migrate` requires one stable operation ID, exact tenant/version, actor identity, and the immutable expected-source object. The Java runner verifies its namespace, dedicated service account, and certificate URI identity before reading or writing. A missing identity, policy, input, row, version, exact-old match, or v2 Entity response fails closed. Render and inspect the operator overlay before installation; do not leave `enabled: true` in the ordinary chart values or an unattended release upgrade. Completed Jobs are deliberately not Helm hooks, so an unchanged upgrade does not rerun them; a changed immutable Job spec is rejected and needs an explicit trusted disposition. + +For each affected scope, retain the preflight row ID and complete source tuple privately, run `migrate`, and require its reported operation/audit/baseline IDs and disposition. The Game Design transaction conditionally replaces the exact old row and inserts an immutable before/after audit atomically. An exact retry of the same operation reads the existing audit and baseline rather than writing again; a lost acknowledgement is resolved by that same operation identity and exact readback. A changed source, ambiguous scope, different actor/workload binding, mismatched Entity v2 schema/scope/digest/commit, or unproved write outcome is a stop condition. Independently read back `publish_recorded_participant_digest` by baseline ID and `entity_digest_baseline_migration_audit` by operation ID from Game Design's PostgreSQL schema; compare the new schema/digest/commit/provenance, complete old tuple, observed v2 tuple, operation, actor/workload, outcome, and timestamp exactly. Never count Job completion alone as database proof. Keep the before/after records with the private migration log, excluding secrets and certificate keys. + +If no retained Entity v1 rows exist, record the exact namespace, database/schema, query time, quiescence evidence, and an empty bounded enumeration through its terminal page; separately preflight every affected known tenant/version scope and record its state. This is a no-data boundary, not a claim that migration ran. If a migration fails or proof is incomplete, leave affected publication closed and retain the old row/audit evidence; do not restore a v1 hash over an audited v2 row or weaken the v2 publish gate. Resume only after an exact retry/readback or an explicit database recovery decision with equivalent provenance. Reopen publication only after every enumerated v1 row has a verified v2 baseline and audit (or the scoped no-data proof), the Entity v2 producer and Game Design reader remain healthy, and the normal v2 publish gate succeeds. Live retained data, PostgreSQL readback, certificate bootstrap, and served mTLS proof must be reported separately from local fixtures and static Helm renders. + `TestDataSeeder` populates a demo game, template, revision and version only when explicit smoke/runtime seeding is enabled through deployment config (`FIREMUD_SMOKE_SEED_DEMO_RUNTIME_ENABLED=true` in the local Compose smoke stack). Run `services/game-design-service/smoke-test.sh` to verify both REST and gRPC endpoints. The lightweight maintained application smoke now lives under `src/test/java/integration`; the old disabled GHCR-based cross-service placeholder was removed because it did not prove a meaningful current contract. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 4e534978f5..be430b9647 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -119,7 +119,7 @@ services as the source of truth for the current Draft template graphs: #### Owner-to-owner digest authorization and tenant identity -`GetDraftDesignDigest` is a read-only owner-to-owner publication read across World Management, Entity Management, Game Logic, and Automation & Scripting. Every receiver uses the shared [Security Architecture](../../system-architecture-security.md) and [Authentication & Authorization](../../system-architecture-authentication.md) workload and method-allowlist rules: only the authenticated Game Design workload identity may call the publication method, and other internal workloads plus user/admin JWTs are denied. The invocation binds exact `{tenantId, scope}` (`versionId` for full publish or the complete `{baseVersionId, scriptPatchVersion}` pair for script patch), stable `publishRequestId`, derived workflow identity, and canonical `requestDigest`; missing, changed, or omitted binding evidence fails closed before a digest is returned. This context is owner-authentication and replay evidence, not an end-user role and not part of the content digest. Temporal activities never propagate the human operator JWT; operator authority ends when Game Design starts or attaches to the workflow. Each response's tenant and complete scope tuple must be exact-compared by Game Design before recording or gating the attestation; Game Design remains publication coordinator and each participant remains owner of its digest. +`GetDraftDesignDigest` is a read-only owner-to-owner publication read across World Management, Entity Management, Game Logic, and Automation & Scripting. Every receiver uses the shared [Security Architecture](../../system-architecture-security.md) and [Authentication & Authorization](../../system-architecture-authentication.md) workload and method-allowlist rules: only the authenticated Game Design workload identity may call the publication method, and other internal workloads plus user/admin JWTs are denied. The one narrow exception is the dedicated `game-design-baseline-migrator` certificate identity, which may call only Entity Management's digest-read method during the protected historical-baseline migration; it has no access to the other three publication reads or a public mutation route. The invocation binds exact `{tenantId, scope}` (`versionId` for full publish or the complete `{baseVersionId, scriptPatchVersion}` pair for script patch), stable `publishRequestId`, derived workflow identity, and canonical `requestDigest`; missing, changed, or omitted binding evidence fails closed before a digest is returned. This context is owner-authentication and replay evidence, not an end-user role and not part of the content digest. Temporal activities never propagate the human operator JWT; operator authority ends when Game Design starts or attaches to the workflow. Each response's tenant and complete scope tuple must be exact-compared by Game Design before recording or gating the attestation; Game Design remains publication coordinator and each participant remains owner of its digest. The publication read uses its own `publicationDigestRequest/v1` SHA-256 contract, not ADR 0047's operator-mutation digest. Let `segment(bytes)` be ADR 0047's unsigned canonical ASCII byte count, `:`, then those exact bytes; let `field(name, value) = segment(utf8(name)) + segment(utf8(value))`. The preimage is `segment(utf8("publicationDigestRequest/v1"))` followed, in this fixed order, by fields `tenantId`, `scopeKind`, `versionId`, `baseVersionId`, `scriptPatchVersion`, `publishRequestId`, and `derivedWorkflowIdentity`. `scopeKind` is exactly `FULL_VERSION` or `SCRIPT_PATCH`. A full request has a canonical positive-decimal `versionId` and empty `baseVersionId`/`scriptPatchVersion`; a patch has an empty `versionId`, canonical positive-decimal `baseVersionId`, and nonempty `scriptPatchVersion`. Empty inactive fields are framed, not omitted. Text fields are nonempty Unicode NFC without malformed scalar values or surrounding whitespace, except for the explicitly empty inactive scope fields; tenant and publish-request IDs also reject `:` so the existing workflow-ID derivation cannot alias two tuples. The digest is the lowercase 64-hex-character SHA-256 of the preimage. The derived workflow identity is `publish::publish-request:` for full publish and `publish-script-patch::publish-request:` for script patch; receivers recompute and compare it before comparing the digest. Neither notes nor a digest of content is an input: notes belong to Game Design's separate control-plane content digest. The script-patch command must carry and retain a stable caller-supplied `publishRequestId`, rather than generating one during publication. Shared golden vectors cover both scope branches, non-ASCII and delimiter-bearing patch values, and changed/omitted-field rejection; producers and all four receivers use the same grammar rather than local string joins. @@ -216,6 +216,8 @@ Rules: ### Digest Schema Migration +**Current implementation status:** Entity's digest producer and Game Design's publish gate use schema v2, while retained schema-v1 Entity full-version baselines are not automatically rewritten by an ordinary publish. A protected, one-shot Game Design maintenance operation enumerates those old baselines, obtains exact-scope v2 evidence from Entity, and conditionally replaces one complete expected-old tuple together with an immutable before/after audit in a single database transaction. It reports success only after exact baseline and audit readback. This reader/reconciler understands both stored baseline schemas; it never compares v1 content with v2 content for publication, and the v2-only gate remains fail closed. Deployment requires the controlled publication window and exact operator preflight in [Game Design operations](./operations.md). No live retained-row migration or no-data proof is implied by code or test fixtures. Entity's current `version:` applied-commit token remains synthetic and does not establish an applied-revision ledger. + Digest semantics are part of the publish safety contract. Changing which rows/fields participate in a domain digest, or how they are canonicalized, requires an explicit migration plan: 1. **Introduce the new digest semantics** diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 129f903030..797da0ac56 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -22,6 +22,8 @@ AR-1.5 full-version publication now reserves its Draft version and PENDING attem The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open arbitrary `CompareAndSetVersionState` transition gap recorded below. +`AR-3.2` Entity digest-schema catch-up now has a dedicated historical-baseline migration path in the Game Design owner: bounded v1 full-version enumeration, exact tenant/version and expected-old preflight, v2 Entity recomputation, atomic guarded baseline/audit write, and exact persisted readback/retry. It is a protected one-shot Job, not ordinary publication or a public operator API. This code and its synthetic test rows do not prove that deployed retained v1 rows were migrated or that the live scoped row set is empty. The controlled readers-first publication window, dedicated migrator certificate issuance, live PostgreSQL readback, and later review remain rollout gates; Entity's `version:` commit token still does not prove applied-revision convergence. Keep the capability partial until those boundaries have actual evidence. + Asset lifecycle status remains partial: publication and artifact services provide the current bounded release-bundle and asset-storage seams, but the destructive lifecycle operations (`TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets`) still lack proved durable operation handling and owner-local epoch/CAS protection. `BeginPurgeVersionAssets` currently mints a random workflow identity, and artifact and Version saves lack DB epoch predicates/affected-row proof. The canonical lifecycle and operation contract is owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status), with [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) providing provenance. The live `CompareAndSetVersionState` path has an additional transition-safety gap: it accepts any non-null lifecycle enum after its in-memory epoch check, without requiring a committed release bundle/artifact for `DRAFT -> PUBLISHED` or enforcing active-instance/template/in-flight-activation predicates before retirement. It must not be rated as activation- or retirement-safe until the legal transition matrix, guards, and focused proof are implemented. Purge failure status is likewise not durable today: `FinalizePurgeVersionAssets` saves `PURGE_FAILED`/failed-workflow markers and rethrows inside `@Transactional`, so rollback can discard those markers after object deletion, leaving durable `PURGE_IN_PROGRESS` without reliable resume evidence. Target recovery needs an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused deletion/post-delete-save proof. diff --git a/dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh b/dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh new file mode 100644 index 0000000000..f31ea8c543 --- /dev/null +++ b/dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh @@ -0,0 +1,375 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +CHART_DIR="$ROOT_DIR/k8s/helm/firemud" +TMP_DIR="$(mktemp -d)" +trap 'rm -rf "$TMP_DIR"' EXIT + +if ! command -v helm >/dev/null 2>&1; then + echo "helm is required to render the Entity baseline migration contract" >&2 + exit 1 +fi + +VALUES="$TMP_DIR/preview-values.yaml" +python3 "$ROOT_DIR/dev-tools/hosted/preview/render-preview-values.py" \ + "$CHART_DIR/values-hosted-shared.example.yaml" \ + "$VALUES" \ + 123 \ + pr-123 \ + pr-123 \ + pr-123.preview.firedevops.net \ + pr-123-deadbeef \ + 32000 + +python3 - "$ROOT_DIR" "$CHART_DIR" "$VALUES" "$TMP_DIR" <<'PY' +import copy +import pathlib +import subprocess +import sys + +import yaml + +root = pathlib.Path(sys.argv[1]) +chart = pathlib.Path(sys.argv[2]) +values = pathlib.Path(sys.argv[3]) +tmp = pathlib.Path(sys.argv[4]) +base = yaml.safe_load(values.read_text(encoding="utf-8")) +image = "ghcr.io/benhook1013/game-design-service@sha256:" + "a" * 64 + + +def render(name, override=None): + namespace = base.get("preview", {}).get("namespace", "pr-123") + args = [ + "helm", + "template", + name, + str(chart), + "--namespace", + namespace, + "-f", + str(values), + ] + if override is not None: + override_path = tmp / f"{name}-override.yaml" + override_path.write_text(yaml.safe_dump(override), encoding="utf-8") + args.extend(["-f", str(override_path)]) + return subprocess.run(args, text=True, capture_output=True, check=False) + + +def documents(output): + return [ + item + for item in yaml.safe_load_all(output) + if isinstance(item, dict) + ] + + +def require_failure(case, override, expected_fragment): + result = render(f"invalid-{case}", override) + if result.returncode == 0: + raise SystemExit(f"Helm accepted invalid migration configuration: {case}") + if expected_fragment not in result.stderr: + raise SystemExit( + f"Helm failure for {case} did not explain the invalid value: {result.stderr}" + ) + + +disabled = render("migration-disabled") +if disabled.returncode != 0: + raise SystemExit(f"disabled chart render failed: {disabled.stderr}") +disabled_docs = documents(disabled.stdout) +if any( + item.get("metadata", {}).get("name", "").startswith("game-design-baseline-migrator") + for item in disabled_docs +): + raise SystemExit("disabled configuration rendered migration identity or Job resources") +if any( + item.get("metadata", {}).get("name") == "game-design-baseline-migrator" + for item in disabled_docs + if item.get("kind") == "NetworkPolicy" +): + raise SystemExit("disabled configuration rendered the migration NetworkPolicy") + +migration = { + "enabled": True, + "mode": "migrate", + "targetNamespace": "pr-123", + "operationId": "entity-v1-to-v2-pr123-v42", + "tenantId": "tenant-alpha", + "versionId": "42", + "actorIdentity": "operator:baseline-migration", + "image": image, + "expectedSource": { + "kind": "ConfigMap", + "name": "entity-v1-baseline-source-2872", + "key": "expected-source.json", + }, +} +enabled = render( + "migration-enabled", + {"previewStack": {"entityDigestBaselineMigration": migration}}, +) +if enabled.returncode != 0: + raise SystemExit(f"enabled chart render failed: {enabled.stderr}") +enabled_docs = documents(enabled.stdout) +by_kind_name = { + (item.get("kind"), item.get("metadata", {}).get("name")): item + for item in enabled_docs +} +job_name = "game-design-baseline-migrator-entity-v1-to-v2-pr123-v42" +job = by_kind_name.get(("Job", job_name)) +if job is None: + raise SystemExit("enabled configuration did not render the operation-scoped Job") +if by_kind_name.get(("ServiceAccount", "game-design-baseline-migrator"), {}).get( + "automountServiceAccountToken" +) is not False: + raise SystemExit("migrator service account must not mount a Kubernetes API token") +role = by_kind_name.get(("Role", "game-design-baseline-migrator")) +if role is None or role.get("rules") != []: + raise SystemExit("migrator Role must contain no Kubernetes API permissions") +role_binding = by_kind_name.get(("RoleBinding", "game-design-baseline-migrator")) +if role_binding is None: + raise SystemExit("enabled configuration did not render the dedicated RoleBinding") + +job_template = job.get("spec", {}).get("template", {}) +pod_spec = job_template.get("spec", {}) +if pod_spec.get("serviceAccountName") != "game-design-baseline-migrator": + raise SystemExit("Job does not use the dedicated migrator service account") +if pod_spec.get("automountServiceAccountToken") is not False: + raise SystemExit("Job pod must not mount a Kubernetes API token") +container = pod_spec.get("containers", [])[0] +if container.get("image") != image: + raise SystemExit("Job image does not match the required immutable image digest") +if container.get("imagePullPolicy") != "IfNotPresent": + raise SystemExit("digest-pinned Job image must use IfNotPresent") +if "helm.sh/hook" in job.get("metadata", {}).get("annotations", {}): + raise SystemExit("migration Job must not be a Helm hook") +if job.get("spec", {}).get("backoffLimit") != 0: + raise SystemExit("migration Job must stop after its first failed attempt") +labels = job_template.get("metadata", {}).get("labels", {}) +if labels.get("app") != "game-design-baseline-migrator": + raise SystemExit("migration Job must use a Service-distinct pod label") +game_design_service = next( + ( + item + for item in enabled_docs + if item.get("kind") == "Service" + and item.get("metadata", {}).get("name") == "game-design-service" + ), + None, +) +if game_design_service is None: + raise SystemExit("expected game-design-service ClusterIP Service was not rendered") +if game_design_service.get("spec", {}).get("selector", {}).get("app") == labels["app"]: + raise SystemExit("game-design-service Service would select the migration Job pod") + +env = {entry["name"]: entry for entry in container.get("env", [])} +if any( + name in env + for name in ( + "FIREMUD_AUTH_JWT_SECRET", + "FIREMUD_AUTH_JWT_SECRET_PATH", + ) +): + raise SystemExit("migration Job must not receive the ordinary shared JWT signing secret") +if container.get("envFrom"): + raise SystemExit("migration Job must not import a broad ordinary service environment") +for name, expected in ( + ("FIREMUD_ENTITY_BASELINE_MIGRATION_ENABLED", "true"), + ("FIREMUD_ENTITY_BASELINE_MIGRATION_MODE", "migrate"), + ("FIREMUD_ENTITY_BASELINE_MIGRATION_OPERATION_ID", migration["operationId"]), + ("FIREMUD_ENTITY_BASELINE_MIGRATION_TENANT_ID", migration["tenantId"]), + ("FIREMUD_ENTITY_BASELINE_MIGRATION_VERSION_ID", migration["versionId"]), + ("FIREMUD_ENTITY_BASELINE_MIGRATION_ACTOR_IDENTITY", migration["actorIdentity"]), + ( + "FIREMUD_ENTITY_BASELINE_MIGRATION_EXPECTED_SOURCE_PATH", + "/migration/expected-source.json", + ), + ("FIREMUD_ENTITY_BASELINE_MIGRATION_TARGET_NAMESPACE", "pr-123"), +): + if env.get(name, {}).get("value") != expected: + raise SystemExit(f"Job did not bind {name} to its exact operator input") +for name in ( + "FIREMUD_ENTITY_BASELINE_MIGRATION_POD_NAMESPACE", + "FIREMUD_ENTITY_BASELINE_MIGRATION_POD_SERVICE_ACCOUNT", +): + if "fieldRef" not in env.get(name, {}).get("valueFrom", {}): + raise SystemExit(f"Job must derive {name} from downward API identity") +for name in ( + "FIREMUD_POSTGRES_USER", + "FIREMUD_POSTGRES_PASSWORD", +): + secret_ref = env.get(name, {}).get("valueFrom", {}).get("secretKeyRef", {}) + if secret_ref.get("name") != "firemud-secret": + raise SystemExit(f"Job database credential {name} is not secret-projected") +for name in ( + "FIREMUD_POSTGRES_HOST", + "FIREMUD_POSTGRES_PORT", + "FIREMUD_POSTGRES_DB", +): + config_ref = env.get(name, {}).get("valueFrom", {}).get("configMapKeyRef", {}) + if config_ref.get("name") != "firemud-config": + raise SystemExit(f"Job database setting {name} is not config-projected") + +volumes = {volume["name"]: volume for volume in pod_spec.get("volumes", [])} +if any( + volume.get("secret", {}).get("secretName") == "firemud-secret" + and volume_name not in {"grpc-identity", "grpc-trust"} + for volume_name, volume in volumes.items() +): + raise SystemExit("migration Job must not project the ordinary application Secret as a volume") +if volumes.get("grpc-identity", {}).get("secret", {}).get("secretName") != ( + "firemud-grpc-game-design-baseline-migrator" +): + raise SystemExit("Job must mount its dedicated, separately provisioned gRPC identity") +if volumes.get("grpc-trust", {}).get("secret", {}).get("secretName") != "firemud-grpc-tls": + raise SystemExit("Job must mount the fixed gRPC trust bundle") +source = volumes.get("expected-source", {}).get("configMap", {}) +if source.get("name") != migration["expectedSource"]["name"]: + raise SystemExit("Job does not mount the operator-supplied expected-source snapshot") +if source.get("items", [{}])[0].get("path") != "expected-source.json": + raise SystemExit("expected-source JSON is not projected to the runner's fixed path") + +policy = by_kind_name.get(("NetworkPolicy", "game-design-baseline-migrator")) +if policy is None: + raise SystemExit("enabled configuration did not render the isolated migration policy") +policy_spec = policy.get("spec", {}) +if policy_spec.get("podSelector", {}).get("matchLabels") != { + "app": "game-design-baseline-migrator", + "firemud.dev/workload": "game-design-baseline-migrator", +}: + raise SystemExit("migration NetworkPolicy does not select only the dedicated Job pods") +if policy_spec.get("ingress") != []: + raise SystemExit("migration Job must not accept inbound connections") +allowed = { + ( + rule.get("to", [{}])[0].get("podSelector", {}).get("matchLabels", {}).get("app"), + rule.get("ports", [{}])[0].get("port"), + ) + for rule in policy_spec.get("egress", []) + if rule.get("to") +} +if ("postgres", 5432) not in allowed or ("entity-management-service", 6565) not in allowed: + raise SystemExit("migration Job egress must include only the required DB and Entity ports") +for app, port in allowed: + if (app, port) not in {("postgres", 5432), ("entity-management-service", 6565), (None, 53)}: + raise SystemExit(f"migration Job has unrelated egress permission: {(app, port)}") + +for case, mutation, fragment in ( + ( + "missing-image", + lambda item: item.update(image=""), + "image must be an immutable image reference", + ), + ( + "tagged-image", + lambda item: item.update(image="ghcr.io/benhook1013/game-design-service:latest"), + "must end in @sha256:", + ), + ( + "missing-source", + lambda item: item.update(expectedSource={"kind": "", "name": "", "key": ""}), + "expectedSource.kind to be ConfigMap or Secret", + ), + ( + "invalid-operation-id", + lambda item: item.update(operationId="not a dns label"), + "requires a DNS-label operationId", + ), + ( + "wrong-target-namespace", + lambda item: item.update(targetNamespace="other-namespace"), + "must exactly match the Helm release namespace", + ), +): + bad = copy.deepcopy(migration) + mutation(bad) + require_failure( + case, + {"previewStack": {"entityDigestBaselineMigration": bad}}, + fragment, + ) + +preflight = { + **{key: value for key, value in migration.items() if key != "expectedSource"}, + "mode": "preflight", + "operationId": "", +} +preflight_result = render( + "migration-preflight", + {"previewStack": {"entityDigestBaselineMigration": preflight}}, +) +if preflight_result.returncode != 0: + raise SystemExit(f"scoped preflight render failed: {preflight_result.stderr}") +preflight_docs = documents(preflight_result.stdout) +preflight_job = next( + item for item in preflight_docs if item.get("kind") == "Job" and item.get("metadata", {}).get("name", "").startswith("game-design-baseline-migrator-preflight-") +) +if any(volume.get("name") == "expected-source" for volume in preflight_job["spec"]["template"]["spec"].get("volumes", [])): + raise SystemExit("read-only preflight unexpectedly requires or mounts an expected-source tuple") + +enumerate_values = { + **{key: value for key, value in migration.items() if key not in {"tenantId", "versionId", "expectedSource"}}, + "mode": "enumerate", + "operationId": "", + "afterBaselineId": "0", + "limit": 500, +} +enumerate_result = render( + "migration-enumerate", + {"previewStack": {"entityDigestBaselineMigration": enumerate_values}}, +) +if enumerate_result.returncode != 0: + raise SystemExit(f"bounded enumerate render failed: {enumerate_result.stderr}") +enumerate_docs = documents(enumerate_result.stdout) +enumerate_job = next( + item for item in enumerate_docs if item.get("kind") == "Job" and "-enumerate-" in item.get("metadata", {}).get("name", "") +) +enumerate_env = { + entry["name"]: entry + for entry in enumerate_job["spec"]["template"]["spec"]["containers"][0].get("env", []) +} +if enumerate_env.get("FIREMUD_ENTITY_BASELINE_MIGRATION_LIMIT", {}).get("value") != "500": + raise SystemExit("enumeration Job did not carry the bounded page limit") +if enumerate_env.get("FIREMUD_ENTITY_BASELINE_MIGRATION_AFTER_BASELINE_ID", {}).get("value") != "0": + raise SystemExit("enumeration Job did not start from the canonical baseline ID cursor") + +require_failure( + "enumerate-scope", + { + "previewStack": { + "entityDigestBaselineMigration": { + **enumerate_values, + "tenantId": "tenant-alpha", + } + } + }, + "enumerate mode must not set tenantId or versionId", +) +require_failure( + "excessive-limit", + { + "previewStack": { + "entityDigestBaselineMigration": { + **enumerate_values, + "limit": 501, + } + } + }, + "limit must be between 1 and 500", +) +unguarded_values = copy.deepcopy(migration) +unguarded_result = render( + "migration-network-policy-required", + { + "previewStack": { + "networkPolicies": {"enabled": False}, + "entityDigestBaselineMigration": unguarded_values, + } + }, +) +if unguarded_result.returncode == 0 or "networkPolicies.enabled=true" not in unguarded_result.stderr: + raise SystemExit("migration Job rendered without its egress NetworkPolicy") +print("Entity digest baseline migration Helm contract passed") +PY diff --git a/k8s/helm/firemud/templates/entity-digest-baseline-migration-job.yaml b/k8s/helm/firemud/templates/entity-digest-baseline-migration-job.yaml new file mode 100644 index 0000000000..971fe8d792 --- /dev/null +++ b/k8s/helm/firemud/templates/entity-digest-baseline-migration-job.yaml @@ -0,0 +1,304 @@ +{{- $migration := .Values.previewStack.entityDigestBaselineMigration | default (dict) -}} +{{- $enabled := $migration.enabled | default false -}} +{{- if $enabled -}} +{{- if not .Values.previewStack.enabled -}} +{{- fail "previewStack.entityDigestBaselineMigration.enabled requires previewStack.enabled=true" -}} +{{- end -}} +{{- $networkPolicies := .Values.previewStack.networkPolicies | default (dict) -}} +{{- if not ($networkPolicies.enabled | default false) -}} +{{- fail "previewStack.entityDigestBaselineMigration.enabled requires previewStack.networkPolicies.enabled=true" -}} +{{- end -}} +{{- $targetNamespace := required "previewStack.entityDigestBaselineMigration.targetNamespace is required when enabled" $migration.targetNamespace -}} +{{- if ne $targetNamespace $.Release.Namespace -}} +{{- fail "previewStack.entityDigestBaselineMigration.targetNamespace must exactly match the Helm release namespace" -}} +{{- end -}} +{{- $mode := required "previewStack.entityDigestBaselineMigration.mode is required when enabled" $migration.mode -}} +{{- if not (has $mode (list "enumerate" "preflight" "migrate")) -}} +{{- fail "previewStack.entityDigestBaselineMigration.mode must be enumerate, preflight, or migrate" -}} +{{- end -}} +{{- $image := required "previewStack.entityDigestBaselineMigration.image must be an immutable image reference" $migration.image -}} +{{- if not (regexMatch "^.+@sha256:[a-f0-9]{64}$" $image) -}} +{{- fail "previewStack.entityDigestBaselineMigration.image must end in @sha256:<64 lowercase hex characters>" -}} +{{- end -}} +{{- $tenantId := $migration.tenantId | default "" -}} +{{- $versionId := $migration.versionId | default "" -}} +{{- $actorIdentity := required "previewStack.entityDigestBaselineMigration.actorIdentity is required when enabled" $migration.actorIdentity -}} +{{- if or (eq (trim $actorIdentity) "") (ne $actorIdentity (trim $actorIdentity)) -}} +{{- fail "previewStack.entityDigestBaselineMigration.actorIdentity must be non-empty and have no surrounding whitespace" -}} +{{- end -}} +{{- if gt (len $actorIdentity) 128 -}} +{{- fail "previewStack.entityDigestBaselineMigration.actorIdentity must be at most 128 characters" -}} +{{- end -}} +{{- if eq $mode "enumerate" -}} +{{- if or (ne $tenantId "") (ne $versionId "") -}} +{{- fail "enumerate mode must not set tenantId or versionId" -}} +{{- end -}} +{{- else -}} +{{- if or (eq (trim $tenantId) "") (ne $tenantId (trim $tenantId)) -}} +{{- fail "preflight and migrate modes require a non-empty tenantId without surrounding whitespace" -}} +{{- end -}} +{{- if not (regexMatch "^[1-9][0-9]*$" (toString $versionId)) -}} +{{- fail "preflight and migrate modes require a canonical positive-decimal versionId" -}} +{{- end -}} +{{- end -}} +{{- $operationId := $migration.operationId | default "" -}} +{{- if and (eq $mode "migrate") (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $operationId)) -}} +{{- fail "migrate mode requires a DNS-label operationId" -}} +{{- end -}} +{{- if gt (len $operationId) 32 -}} +{{- fail "previewStack.entityDigestBaselineMigration.operationId must be at most 32 characters" -}} +{{- end -}} +{{- $afterBaselineId := $migration.afterBaselineId | default "0" | toString -}} +{{- if not (regexMatch "^(0|[1-9][0-9]*)$" $afterBaselineId) -}} +{{- fail "afterBaselineId must be a canonical non-negative decimal" -}} +{{- end -}} +{{- $limit := $migration.limit | default 100 -}} +{{- if or (lt (int $limit) 1) (gt (int $limit) 500) -}} +{{- fail "previewStack.entityDigestBaselineMigration.limit must be between 1 and 500" -}} +{{- end -}} +{{- $expectedSource := $migration.expectedSource | default (dict) -}} +{{- if eq $mode "migrate" -}} +{{- if not (has $expectedSource.kind (list "ConfigMap" "Secret")) -}} +{{- fail "migrate mode requires expectedSource.kind to be ConfigMap or Secret" -}} +{{- end -}} +{{- $expectedSourceName := required "migrate mode requires expectedSource.name for an immutable operator-applied source tuple" $expectedSource.name -}} +{{- if not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$" $expectedSourceName) -}} +{{- fail "expectedSource.name must be a DNS subdomain" -}} +{{- end -}} +{{- $expectedSourceKey := required "migrate mode requires expectedSource.key" $expectedSource.key -}} +{{- if eq (trim $expectedSourceKey) "" -}} +{{- fail "expectedSource.key must be non-empty" -}} +{{- end -}} +{{- end -}} +{{- $grpcIdentitySecretName := required "previewStack.entityDigestBaselineMigration.grpcIdentitySecretName must name the dedicated migrator identity Secret" $migration.grpcIdentitySecretName -}} +{{- if ne $grpcIdentitySecretName "firemud-grpc-game-design-baseline-migrator" -}} +{{- fail "grpcIdentitySecretName must be firemud-grpc-game-design-baseline-migrator; shared service identities are not accepted" -}} +{{- end -}} +{{- $readScopeName := printf "%s:%s:%s:%s:%s:%s" $mode $tenantId (toString $versionId) $afterBaselineId (toString $limit) $targetNamespace | sha256sum | trunc 12 -}} +{{- $jobSuffix := $operationId -}} +{{- if ne $mode "migrate" -}} +{{- $jobSuffix = printf "%s-%s" $mode $readScopeName -}} +{{- end -}} +{{- $jobName := printf "game-design-baseline-migrator-%s" $jobSuffix -}} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: game-design-baseline-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: game-design-baseline-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +rules: [] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: game-design-baseline-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +subjects: + - kind: ServiceAccount + name: game-design-baseline-migrator + namespace: {{ .Release.Namespace | quote }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: game-design-baseline-migrator +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ $jobName | quote }} + labels: +{{ include "firemud.commonLabels" . | indent 4 }} + annotations: + firemud.dev/migration-mode: {{ $mode | quote }} + firemud.dev/migration-operation-id: {{ $operationId | quote }} +spec: + completions: 1 + parallelism: 1 + backoffLimit: 0 + activeDeadlineSeconds: 900 + template: + metadata: + labels: + app: game-design-baseline-migrator + firemud.dev/workload: game-design-baseline-migrator + spec: + serviceAccountName: game-design-baseline-migrator + automountServiceAccountToken: false + restartPolicy: Never + securityContext: + runAsNonRoot: true + runAsUser: 1000 + runAsGroup: 1000 + fsGroup: 1000 + seccompProfile: + type: RuntimeDefault + {{- with .Values.previewStack.imagePullSecrets }} + imagePullSecrets: + {{- range $secret := . }} + {{- if kindIs "string" $secret }} + - name: {{ $secret }} + {{- else }} +{{ toYaml (list $secret) | indent 8 }} + {{- end }} + {{- end }} + {{- end }} + containers: + - name: migration + image: {{ $image | quote }} + imagePullPolicy: IfNotPresent + command: + - java + args: + - -jar + - /app/app.jar + - --spring.main.web-application-type=none + - --spring.grpc.server.enabled=false + - --firemud.entity-baseline-migration.enabled=true + env: + - name: SPRING_FLYWAY_TABLE + value: flyway_schema_history_game_design_service + - name: SERVICE_SCHEMA + value: game_design_service + - name: FIREMUD_POSTGRES_HOST + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_HOST + - name: FIREMUD_POSTGRES_PORT + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_PORT + - name: FIREMUD_POSTGRES_DB + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_DB + - name: FIREMUD_POSTGRES_USER + valueFrom: + secretKeyRef: + name: firemud-secret + key: FIREMUD_POSTGRES_USER + - name: FIREMUD_POSTGRES_PASSWORD + valueFrom: + secretKeyRef: + name: firemud-secret + key: FIREMUD_POSTGRES_PASSWORD + - name: FIREMUD_REDIS_ENABLED + value: "false" + - name: FIREMUD_TEMPORAL_ENABLED + value: "false" + - name: FIREMUD_TEMPORAL_WORKERS_ENABLED + value: "false" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: FIREMUD_GRPC_CERT_CHAIN_PATH + value: /tls/tls.crt + - name: FIREMUD_GRPC_PRIVATE_KEY_PATH + value: /tls/tls.key + - name: FIREMUD_GRPC_CA_CERT_PATH + value: /grpc-trust/ca.crt + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_ENABLED + value: "true" + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_MODE + value: {{ $mode | quote }} + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_OPERATION_ID + value: {{ $operationId | quote }} + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_TENANT_ID + value: {{ $tenantId | quote }} + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_VERSION_ID + value: {{ toString $versionId | quote }} + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_ACTOR_IDENTITY + value: {{ $actorIdentity | quote }} + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_EXPECTED_SOURCE_PATH + value: /migration/expected-source.json + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_TARGET_NAMESPACE + value: {{ $targetNamespace | quote }} + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_POD_SERVICE_ACCOUNT + valueFrom: + fieldRef: + fieldPath: spec.serviceAccountName + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_AFTER_BASELINE_ID + value: {{ $afterBaselineId | quote }} + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_LIMIT + value: {{ int $limit | quote }} + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsUser: 1000 + runAsGroup: 1000 + capabilities: + drop: + - ALL + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + cpu: 1 + memory: 768Mi + volumeMounts: + - name: grpc-identity + mountPath: /tls + readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true + - name: migration-tmp + mountPath: /tmp + {{- if eq $mode "migrate" }} + - name: expected-source + mountPath: /migration + readOnly: true + {{- end }} + volumes: + - name: grpc-identity + secret: + secretName: {{ $grpcIdentitySecretName | quote }} + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + - name: grpc-trust + secret: + secretName: firemud-grpc-tls + items: + - key: ca.crt + path: ca.crt + - name: migration-tmp + emptyDir: + sizeLimit: 64Mi + {{- if eq $mode "migrate" }} + - name: expected-source + {{- if eq $expectedSource.kind "Secret" }} + secret: + secretName: {{ $expectedSource.name | quote }} + items: + - key: {{ $expectedSource.key | quote }} + path: expected-source.json + {{- else }} + configMap: + name: {{ $expectedSource.name | quote }} + items: + - key: {{ $expectedSource.key | quote }} + path: expected-source.json + {{- end }} + {{- end }} +{{- end -}} diff --git a/k8s/helm/firemud/templates/network-policies.yaml b/k8s/helm/firemud/templates/network-policies.yaml index f40e18b14e..1ad9aec462 100644 --- a/k8s/helm/firemud/templates/network-policies.yaml +++ b/k8s/helm/firemud/templates/network-policies.yaml @@ -26,6 +26,7 @@ {{- if $gatewayWsTls.enabled }} {{- $gatewayWsTlsTargetPort = required "previewStack.gatewayWsTls.targetPort is required when Gateway WebSocket TLS is enabled" $gatewayWsTls.targetPort }} {{- end }} +{{- $entityDigestBaselineMigration := .Values.previewStack.entityDigestBaselineMigration | default (dict) }} --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy @@ -384,4 +385,49 @@ spec: - protocol: TCP port: 9200 {{- end }} +{{- if $entityDigestBaselineMigration.enabled }} +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: game-design-baseline-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + podSelector: + matchLabels: + app: game-design-baseline-migrator + firemud.dev/workload: game-design-baseline-migrator + policyTypes: + - Ingress + - Egress + ingress: [] + egress: + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + podSelector: + matchLabels: + k8s-app: kube-dns + ports: + - protocol: UDP + port: 53 + - protocol: TCP + port: 53 + - to: + - podSelector: + matchLabels: + app: postgres + ports: + - protocol: TCP + port: 5432 + - to: + - podSelector: + matchLabels: + app: entity-management-service + ports: + - protocol: TCP + port: 6565 +{{- end }} {{- end }} diff --git a/k8s/helm/firemud/values.yaml b/k8s/helm/firemud/values.yaml index f1e838a333..468a69541b 100644 --- a/k8s/helm/firemud/values.yaml +++ b/k8s/helm/firemud/values.yaml @@ -1,5 +1,25 @@ previewStack: enabled: false + entityDigestBaselineMigration: + # This is an operator-invoked protected maintenance Job. Keep it disabled + # in ordinary chart releases; no Helm hook is used to trigger execution. + enabled: false + mode: "" + targetNamespace: "" + operationId: "" + tenantId: "" + versionId: "" + afterBaselineId: "0" + limit: 100 + actorIdentity: "" + image: "" + expectedSource: + kind: "" + name: "" + key: expected-source.json + # A dedicated identity Secret must be provisioned by the environment's + # trust owner. The chart never falls back to a service certificate. + grpcIdentitySecretName: firemud-grpc-game-design-baseline-migrator # Hosted environments use the HostedEnvironmentIdentity controller for # certificate identity. Local installs retain standalone cert-manager mode. certificateIdentity: diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java index f5515c67b5..3d15d9f402 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java @@ -30,6 +30,7 @@ public record GrpcPeerIdentity(String uri, String namespace, String service) { "account-service", "automation-scripting-service", "entity-management-service", + "game-design-baseline-migrator", "game-design-service", "game-logic-service", "game-session-service", diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java index 512f4fb6ec..cc30881086 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java @@ -30,6 +30,15 @@ void extractsOneAllowedUriSanFromAuthenticatedLeaf() throws Exception { .containsExactly(GAME_DESIGN_URI, "firemud", "game-design-service"); } + @Test + void extractsDedicatedEntityBaselineMigratorIdentity() throws Exception { + String uri = "spiffe://firemud/ns/firemud/sa/game-design-baseline-migrator"; + assertThat(GrpcPeerIdentity.fromSslSession(sessionWithUriSans(uri))) + .get() + .extracting(GrpcPeerIdentity::uri, GrpcPeerIdentity::namespace, GrpcPeerIdentity::service) + .containsExactly(uri, "firemud", "game-design-baseline-migrator"); + } + @Test void normalizesCanonicalEquivalentUriSanBeforeValidatingWorkloadIdentity() { assertThat(GrpcPeerIdentity.parseUri("spiffe://FIREMUD/ns/%66iremud/sa/game-%64esign-service")) diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/PublicationReadGuard.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/PublicationReadGuard.java index 6f8ac466fb..3d17998c71 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/PublicationReadGuard.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/PublicationReadGuard.java @@ -32,6 +32,7 @@ public final class PublicationReadGuard { AUTOMATION_SCRIPTING_DIGEST_METHOD); private static final String GAME_DESIGN_SERVICE = "game-design-service"; + private static final String ENTITY_BASELINE_MIGRATOR = "game-design-baseline-migrator"; private final String trustedNamespace; public PublicationReadGuard(String trustedNamespace) { @@ -59,6 +60,14 @@ public boolean protects(String fullMethodName) { */ public void requirePublicationRead(String fullMethodName) { if (protects(fullMethodName)) { + GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); + if (ENTITY_MANAGEMENT_DIGEST_METHOD.equals(fullMethodName) + && peerIdentity != null + && peerIdentity.isService(ENTITY_BASELINE_MIGRATOR) + && peerIdentity.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return; + } requireGameDesignWorkload(); } } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/PublicationReadGuardTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/PublicationReadGuardTest.java index 62bb1f5f42..884b93fb08 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/PublicationReadGuardTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/PublicationReadGuardTest.java @@ -22,6 +22,11 @@ class PublicationReadGuardTest { "spiffe://firemud/ns/firemud/sa/game-design-service", TRUSTED_NAMESPACE, "game-design-service"); + private static final GrpcPeerIdentity ENTITY_BASELINE_MIGRATOR_PEER = + new GrpcPeerIdentity( + "spiffe://firemud/ns/firemud/sa/game-design-baseline-migrator", + TRUSTED_NAMESPACE, + "game-design-baseline-migrator"); private final PublicationReadGuard guard = new PublicationReadGuard(TRUSTED_NAMESPACE); @@ -61,6 +66,42 @@ void allowsAllFourExactPublicationReadsWithWorkloadOnlyContext() { }); } + @Test + void baselineMigratorCanReadOnlyTheEntityDigestWithoutUserContext() { + withPeer( + ENTITY_BASELINE_MIGRATOR_PEER, + () -> { + guard.requirePublicationRead(PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD); + for (String method : PublicationReadGuard.PUBLICATION_READ_METHODS) { + if (!method.equals(PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD)) { + assertThatThrownBy(() -> guard.requirePublicationRead(method)) + .isInstanceOf(AdminAuthorizationException.class); + } + } + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + assertThatThrownBy( + () -> + guard.requirePublicationRead( + PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD)) + .isInstanceOf(AdminAuthorizationException.class); + }); + } + + @Test + void baselineMigratorFromAnotherNamespaceCannotReadEntityDigest() { + withPeer( + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-design-baseline-migrator", + "other", + "game-design-baseline-migrator"), + () -> + assertThatThrownBy( + () -> + guard.requirePublicationRead( + PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD)) + .isInstanceOf(AdminAuthorizationException.class)); + } + @Test void deniesAuthenticatedUserContextEvenWithGameDesignPeer() { withPeer( diff --git a/services/entity-management-service/src/main/resources/application.yml b/services/entity-management-service/src/main/resources/application.yml index d3b5e99641..72384115b1 100644 --- a/services/entity-management-service/src/main/resources/application.yml +++ b/services/entity-management-service/src/main/resources/application.yml @@ -73,6 +73,8 @@ firemud: grpc: public-methods: - entity_management.v1.EntityManagementService/Ping + # JWT is not authority for this read: its handler requires an exact mTLS workload peer. + - entity_management.v1.EntityManagementService/GetDraftDesignDigest grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/EntityPublicationReadConfigurationTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/EntityPublicationReadConfigurationTest.java new file mode 100644 index 0000000000..c3cafe015c --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/EntityPublicationReadConfigurationTest.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.entitymanagement; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.security.PublicationReadGuard; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.config.YamlMapFactoryBean; +import org.springframework.core.io.FileSystemResource; + +class EntityPublicationReadConfigurationTest { + @Test + void onlyPingAndTheMtlsGuardedDigestBypassJwtAtTheTransport() { + YamlMapFactoryBean yaml = new YamlMapFactoryBean(); + yaml.setResources(new FileSystemResource("src/main/resources/application.yml")); + Map properties = yaml.getObject(); + + assertThat(properties).isNotNull(); + Map firemud = (Map) properties.get("firemud"); + Map auth = (Map) firemud.get("auth"); + Map grpc = (Map) auth.get("grpc"); + List methods = + ((List) grpc.get("public-methods")).stream().map(String::valueOf).toList(); + assertThat(methods) + .containsExactly( + "entity_management.v1.EntityManagementService/Ping", + PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java index d63df1e4df..2e5663f873 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java @@ -2,8 +2,10 @@ import net.firedevops.firemud.common.GlobalExceptionHandler; import org.springframework.boot.SpringApplication; +import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Import; @SpringBootApplication @@ -11,6 +13,27 @@ @Import(GlobalExceptionHandler.class) public class GameDesignServiceApplication { public static void main(String[] args) { - SpringApplication.run(GameDesignServiceApplication.class, args); + if ("true".equals(System.getenv("FIREMUD_ENTITY_BASELINE_MIGRATION_ENABLED"))) { + if (System.getenv("FIREMUD_AUTH_JWT_SECRET") != null + || System.getenv("FIREMUD_AUTH_JWT_SECRET_PATH") != null) { + throw new IllegalStateException( + "migration Job must not receive the shared JWT signing key"); + } + SpringApplication application = new SpringApplication(GameDesignServiceApplication.class); + application.setWebApplicationType(WebApplicationType.NONE); + application.setDefaultProperties( + java.util.Map.of( + "spring.main.web-application-type", "none", + "spring.grpc.server.enabled", "false", + "firemud.temporal.enabled", "false", + "firemud.auth.jwt-secret", + java.util.UUID.randomUUID().toString().replace("-", "") + + java.util.UUID.randomUUID().toString().replace("-", ""))); + try (ConfigurableApplicationContext ignored = application.run(args)) { + // The conditional migration runner has completed, including exact database readback. + } + } else { + SpringApplication.run(GameDesignServiceApplication.class, args); + } } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/EntityDigestBaselineMigrationAudit.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/EntityDigestBaselineMigrationAudit.java new file mode 100644 index 0000000000..847eadceda --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/EntityDigestBaselineMigrationAudit.java @@ -0,0 +1,37 @@ +package net.firedevops.firemud.gamedesign.entity; + +import java.time.LocalDateTime; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.PublishType; + +/** Immutable before-and-after evidence for one Entity digest baseline schema migration. */ +public record EntityDigestBaselineMigrationAudit( + Long id, + String operationId, + Long recordedParticipantDigestId, + String sourceTenantId, + PublishType sourcePublishType, + PublishParticipantKey sourceParticipantKey, + Long sourceBaseVersionId, + String sourceScopeValue, + String sourceAppliedCommitId, + String sourceContentDigest, + Integer sourceDigestSchemaVersion, + String sourceRecordedFromPublishWorkflowId, + LocalDateTime sourceRecordedAt, + String sourceLastVerifiedPublishWorkflowId, + LocalDateTime sourceLastVerifiedAt, + String observedTenantId, + PublishType observedPublishType, + PublishParticipantKey observedParticipantKey, + Long observedBaseVersionId, + String observedScopeValue, + String observedAppliedCommitId, + String observedContentDigest, + Integer observedDigestSchemaVersion, + String actorIdentity, + String workloadIdentity, + String outcome, + LocalDateTime committedAt) { + public static final String COMMITTED_OUTCOME = "COMMITTED"; +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java new file mode 100644 index 0000000000..b44ad926fd --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.ExpectedSource; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.MigrationCommand; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +/** Trusted, one-shot entry point; no HTTP, gRPC server, or user-JWT mutation route is exposed. */ +@Component +@ConditionalOnProperty( + prefix = "firemud.entity-baseline-migration", + name = "enabled", + havingValue = "true") +public class EntityDigestBaselineMigrationJobRunner implements ApplicationRunner { + private static final Logger LOG = + LoggerFactory.getLogger(EntityDigestBaselineMigrationJobRunner.class); + private static final String MIGRATOR_SERVICE = "game-design-baseline-migrator"; + private static final int MAX_BATCH_SIZE = 500; + + private final Environment environment; + private final ObjectMapper objectMapper; + private final EntityDigestBaselineMigrationService migrationService; + + public EntityDigestBaselineMigrationJobRunner( + Environment environment, + ObjectMapper objectMapper, + EntityDigestBaselineMigrationService migrationService) { + this.environment = environment; + this.objectMapper = objectMapper; + this.migrationService = migrationService; + } + + @Override + public void run(ApplicationArguments args) throws Exception { + if (!"true".equals(System.getenv("FIREMUD_ENTITY_BASELINE_MIGRATION_ENABLED")) + || !"none".equalsIgnoreCase(required("spring.main.web-application-type")) + || environment.getProperty("spring.grpc.server.enabled", Boolean.class, true) + || environment.getProperty("firemud.temporal.enabled", Boolean.class, true)) { + throw new IllegalStateException( + "migration Job must not start application listeners or workers"); + } + String namespace = required("firemud.entity-baseline-migration.pod-namespace"); + GrpcPeerIdentity identity = verifiedWorkloadIdentity(); + requireJobAuthority( + namespace, + required("firemud.entity-baseline-migration.target-namespace"), + required("firemud.entity-baseline-migration.pod-service-account"), + identity); + String workloadIdentity = identity.uri(); + + String mode = required("firemud.entity-baseline-migration.mode"); + switch (mode) { + case "enumerate" -> { + long afterId = optionalLong("firemud.entity-baseline-migration.after-baseline-id", 0); + int limit = (int) optionalLong("firemud.entity-baseline-migration.limit", MAX_BATCH_SIZE); + LOG.info( + "Entity v1 baseline enumeration targetNamespace={} result={}", + namespace, + objectMapper.writeValueAsString( + migrationService.enumerateEntityV1Batch(afterId, limit))); + } + case "preflight" -> { + String tenantId = required("firemud.entity-baseline-migration.tenant-id"); + long versionId = requiredPositiveLong("firemud.entity-baseline-migration.version-id"); + LOG.info( + "Entity baseline preflight targetNamespace={} result={}", + namespace, + objectMapper.writeValueAsString(migrationService.preflightScope(tenantId, versionId))); + } + case "migrate" -> { + String operationId = required("firemud.entity-baseline-migration.operation-id"); + String tenantId = required("firemud.entity-baseline-migration.tenant-id"); + long versionId = requiredPositiveLong("firemud.entity-baseline-migration.version-id"); + String actorIdentity = required("firemud.entity-baseline-migration.actor-identity"); + Path expectedSourcePath = + Path.of(required("firemud.entity-baseline-migration.expected-source-path")); + ExpectedSource expectedSource = + objectMapper.readValue(Files.readAllBytes(expectedSourcePath), ExpectedSource.class); + if (expectedSource.baselineId() == null) { + throw new IllegalArgumentException("expected source lacks its baseline id"); + } + MigrationCommand command = + new MigrationCommand( + operationId, + expectedSource.baselineId(), + tenantId, + versionId, + expectedSource, + actorIdentity, + workloadIdentity); + LOG.info( + "Entity baseline migration targetNamespace={} result={}", + namespace, + objectMapper.writeValueAsString(migrationService.migrate(command))); + } + default -> throw new IllegalArgumentException("unsupported migration Job mode"); + } + } + + static void requireJobAuthority( + String podNamespace, + String targetNamespace, + String podServiceAccount, + GrpcPeerIdentity identity) { + if (!podNamespace.equals(targetNamespace)) { + throw new IllegalStateException("migration Job is outside its exact target namespace"); + } + if (!MIGRATOR_SERVICE.equals(podServiceAccount)) { + throw new IllegalStateException("migration Job lacks the dedicated service account"); + } + if (identity == null + || !identity.isService(MIGRATOR_SERVICE) + || !identity.isInNamespace(podNamespace)) { + throw new IllegalStateException( + "migration client certificate has the wrong workload identity"); + } + } + + private GrpcPeerIdentity verifiedWorkloadIdentity() throws Exception { + Path certificatePath = Path.of(required("FIREMUD_GRPC_CERT_CHAIN_PATH")); + X509Certificate leaf; + try (InputStream input = Files.newInputStream(certificatePath)) { + leaf = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + return GrpcPeerIdentity.fromCertificate(leaf) + .orElseThrow( + () -> + new IllegalStateException("migration client certificate lacks one valid URI SAN")); + } + + private long optionalLong(String property, long fallback) { + String value = environment.getProperty(property); + return value == null || value.isBlank() ? fallback : Long.parseLong(value); + } + + private long requiredPositiveLong(String property) { + long value = Long.parseLong(required(property)); + if (value < 1) { + throw new IllegalArgumentException(property + " must be positive"); + } + return value; + } + + private String required(String property) { + String value = environment.getProperty(property); + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(property + " is required"); + } + return value; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/EntityDigestBaselineMigrationAuditRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/EntityDigestBaselineMigrationAuditRepository.java new file mode 100644 index 0000000000..b32c9c8b13 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/EntityDigestBaselineMigrationAuditRepository.java @@ -0,0 +1,203 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.LocalDateTime; +import java.util.Optional; +import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.PublishType; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; + +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class EntityDigestBaselineMigrationAuditRepository { + private static final Table TABLE_REF = + DSL.table(DSL.name("entity_digest_baseline_migration_audit")); + private static final Field ID = DSL.field(DSL.name("id"), Long.class); + private static final Field OPERATION_ID = + DSL.field(DSL.name("operation_id"), String.class); + private static final Field BASELINE_ID = + DSL.field(DSL.name("recorded_participant_digest_id"), Long.class); + private static final Field SOURCE_TENANT_ID = + DSL.field(DSL.name("source_tenant_id"), String.class); + private static final Field SOURCE_PUBLISH_TYPE = + DSL.field(DSL.name("source_publish_type"), String.class); + private static final Field SOURCE_PARTICIPANT_KEY = + DSL.field(DSL.name("source_participant_key"), String.class); + private static final Field SOURCE_BASE_VERSION_ID = + DSL.field(DSL.name("source_base_version_id"), Long.class); + private static final Field SOURCE_SCOPE_VALUE = + DSL.field(DSL.name("source_scope_value"), String.class); + private static final Field SOURCE_APPLIED_COMMIT_ID = + DSL.field(DSL.name("source_applied_commit_id"), String.class); + private static final Field SOURCE_CONTENT_DIGEST = + DSL.field(DSL.name("source_content_digest"), String.class); + private static final Field SOURCE_DIGEST_SCHEMA_VERSION = + DSL.field(DSL.name("source_digest_schema_version"), Integer.class); + private static final Field SOURCE_RECORDED_FROM_WORKFLOW_ID = + DSL.field(DSL.name("source_recorded_from_publish_workflow_id"), String.class); + private static final Field SOURCE_RECORDED_AT = + DSL.field(DSL.name("source_recorded_at"), LocalDateTime.class); + private static final Field SOURCE_LAST_VERIFIED_WORKFLOW_ID = + DSL.field(DSL.name("source_last_verified_publish_workflow_id"), String.class); + private static final Field SOURCE_LAST_VERIFIED_AT = + DSL.field(DSL.name("source_last_verified_at"), LocalDateTime.class); + private static final Field OBSERVED_TENANT_ID = + DSL.field(DSL.name("observed_tenant_id"), String.class); + private static final Field OBSERVED_PUBLISH_TYPE = + DSL.field(DSL.name("observed_publish_type"), String.class); + private static final Field OBSERVED_PARTICIPANT_KEY = + DSL.field(DSL.name("observed_participant_key"), String.class); + private static final Field OBSERVED_BASE_VERSION_ID = + DSL.field(DSL.name("observed_base_version_id"), Long.class); + private static final Field OBSERVED_SCOPE_VALUE = + DSL.field(DSL.name("observed_scope_value"), String.class); + private static final Field OBSERVED_APPLIED_COMMIT_ID = + DSL.field(DSL.name("observed_applied_commit_id"), String.class); + private static final Field OBSERVED_CONTENT_DIGEST = + DSL.field(DSL.name("observed_content_digest"), String.class); + private static final Field OBSERVED_DIGEST_SCHEMA_VERSION = + DSL.field(DSL.name("observed_digest_schema_version"), Integer.class); + private static final Field ACTOR_IDENTITY = + DSL.field(DSL.name("actor_identity"), String.class); + private static final Field WORKLOAD_IDENTITY = + DSL.field(DSL.name("workload_identity"), String.class); + private static final Field OUTCOME = DSL.field(DSL.name("outcome"), String.class); + private static final Field COMMITTED_AT = + DSL.field(DSL.name("committed_at"), LocalDateTime.class); + + private final DSLContext dsl; + + public EntityDigestBaselineMigrationAuditRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Inserts one immutable audit record; operation and baseline uniqueness are enforced by SQL. */ + public EntityDigestBaselineMigrationAudit insert(EntityDigestBaselineMigrationAudit audit) { + validateCommittedAudit(audit); + Record record = + dsl.insertInto(TABLE_REF) + .set(OPERATION_ID, audit.operationId()) + .set(BASELINE_ID, audit.recordedParticipantDigestId()) + .set(SOURCE_TENANT_ID, audit.sourceTenantId()) + .set(SOURCE_PUBLISH_TYPE, audit.sourcePublishType().name()) + .set(SOURCE_PARTICIPANT_KEY, audit.sourceParticipantKey().name()) + .set(SOURCE_BASE_VERSION_ID, audit.sourceBaseVersionId()) + .set(SOURCE_SCOPE_VALUE, audit.sourceScopeValue()) + .set(SOURCE_APPLIED_COMMIT_ID, audit.sourceAppliedCommitId()) + .set(SOURCE_CONTENT_DIGEST, audit.sourceContentDigest()) + .set(SOURCE_DIGEST_SCHEMA_VERSION, audit.sourceDigestSchemaVersion()) + .set(SOURCE_RECORDED_FROM_WORKFLOW_ID, audit.sourceRecordedFromPublishWorkflowId()) + .set(SOURCE_RECORDED_AT, audit.sourceRecordedAt()) + .set(SOURCE_LAST_VERIFIED_WORKFLOW_ID, audit.sourceLastVerifiedPublishWorkflowId()) + .set(SOURCE_LAST_VERIFIED_AT, audit.sourceLastVerifiedAt()) + .set(OBSERVED_TENANT_ID, audit.observedTenantId()) + .set(OBSERVED_PUBLISH_TYPE, audit.observedPublishType().name()) + .set(OBSERVED_PARTICIPANT_KEY, audit.observedParticipantKey().name()) + .set(OBSERVED_BASE_VERSION_ID, audit.observedBaseVersionId()) + .set(OBSERVED_SCOPE_VALUE, audit.observedScopeValue()) + .set(OBSERVED_APPLIED_COMMIT_ID, audit.observedAppliedCommitId()) + .set(OBSERVED_CONTENT_DIGEST, audit.observedContentDigest()) + .set(OBSERVED_DIGEST_SCHEMA_VERSION, audit.observedDigestSchemaVersion()) + .set(ACTOR_IDENTITY, audit.actorIdentity()) + .set(WORKLOAD_IDENTITY, audit.workloadIdentity()) + .set(OUTCOME, audit.outcome()) + .set(COMMITTED_AT, audit.committedAt()) + .returning() + .fetchOne(); + return toEntity(record); + } + + /** Resolves a prior operation by its stable id for exact retry and readback. */ + public Optional findByOperationId(String operationId) { + if (operationId == null || operationId.isBlank()) { + throw new IllegalArgumentException("operationId must not be blank"); + } + return Optional.ofNullable( + dsl.selectFrom(TABLE_REF).where(OPERATION_ID.eq(operationId)).fetchOne(this::toEntity)); + } + + private void validateCommittedAudit(EntityDigestBaselineMigrationAudit audit) { + if (audit == null) { + throw new IllegalArgumentException("audit is required"); + } + requireNonBlank(audit.operationId(), "operationId"); + requireNonBlank(audit.sourceTenantId(), "sourceTenantId"); + requireNonBlank(audit.sourceScopeValue(), "sourceScopeValue"); + requireNonBlank(audit.sourceAppliedCommitId(), "sourceAppliedCommitId"); + requireNonBlank(audit.sourceContentDigest(), "sourceContentDigest"); + requireNonBlank(audit.sourceRecordedFromPublishWorkflowId(), "sourceRecordedFrom workflow id"); + requireNonBlank(audit.sourceLastVerifiedPublishWorkflowId(), "sourceLastVerified workflow id"); + requireNonBlank(audit.observedTenantId(), "observedTenantId"); + requireNonBlank(audit.observedScopeValue(), "observedScopeValue"); + requireNonBlank(audit.observedAppliedCommitId(), "observedAppliedCommitId"); + requireNonBlank(audit.observedContentDigest(), "observedContentDigest"); + requireNonBlank(audit.actorIdentity(), "actorIdentity"); + requireNonBlank(audit.workloadIdentity(), "workloadIdentity"); + if (audit.recordedParticipantDigestId() == null + || audit.recordedParticipantDigestId() < 1 + || audit.sourcePublishType() != PublishType.FULL_VERSION + || audit.sourceParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || audit.sourceBaseVersionId() != null + || audit.sourceDigestSchemaVersion() != 1 + || audit.sourceRecordedAt() == null + || audit.sourceLastVerifiedAt() == null + || audit.observedPublishType() != PublishType.FULL_VERSION + || audit.observedParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || audit.observedBaseVersionId() != null + || audit.observedDigestSchemaVersion() != 2 + || !audit.sourceTenantId().equals(audit.observedTenantId()) + || !audit.sourceScopeValue().equals(audit.observedScopeValue()) + || !EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME.equals(audit.outcome()) + || audit.committedAt() == null) { + throw new IllegalArgumentException("audit is not a complete Entity v1-to-v2 commit record"); + } + } + + private void requireNonBlank(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(fieldName + " must not be blank"); + } + } + + private EntityDigestBaselineMigrationAudit toEntity(Record record) { + if (record == null) { + return null; + } + return new EntityDigestBaselineMigrationAudit( + record.get(ID), + record.get(OPERATION_ID), + record.get(BASELINE_ID), + record.get(SOURCE_TENANT_ID), + PublishType.valueOf(record.get(SOURCE_PUBLISH_TYPE)), + PublishParticipantKey.valueOf(record.get(SOURCE_PARTICIPANT_KEY)), + record.get(SOURCE_BASE_VERSION_ID), + record.get(SOURCE_SCOPE_VALUE), + record.get(SOURCE_APPLIED_COMMIT_ID), + record.get(SOURCE_CONTENT_DIGEST), + record.get(SOURCE_DIGEST_SCHEMA_VERSION), + record.get(SOURCE_RECORDED_FROM_WORKFLOW_ID), + record.get(SOURCE_RECORDED_AT), + record.get(SOURCE_LAST_VERIFIED_WORKFLOW_ID), + record.get(SOURCE_LAST_VERIFIED_AT), + record.get(OBSERVED_TENANT_ID), + PublishType.valueOf(record.get(OBSERVED_PUBLISH_TYPE)), + PublishParticipantKey.valueOf(record.get(OBSERVED_PARTICIPANT_KEY)), + record.get(OBSERVED_BASE_VERSION_ID), + record.get(OBSERVED_SCOPE_VALUE), + record.get(OBSERVED_APPLIED_COMMIT_ID), + record.get(OBSERVED_CONTENT_DIGEST), + record.get(OBSERVED_DIGEST_SCHEMA_VERSION), + record.get(ACTOR_IDENTITY), + record.get(WORKLOAD_IDENTITY), + record.get(OUTCOME), + record.get(COMMITTED_AT)); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java index ea1be7127d..4bc0ccc195 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java @@ -2,6 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.LocalDateTime; +import java.util.List; import java.util.Optional; import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; @@ -18,6 +19,9 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class RecordedParticipantDigestRepository { + private static final int MAX_ENTITY_BASELINE_MIGRATION_BATCH_SIZE = 500; + private static final int ENTITY_V1_DIGEST_SCHEMA_VERSION = 1; + private static final int ENTITY_V2_DIGEST_SCHEMA_VERSION = 2; private static final Table TABLE_REF = DSL.table(DSL.name("publish_recorded_participant_digest")); private static final Field ID = DSL.field(DSL.name("id"), Long.class); @@ -74,6 +78,148 @@ public RecordedParticipantDigestRepository(DSLContext dsl) { .fetchOne(this::toEntity)); } + /** Returns one ID-keyset page of retained full-version Entity v1 baselines. */ + public List findEntityV1FullVersionBatchAfterId( + long afterId, int limit) { + if (afterId < 0) { + throw new IllegalArgumentException("afterId must be non-negative"); + } + if (limit < 1 || limit > MAX_ENTITY_BASELINE_MIGRATION_BATCH_SIZE) { + throw new IllegalArgumentException( + "limit must be between 1 and " + MAX_ENTITY_BASELINE_MIGRATION_BATCH_SIZE); + } + return dsl.selectFrom(TABLE_REF) + .where( + ID.gt(afterId) + .and(PUBLISH_TYPE.eq(PublishType.FULL_VERSION.name())) + .and(PARTICIPANT_KEY.eq(PublishParticipantKey.ENTITY_MANAGEMENT.name())) + .and(BASE_VERSION_ID.isNull()) + .and(DIGEST_SCHEMA_VERSION.eq(ENTITY_V1_DIGEST_SCHEMA_VERSION))) + .orderBy(ID.asc()) + .limit(limit) + .fetch(this::toEntity); + } + + /** + * Reads at most two Entity full-version baselines for an exact tenant/version scope. Returning + * two rows is enough for callers to reject an ambiguous scope without loading unbounded data. + */ + public List findEntityFullVersionBaselinesByScope( + String tenantId, String versionId) { + requireNonBlank(tenantId, "tenantId"); + requireNonBlank(versionId, "versionId"); + return dsl.selectFrom(TABLE_REF) + .where( + TENANT_ID + .eq(tenantId) + .and(PUBLISH_TYPE.eq(PublishType.FULL_VERSION.name())) + .and(PARTICIPANT_KEY.eq(PublishParticipantKey.ENTITY_MANAGEMENT.name())) + .and(BASE_VERSION_ID.isNull()) + .and(SCOPE_VALUE.eq(versionId))) + .orderBy(ID.asc()) + .limit(2) + .fetch(this::toEntity); + } + + /** Reads a recorded baseline by its stable row identity for exact migration readback. */ + public Optional findById(long id) { + if (id < 1) { + throw new IllegalArgumentException("id must be positive"); + } + return Optional.ofNullable(dsl.selectFrom(TABLE_REF).where(ID.eq(id)).fetchOne(this::toEntity)); + } + + /** + * Replaces only the digest, schema, commit, and provenance when the complete expected v1 row is + * still present. The caller owns the transaction that also inserts the migration audit row. + * + * @return the number of rows changed; callers must require exactly one + */ + public int migrateEntityFullVersionBaselineIfUnchanged( + RecordedParticipantDigest expectedOld, RecordedParticipantDigest replacement) { + validateEntityBaselineMigrationPair(expectedOld, replacement); + return dsl.update(TABLE_REF) + .set(APPLIED_COMMIT_ID, replacement.getAppliedCommitId()) + .set(CONTENT_DIGEST, replacement.getContentDigest()) + .set(DIGEST_SCHEMA_VERSION, replacement.getDigestSchemaVersion()) + .set(RECORDED_FROM_PUBLISH_WORKFLOW_ID, replacement.getRecordedFromPublishWorkflowId()) + .set(RECORDED_AT, replacement.getRecordedAt()) + .set(LAST_VERIFIED_PUBLISH_WORKFLOW_ID, replacement.getLastVerifiedPublishWorkflowId()) + .set(LAST_VERIFIED_AT, replacement.getLastVerifiedAt()) + .where( + ID.eq(expectedOld.getId()) + .and(TENANT_ID.eq(expectedOld.getTenantId())) + .and(PUBLISH_TYPE.eq(PublishType.FULL_VERSION.name())) + .and(PARTICIPANT_KEY.eq(PublishParticipantKey.ENTITY_MANAGEMENT.name())) + .and(BASE_VERSION_ID.isNull()) + .and(SCOPE_VALUE.eq(expectedOld.getScopeValue())) + .and(APPLIED_COMMIT_ID.eq(expectedOld.getAppliedCommitId())) + .and(CONTENT_DIGEST.eq(expectedOld.getContentDigest())) + .and(DIGEST_SCHEMA_VERSION.eq(ENTITY_V1_DIGEST_SCHEMA_VERSION)) + .and( + RECORDED_FROM_PUBLISH_WORKFLOW_ID.eq( + expectedOld.getRecordedFromPublishWorkflowId())) + .and(RECORDED_AT.eq(expectedOld.getRecordedAt())) + .and( + LAST_VERIFIED_PUBLISH_WORKFLOW_ID.eq( + expectedOld.getLastVerifiedPublishWorkflowId())) + .and(LAST_VERIFIED_AT.eq(expectedOld.getLastVerifiedAt()))) + .execute(); + } + + private void validateEntityBaselineMigrationPair( + RecordedParticipantDigest expectedOld, RecordedParticipantDigest replacement) { + if (expectedOld == null || replacement == null) { + throw new IllegalArgumentException("expected and replacement baselines are required"); + } + requireNonBlank(expectedOld.getTenantId(), "expected tenantId"); + requireNonBlank(expectedOld.getScopeValue(), "expected scopeValue"); + requireNonBlank(expectedOld.getAppliedCommitId(), "expected appliedCommitId"); + requireNonBlank(expectedOld.getContentDigest(), "expected contentDigest"); + requireNonBlank( + expectedOld.getRecordedFromPublishWorkflowId(), "expected recordedFromPublishWorkflowId"); + requireNonBlank( + expectedOld.getLastVerifiedPublishWorkflowId(), "expected lastVerifiedPublishWorkflowId"); + if (expectedOld.getId() == null + || expectedOld.getId() < 1 + || expectedOld.getPublishType() != PublishType.FULL_VERSION + || expectedOld.getParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || expectedOld.getBaseVersionId() != null + || expectedOld.getDigestSchemaVersion() != ENTITY_V1_DIGEST_SCHEMA_VERSION + || expectedOld.getRecordedAt() == null + || expectedOld.getLastVerifiedAt() == null) { + throw new IllegalArgumentException("expected baseline is not a complete Entity v1 row"); + } + + requireNonBlank(replacement.getTenantId(), "replacement tenantId"); + requireNonBlank(replacement.getScopeValue(), "replacement scopeValue"); + requireNonBlank(replacement.getAppliedCommitId(), "replacement appliedCommitId"); + requireNonBlank(replacement.getContentDigest(), "replacement contentDigest"); + requireNonBlank( + replacement.getRecordedFromPublishWorkflowId(), + "replacement recordedFromPublishWorkflowId"); + requireNonBlank( + replacement.getLastVerifiedPublishWorkflowId(), + "replacement lastVerifiedPublishWorkflowId"); + if (!expectedOld.getTenantId().equals(replacement.getTenantId()) + || !expectedOld.getScopeValue().equals(replacement.getScopeValue()) + || (replacement.getId() != null && !expectedOld.getId().equals(replacement.getId())) + || replacement.getPublishType() != PublishType.FULL_VERSION + || replacement.getParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || replacement.getBaseVersionId() != null + || replacement.getDigestSchemaVersion() != ENTITY_V2_DIGEST_SCHEMA_VERSION + || replacement.getRecordedAt() == null + || replacement.getLastVerifiedAt() == null) { + throw new IllegalArgumentException("replacement is not the matching Entity v2 baseline"); + } + } + + private void requireNonBlank(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(fieldName + " must not be blank"); + } + } + public RecordedParticipantDigest save(RecordedParticipantDigest digest) { LocalDateTime recordedAt = digest.getRecordedAt() == null ? LocalDateTime.now() : digest.getRecordedAt(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java new file mode 100644 index 0000000000..c42585eac3 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java @@ -0,0 +1,641 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.client.EntityManagementClient; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; +import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.repository.EntityDigestBaselineMigrationAuditRepository; +import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.springframework.stereotype.Service; + +/** Bounded enumeration, preflight, and one-scope recomputation for retained Entity v1 baselines. */ +@Service +public class EntityDigestBaselineMigrationService { + private static final int SOURCE_SCHEMA_VERSION = 1; + private static final int TARGET_SCHEMA_VERSION = 2; + private static final int MAX_BATCH_SIZE = 500; + private static final int MAX_OPERATION_ID_UTF8_BYTES = 128; + private static final int MAX_AUDIT_IDENTITY_UTF8_BYTES = 256; + private static final String PUBLICATION_REQUEST_PREFIX = "entity-baseline-migration-"; + + private final RecordedParticipantDigestRepository baselineRepository; + private final EntityDigestBaselineMigrationAuditRepository auditRepository; + private final VersionRepository versionRepository; + private final EntityManagementClient entityManagementClient; + private final EntityDigestBaselineMigrationWriteService writeService; + + public EntityDigestBaselineMigrationService( + RecordedParticipantDigestRepository baselineRepository, + EntityDigestBaselineMigrationAuditRepository auditRepository, + VersionRepository versionRepository, + EntityManagementClient entityManagementClient, + EntityDigestBaselineMigrationWriteService writeService) { + this.baselineRepository = baselineRepository; + this.auditRepository = auditRepository; + this.versionRepository = versionRepository; + this.entityManagementClient = entityManagementClient; + this.writeService = writeService; + } + + /** Returns one keyset page of retained Entity full-version schema-v1 rows. */ + public EntityV1Batch enumerateEntityV1Batch(long afterBaselineId, int limit) { + if (afterBaselineId < 0) { + throw new IllegalArgumentException("afterBaselineId must be non-negative"); + } + if (limit < 1 || limit > MAX_BATCH_SIZE) { + throw new IllegalArgumentException("limit must be between 1 and " + MAX_BATCH_SIZE); + } + List rows = + baselineRepository.findEntityV1FullVersionBatchAfterId(afterBaselineId, limit); + if (rows.size() > limit) { + throw new IllegalStateException("baseline batch exceeded the requested bound"); + } + List summaries = rows.stream().map(this::toV1Summary).toList(); + Long nextAfterBaselineId = + summaries.isEmpty() ? null : summaries.get(summaries.size() - 1).baselineId(); + return new EntityV1Batch(afterBaselineId, limit, summaries, nextAfterBaselineId); + } + + /** + * Classifies exactly one tenant/version scope without writing. NO_RECORDED_BASELINE proves only + * this queried scope has no retained Entity full-version baseline at read time. + */ + public ScopePreflight preflightScope(String tenantId, long versionId) { + requireText(tenantId, "tenantId", 36); + requirePositive(versionId, "versionId"); + Version version = + versionRepository + .findByTenantIdAndId(tenantId, versionId) + .orElseThrow(() -> rejected("VERSION_MISSING", "tenant/version does not exist")); + if (!Objects.equals(version.getTenantId(), tenantId) + || !Objects.equals(version.getId(), versionId) + || version.isScriptOnly()) { + throw rejected("VERSION_SCOPE_MISMATCH", "version is outside the tenant or is script-only"); + } + List rows = + baselineRepository.findEntityFullVersionBaselinesByScope( + tenantId, Long.toString(versionId)); + if (rows.size() > 2) { + throw new IllegalStateException("scope preflight exceeded its two-row bound"); + } + for (RecordedParticipantDigest row : rows) { + if (!Objects.equals(row.getTenantId(), tenantId) + || !Objects.equals(row.getScopeValue(), Long.toString(versionId)) + || row.getPublishType() != PublishType.FULL_VERSION + || row.getParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || row.getBaseVersionId() != null) { + throw new IllegalStateException("scope query returned a row outside its exact scope"); + } + } + ScopeStatus status; + if (rows.isEmpty()) { + status = ScopeStatus.NO_RECORDED_BASELINE; + } else if (rows.size() > 1) { + status = ScopeStatus.AMBIGUOUS_BASELINE; + } else if (Objects.equals(rows.get(0).getDigestSchemaVersion(), SOURCE_SCHEMA_VERSION)) { + status = ScopeStatus.V1_REQUIRES_MIGRATION; + } else if (Objects.equals(rows.get(0).getDigestSchemaVersion(), TARGET_SCHEMA_VERSION)) { + status = ScopeStatus.V2_ALREADY_RECORDED; + } else { + status = ScopeStatus.UNSUPPORTED_SCHEMA; + } + return new ScopePreflight( + tenantId, versionId, status, rows.stream().map(this::toSummary).toList()); + } + + /** Recomputes and atomically re-records one exact Entity full-version v1 baseline. */ + public MigrationResult migrate(MigrationCommand command) { + validateCommand(command); + + Optional priorAudit = + auditRepository.findByOperationId(command.operationId()); + if (priorAudit.isPresent()) { + EntityDigestBaselineMigrationAudit audit = priorAudit.orElseThrow(); + assertAuditSourceMatchesCommand(audit, command); + return readBackCommittedResult(command, audit, MigrationDisposition.EXACT_RETRY); + } + + RecordedParticipantDigest current = + baselineRepository + .findById(command.baselineId()) + .orElseThrow(() -> rejected("BASELINE_MISSING", "baseline row does not exist")); + validateCurrentRowIdentity(current, command); + List scopeRows = + baselineRepository.findEntityFullVersionBaselinesByScope( + command.tenantId(), Long.toString(command.versionId())); + if (scopeRows.size() != 1) { + throw rejected( + scopeRows.isEmpty() ? "BASELINE_MISSING" : "BASELINE_SCOPE_AMBIGUOUS", + "the exact tenant/version scope must contain one Entity full-version baseline"); + } + if (!Objects.equals(scopeRows.get(0).getId(), command.baselineId())) { + throw rejected( + "BASELINE_ID_SCOPE_MISMATCH", "baseline id does not own the requested tenant/version"); + } + assertSourceMatchesCommand(current, command.expectedSource()); + + Version version = + versionRepository + .findByTenantIdAndId(command.tenantId(), command.versionId()) + .orElseThrow(() -> rejected("VERSION_MISSING", "tenant/version does not exist")); + if (!Objects.equals(version.getTenantId(), command.tenantId()) + || !Objects.equals(version.getId(), command.versionId()) + || version.isScriptOnly()) { + throw rejected("VERSION_SCOPE_MISMATCH", "version is outside the tenant or is script-only"); + } + + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full( + command.tenantId(), + Long.toString(command.versionId()), + stablePublicationRequestId(command.operationId())); + PublishParticipantDigestDto observed = + entityManagementClient.getDraftDesignDigestForVersion(binding); + validateObservedDigest(observed, command); + + LocalDateTime migrationTime = LocalDateTime.now().truncatedTo(ChronoUnit.MICROS); + RecordedParticipantDigest replacement = + replacementFor(current, observed, command.operationId(), migrationTime); + EntityDigestBaselineMigrationAudit audit = auditFor(current, observed, command, migrationTime); + try { + writeService.commit(current, replacement, audit); + } catch (RuntimeException uncertainWrite) { + try { + return readBackCommittedResult( + command, audit, MigrationDisposition.RECOVERED_AFTER_WRITE_ERROR); + } catch (RuntimeException readbackFailure) { + uncertainWrite.addSuppressed(readbackFailure); + throw rejected( + "WRITE_OUTCOME_UNPROVEN", + "migration write outcome could not be proven by exact audit and baseline readback", + uncertainWrite); + } + } + return readBackCommittedResult(command, audit, MigrationDisposition.APPLIED); + } + + private void validateCommand(MigrationCommand command) { + if (command == null) { + throw new IllegalArgumentException("migration command is required"); + } + requireText(command.operationId(), "operationId", MAX_OPERATION_ID_UTF8_BYTES); + requireText(command.tenantId(), "tenantId", 36); + requirePositive(command.baselineId(), "baselineId"); + requirePositive(command.versionId(), "versionId"); + requireText(command.actorIdentity(), "actorIdentity", MAX_AUDIT_IDENTITY_UTF8_BYTES); + requireText(command.workloadIdentity(), "workloadIdentity", MAX_AUDIT_IDENTITY_UTF8_BYTES); + ExpectedSource expected = Objects.requireNonNull(command.expectedSource(), "expectedSource"); + requireText(expected.tenantId(), "expected tenantId", 36); + requireText(expected.scopeValue(), "expected scopeValue", 128); + requireText(expected.appliedCommitId(), "expected appliedCommitId", 128); + requireText(expected.contentDigest(), "expected contentDigest", 128); + requireText(expected.recordedFromPublishWorkflowId(), "expected recordedFrom workflow", 1024); + requireText(expected.lastVerifiedPublishWorkflowId(), "expected lastVerified workflow", 1024); + if (expected.digestSchemaVersion() == null + || expected.digestSchemaVersion() != SOURCE_SCHEMA_VERSION + || expected.recordedAt() == null + || expected.lastVerifiedAt() == null + || expected.baselineId() == null + || expected.baselineId() < 1 + || !Objects.equals(expected.baselineId(), command.baselineId()) + || !Objects.equals(expected.tenantId(), command.tenantId()) + || expected.publishType() != PublishType.FULL_VERSION + || expected.participantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || expected.baseVersionId() != null + || !Objects.equals(expected.scopeValue(), Long.toString(command.versionId()))) { + throw rejected( + "SOURCE_SCHEMA_OR_PROVENANCE_INVALID", + "expected source must be a complete schema-v1 baseline with provenance"); + } + } + + private void validateCurrentRowIdentity( + RecordedParticipantDigest current, MigrationCommand command) { + if (!Objects.equals(current.getId(), command.baselineId())) { + throw rejected("BASELINE_ID_MISMATCH", "baseline readback id does not match the command"); + } + if (!Objects.equals(current.getTenantId(), command.tenantId())) { + throw rejected("BASELINE_TENANT_MISMATCH", "baseline belongs to another tenant"); + } + if (current.getPublishType() != PublishType.FULL_VERSION + || current.getParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || current.getBaseVersionId() != null) { + throw rejected( + "BASELINE_PARTICIPANT_OR_SCOPE_INVALID", "baseline is not an Entity full-version record"); + } + if (!Objects.equals(current.getScopeValue(), Long.toString(command.versionId()))) { + throw rejected("BASELINE_VERSION_MISMATCH", "baseline belongs to another version"); + } + if (!Objects.equals(current.getDigestSchemaVersion(), SOURCE_SCHEMA_VERSION)) { + throw rejected( + "SOURCE_SCHEMA_UNSUPPORTED", "migration source must be an Entity schema-v1 row"); + } + } + + private void assertSourceMatchesCommand( + RecordedParticipantDigest current, ExpectedSource expected) { + if (!Objects.equals(current.getId(), expected.baselineId()) + || !Objects.equals(current.getTenantId(), expected.tenantId()) + || current.getPublishType() != expected.publishType() + || current.getParticipantKey() != expected.participantKey() + || !Objects.equals(current.getBaseVersionId(), expected.baseVersionId()) + || !Objects.equals(current.getScopeValue(), expected.scopeValue()) + || !Objects.equals(current.getAppliedCommitId(), expected.appliedCommitId()) + || !Objects.equals(current.getContentDigest(), expected.contentDigest()) + || !Objects.equals(current.getDigestSchemaVersion(), expected.digestSchemaVersion()) + || !Objects.equals( + current.getRecordedFromPublishWorkflowId(), expected.recordedFromPublishWorkflowId()) + || !Objects.equals(current.getRecordedAt(), expected.recordedAt()) + || !Objects.equals( + current.getLastVerifiedPublishWorkflowId(), expected.lastVerifiedPublishWorkflowId()) + || !Objects.equals(current.getLastVerifiedAt(), expected.lastVerifiedAt())) { + throw rejected( + "SOURCE_BASELINE_CHANGED", + "baseline tuple or provenance changed after the expected source was captured"); + } + } + + private void validateObservedDigest( + PublishParticipantDigestDto observed, MigrationCommand command) { + if (observed == null || !observed.succeeded()) { + throw rejected( + "ENTITY_DIGEST_UNAVAILABLE", + observed == null ? "Entity returned no digest response" : observed.errorCode()); + } + if (!PublishParticipantKey.ENTITY_MANAGEMENT.name().equals(observed.participantKey()) + || !Long.toString(command.versionId()).equals(observed.scopeValue()) + || observed.baseVersionId() != null) { + throw rejected( + "ENTITY_DIGEST_SCOPE_MISMATCH", "Entity v2 evidence does not match the exact scope"); + } + if (!Objects.equals(observed.digestSchemaVersion(), TARGET_SCHEMA_VERSION)) { + throw rejected("ENTITY_DIGEST_SCHEMA_UNSUPPORTED", "Entity did not return digest schema 2"); + } + if (observed.contentDigest() == null || observed.contentDigest().isBlank()) { + throw rejected("ENTITY_DIGEST_INCOMPLETE", "Entity returned a blank v2 content digest"); + } + if (observed.contentDigest().getBytes(StandardCharsets.UTF_8).length > 128) { + throw rejected("ENTITY_DIGEST_INCOMPLETE", "Entity v2 content digest exceeds storage bounds"); + } + if (observed.appliedCommitId() == null + || observed.appliedCommitId().isBlank() + || !Objects.equals( + observed.appliedCommitId(), command.expectedSource().appliedCommitId())) { + throw rejected( + "ENTITY_APPLIED_COMMIT_MISMATCH", + "Entity v2 evidence does not preserve the expected applied-commit identity"); + } + } + + private RecordedParticipantDigest replacementFor( + RecordedParticipantDigest current, + PublishParticipantDigestDto observed, + String operationId, + LocalDateTime migrationTime) { + RecordedParticipantDigest replacement = new RecordedParticipantDigest(); + replacement.setId(current.getId()); + replacement.setTenantId(current.getTenantId()); + replacement.setPublishType(current.getPublishType()); + replacement.setParticipantKey(current.getParticipantKey()); + replacement.setScopeValue(current.getScopeValue()); + replacement.setBaseVersionId(null); + replacement.setAppliedCommitId(observed.appliedCommitId()); + replacement.setContentDigest(observed.contentDigest()); + replacement.setDigestSchemaVersion(TARGET_SCHEMA_VERSION); + replacement.setRecordedFromPublishWorkflowId(operationId); + replacement.setRecordedAt(migrationTime); + replacement.setLastVerifiedPublishWorkflowId(operationId); + replacement.setLastVerifiedAt(migrationTime); + return replacement; + } + + private EntityDigestBaselineMigrationAudit auditFor( + RecordedParticipantDigest source, + PublishParticipantDigestDto observed, + MigrationCommand command, + LocalDateTime migrationTime) { + return new EntityDigestBaselineMigrationAudit( + null, + command.operationId(), + source.getId(), + source.getTenantId(), + source.getPublishType(), + source.getParticipantKey(), + source.getBaseVersionId(), + source.getScopeValue(), + source.getAppliedCommitId(), + source.getContentDigest(), + source.getDigestSchemaVersion(), + source.getRecordedFromPublishWorkflowId(), + source.getRecordedAt(), + source.getLastVerifiedPublishWorkflowId(), + source.getLastVerifiedAt(), + source.getTenantId(), + source.getPublishType(), + source.getParticipantKey(), + null, + source.getScopeValue(), + observed.appliedCommitId(), + observed.contentDigest(), + observed.digestSchemaVersion(), + command.actorIdentity(), + command.workloadIdentity(), + EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME, + migrationTime); + } + + private void assertAuditSourceMatchesCommand( + EntityDigestBaselineMigrationAudit audit, MigrationCommand command) { + ExpectedSource expected = command.expectedSource(); + if (!Objects.equals(audit.operationId(), command.operationId()) + || audit.id() == null + || audit.id() < 1 + || !Objects.equals(audit.recordedParticipantDigestId(), command.baselineId()) + || !Objects.equals(audit.sourceTenantId(), command.tenantId()) + || audit.sourcePublishType() != expected.publishType() + || audit.sourceParticipantKey() != expected.participantKey() + || !Objects.equals(audit.sourceBaseVersionId(), expected.baseVersionId()) + || !Objects.equals(audit.sourceScopeValue(), Long.toString(command.versionId())) + || !Objects.equals(audit.sourceAppliedCommitId(), expected.appliedCommitId()) + || !Objects.equals(audit.sourceContentDigest(), expected.contentDigest()) + || !Objects.equals(audit.sourceDigestSchemaVersion(), expected.digestSchemaVersion()) + || !Objects.equals( + audit.sourceRecordedFromPublishWorkflowId(), expected.recordedFromPublishWorkflowId()) + || !Objects.equals(audit.sourceRecordedAt(), expected.recordedAt()) + || !Objects.equals( + audit.sourceLastVerifiedPublishWorkflowId(), expected.lastVerifiedPublishWorkflowId()) + || !Objects.equals(audit.sourceLastVerifiedAt(), expected.lastVerifiedAt()) + || !Objects.equals(audit.actorIdentity(), command.actorIdentity()) + || !Objects.equals(audit.workloadIdentity(), command.workloadIdentity()) + || !Objects.equals(audit.observedTenantId(), command.tenantId()) + || audit.observedPublishType() != PublishType.FULL_VERSION + || audit.observedParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || audit.observedBaseVersionId() != null + || !Objects.equals(audit.observedScopeValue(), Long.toString(command.versionId())) + || !Objects.equals(audit.observedAppliedCommitId(), expected.appliedCommitId()) + || !Objects.equals(audit.observedDigestSchemaVersion(), TARGET_SCHEMA_VERSION) + || audit.observedContentDigest() == null + || audit.observedContentDigest().isBlank() + || !EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME.equals(audit.outcome())) { + throw rejected( + "OPERATION_ID_CONFLICT", "operation id is already bound to a different source command"); + } + } + + private MigrationResult readBackCommittedResult( + MigrationCommand command, + EntityDigestBaselineMigrationAudit expectedAudit, + MigrationDisposition disposition) { + EntityDigestBaselineMigrationAudit actualAudit = + auditRepository + .findByOperationId(command.operationId()) + .orElseThrow( + () -> + rejected("AUDIT_READBACK_MISSING", "committed migration audit was not found")); + assertAuditSourceMatchesCommand(actualAudit, command); + if (!sameAuditTarget(actualAudit, expectedAudit)) { + throw rejected("AUDIT_READBACK_MISMATCH", "audit target differs from the attempted result"); + } + RecordedParticipantDigest actualBaseline = + baselineRepository + .findById(command.baselineId()) + .orElseThrow( + () -> rejected("BASELINE_READBACK_MISSING", "migrated baseline was not found")); + if (!Objects.equals(actualBaseline.getId(), actualAudit.recordedParticipantDigestId()) + || !Objects.equals(actualBaseline.getTenantId(), actualAudit.observedTenantId()) + || actualBaseline.getPublishType() != actualAudit.observedPublishType() + || actualBaseline.getParticipantKey() != actualAudit.observedParticipantKey() + || !Objects.equals(actualBaseline.getBaseVersionId(), actualAudit.observedBaseVersionId()) + || !Objects.equals(actualBaseline.getScopeValue(), actualAudit.observedScopeValue()) + || !Objects.equals( + actualBaseline.getAppliedCommitId(), actualAudit.observedAppliedCommitId()) + || !Objects.equals(actualBaseline.getContentDigest(), actualAudit.observedContentDigest()) + || !Objects.equals( + actualBaseline.getDigestSchemaVersion(), actualAudit.observedDigestSchemaVersion()) + || !Objects.equals(actualBaseline.getRecordedFromPublishWorkflowId(), command.operationId()) + || !Objects.equals(actualBaseline.getRecordedAt(), actualAudit.committedAt()) + || !Objects.equals(actualBaseline.getLastVerifiedPublishWorkflowId(), command.operationId()) + || !Objects.equals(actualBaseline.getLastVerifiedAt(), actualAudit.committedAt())) { + throw rejected( + "BASELINE_READBACK_MISMATCH", "persisted baseline does not exactly match its audit"); + } + return new MigrationResult( + command.operationId(), + actualAudit.id(), + actualBaseline.getId(), + command.tenantId(), + command.versionId(), + actualBaseline.getAppliedCommitId(), + actualBaseline.getContentDigest(), + actualBaseline.getDigestSchemaVersion(), + disposition); + } + + private boolean sameAuditTarget( + EntityDigestBaselineMigrationAudit actual, EntityDigestBaselineMigrationAudit expected) { + return (expected.id() == null || Objects.equals(actual.id(), expected.id())) + && Objects.equals(actual.operationId(), expected.operationId()) + && Objects.equals( + actual.recordedParticipantDigestId(), expected.recordedParticipantDigestId()) + && Objects.equals(actual.observedTenantId(), expected.observedTenantId()) + && actual.observedPublishType() == expected.observedPublishType() + && actual.observedParticipantKey() == expected.observedParticipantKey() + && Objects.equals(actual.observedBaseVersionId(), expected.observedBaseVersionId()) + && Objects.equals(actual.observedScopeValue(), expected.observedScopeValue()) + && Objects.equals(actual.observedAppliedCommitId(), expected.observedAppliedCommitId()) + && Objects.equals(actual.observedContentDigest(), expected.observedContentDigest()) + && Objects.equals( + actual.observedDigestSchemaVersion(), expected.observedDigestSchemaVersion()) + && Objects.equals(actual.actorIdentity(), expected.actorIdentity()) + && Objects.equals(actual.workloadIdentity(), expected.workloadIdentity()) + && Objects.equals(actual.outcome(), expected.outcome()) + && Objects.equals(actual.committedAt(), expected.committedAt()); + } + + private BaselineSummary toV1Summary(RecordedParticipantDigest row) { + if (row.getDigestSchemaVersion() == null + || row.getDigestSchemaVersion() != SOURCE_SCHEMA_VERSION + || row.getPublishType() != PublishType.FULL_VERSION + || row.getParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || row.getBaseVersionId() != null) { + throw new IllegalStateException("v1 batch query returned a non-Entity full-version row"); + } + return toSummary(row); + } + + private BaselineSummary toSummary(RecordedParticipantDigest row) { + if (row.getId() == null || row.getId() < 1) { + throw new IllegalStateException("baseline query returned a row without a stable id"); + } + long versionId = parsePositiveVersionId(row.getId(), row.getScopeValue()); + return new BaselineSummary( + row.getId(), + row.getTenantId(), + versionId, + row.getAppliedCommitId(), + row.getContentDigest(), + row.getDigestSchemaVersion(), + row.getRecordedFromPublishWorkflowId(), + row.getRecordedAt(), + row.getLastVerifiedPublishWorkflowId(), + row.getLastVerifiedAt()); + } + + private long parsePositiveVersionId(long baselineId, String scopeValue) { + try { + long id = Long.parseLong(scopeValue); + if (id < 1 || !Long.toString(id).equals(scopeValue)) { + throw new NumberFormatException("non-canonical positive id"); + } + return id; + } catch (RuntimeException invalidScope) { + throw new IllegalStateException( + "Entity full-version baseline " + + baselineId + + " has a non-canonical positive version scope: " + + scopeValue, + invalidScope); + } + } + + private String stablePublicationRequestId(String operationId) { + try { + byte[] hash = + MessageDigest.getInstance("SHA-256").digest(operationId.getBytes(StandardCharsets.UTF_8)); + return PUBLICATION_REQUEST_PREFIX + HexFormat.of().formatHex(hash); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private void requireText(String value, String name, int maxUtf8Bytes) { + if (value == null + || value.isBlank() + || value.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes) { + throw new IllegalArgumentException(name + " must be non-blank and within its storage bound"); + } + } + + private void requirePositive(long value, String name) { + if (value < 1) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private MigrationRejectedException rejected(String code, String message) { + return new MigrationRejectedException(code, message, null); + } + + private MigrationRejectedException rejected(String code, String message, Throwable cause) { + return new MigrationRejectedException(code, message, cause); + } + + public enum ScopeStatus { + V1_REQUIRES_MIGRATION, + V2_ALREADY_RECORDED, + NO_RECORDED_BASELINE, + AMBIGUOUS_BASELINE, + UNSUPPORTED_SCHEMA + } + + public enum MigrationDisposition { + APPLIED, + EXACT_RETRY, + RECOVERED_AFTER_WRITE_ERROR + } + + public record ExpectedSource( + Long baselineId, + String tenantId, + PublishType publishType, + PublishParticipantKey participantKey, + Long baseVersionId, + String scopeValue, + String appliedCommitId, + String contentDigest, + Integer digestSchemaVersion, + String recordedFromPublishWorkflowId, + LocalDateTime recordedAt, + String lastVerifiedPublishWorkflowId, + LocalDateTime lastVerifiedAt) {} + + public record MigrationCommand( + String operationId, + long baselineId, + String tenantId, + long versionId, + ExpectedSource expectedSource, + String actorIdentity, + String workloadIdentity) {} + + public record BaselineSummary( + long baselineId, + String tenantId, + long versionId, + String appliedCommitId, + String contentDigest, + Integer digestSchemaVersion, + String recordedFromPublishWorkflowId, + LocalDateTime recordedAt, + String lastVerifiedPublishWorkflowId, + LocalDateTime lastVerifiedAt) {} + + public record EntityV1Batch( + long scannedAfterBaselineId, + int limit, + List baselines, + Long nextAfterBaselineId) { + public EntityV1Batch { + baselines = List.copyOf(baselines); + } + + public boolean isEmptyAtCursor() { + return baselines.isEmpty(); + } + } + + public record ScopePreflight( + String tenantId, long versionId, ScopeStatus status, List baselines) { + public ScopePreflight { + baselines = List.copyOf(baselines); + } + } + + public record MigrationResult( + String operationId, + Long auditId, + Long baselineId, + String tenantId, + long versionId, + String appliedCommitId, + String contentDigest, + Integer digestSchemaVersion, + MigrationDisposition disposition) {} + + public static final class MigrationRejectedException extends IllegalStateException { + private final String failureCode; + + private MigrationRejectedException(String failureCode, String message, Throwable cause) { + super(message, cause); + this.failureCode = failureCode; + } + + public String failureCode() { + return failureCode; + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java new file mode 100644 index 0000000000..a074832ef5 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.Objects; +import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; +import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; +import net.firedevops.firemud.gamedesign.repository.EntityDigestBaselineMigrationAuditRepository; +import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Commits one guarded baseline replacement and its immutable audit row in the same transaction. */ +@Service +public class EntityDigestBaselineMigrationWriteService { + private final RecordedParticipantDigestRepository baselineRepository; + private final EntityDigestBaselineMigrationAuditRepository auditRepository; + + public EntityDigestBaselineMigrationWriteService( + RecordedParticipantDigestRepository baselineRepository, + EntityDigestBaselineMigrationAuditRepository auditRepository) { + this.baselineRepository = baselineRepository; + this.auditRepository = auditRepository; + } + + @Transactional + public void commit( + RecordedParticipantDigest expectedOld, + RecordedParticipantDigest replacement, + EntityDigestBaselineMigrationAudit audit) { + validateWriteSet(expectedOld, replacement, audit); + int updated = + baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(expectedOld, replacement); + if (updated != 1) { + throw new IllegalStateException( + "Entity v1 baseline changed before the guarded migration write"); + } + auditRepository.insert(audit); + } + + private void validateWriteSet( + RecordedParticipantDigest expectedOld, + RecordedParticipantDigest replacement, + EntityDigestBaselineMigrationAudit audit) { + Objects.requireNonNull(expectedOld, "expectedOld must not be null"); + Objects.requireNonNull(replacement, "replacement must not be null"); + Objects.requireNonNull(audit, "audit must not be null"); + if (!Objects.equals(expectedOld.getId(), replacement.getId()) + || !Objects.equals(expectedOld.getTenantId(), replacement.getTenantId()) + || expectedOld.getPublishType() != replacement.getPublishType() + || expectedOld.getParticipantKey() != replacement.getParticipantKey() + || !Objects.equals(expectedOld.getScopeValue(), replacement.getScopeValue()) + || !Objects.equals(expectedOld.getAppliedCommitId(), replacement.getAppliedCommitId()) + || !Objects.equals(expectedOld.getBaseVersionId(), replacement.getBaseVersionId()) + || !Objects.equals( + expectedOld.getRecordedFromPublishWorkflowId(), + audit.sourceRecordedFromPublishWorkflowId()) + || !Objects.equals(expectedOld.getRecordedAt(), audit.sourceRecordedAt()) + || !Objects.equals( + expectedOld.getLastVerifiedPublishWorkflowId(), + audit.sourceLastVerifiedPublishWorkflowId()) + || !Objects.equals(expectedOld.getLastVerifiedAt(), audit.sourceLastVerifiedAt()) + || !Objects.equals(expectedOld.getContentDigest(), audit.sourceContentDigest()) + || !Objects.equals(expectedOld.getDigestSchemaVersion(), audit.sourceDigestSchemaVersion()) + || expectedOld.getPublishType() != audit.sourcePublishType() + || expectedOld.getParticipantKey() != audit.sourceParticipantKey() + || !Objects.equals(expectedOld.getBaseVersionId(), audit.sourceBaseVersionId()) + || !Integer.valueOf(1).equals(expectedOld.getDigestSchemaVersion()) + || !Objects.equals(expectedOld.getId(), audit.recordedParticipantDigestId()) + || !Objects.equals(expectedOld.getTenantId(), audit.sourceTenantId()) + || !Objects.equals(expectedOld.getScopeValue(), audit.sourceScopeValue()) + || !Objects.equals(expectedOld.getAppliedCommitId(), audit.sourceAppliedCommitId()) + || !Objects.equals(replacement.getTenantId(), audit.observedTenantId()) + || replacement.getPublishType() != audit.observedPublishType() + || replacement.getParticipantKey() != audit.observedParticipantKey() + || !Objects.equals(replacement.getBaseVersionId(), audit.observedBaseVersionId()) + || !Objects.equals(replacement.getScopeValue(), audit.observedScopeValue()) + || !Objects.equals(replacement.getAppliedCommitId(), audit.observedAppliedCommitId()) + || !Objects.equals(replacement.getContentDigest(), audit.observedContentDigest()) + || !Objects.equals( + replacement.getDigestSchemaVersion(), audit.observedDigestSchemaVersion()) + || !Integer.valueOf(2).equals(replacement.getDigestSchemaVersion()) + || audit.observedContentDigest() == null + || audit.observedContentDigest().isBlank() + || !Objects.equals(replacement.getRecordedFromPublishWorkflowId(), audit.operationId()) + || !Objects.equals(replacement.getLastVerifiedPublishWorkflowId(), audit.operationId()) + || !Objects.equals(replacement.getRecordedAt(), audit.committedAt()) + || !Objects.equals(replacement.getLastVerifiedAt(), audit.committedAt()) + || !EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME.equals(audit.outcome())) { + throw new IllegalArgumentException( + "migration audit and guarded baseline replacement do not describe one operation"); + } + } +} diff --git a/services/game-design-service/src/main/resources/db/migration/V29__entity_digest_baseline_migration.sql b/services/game-design-service/src/main/resources/db/migration/V29__entity_digest_baseline_migration.sql new file mode 100644 index 0000000000..2e9ec10ac1 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V29__entity_digest_baseline_migration.sql @@ -0,0 +1,53 @@ +CREATE TABLE entity_digest_baseline_migration_audit ( + id BIGSERIAL PRIMARY KEY, + operation_id VARCHAR(128) NOT NULL, + recorded_participant_digest_id BIGINT NOT NULL, + source_tenant_id VARCHAR(36) NOT NULL, + source_publish_type VARCHAR(32) NOT NULL, + source_participant_key VARCHAR(64) NOT NULL, + source_base_version_id BIGINT, + source_scope_value VARCHAR(128) NOT NULL, + source_applied_commit_id VARCHAR(128) NOT NULL, + source_content_digest VARCHAR(128) NOT NULL, + source_digest_schema_version INT NOT NULL, + source_recorded_from_publish_workflow_id VARCHAR(1024) NOT NULL, + source_recorded_at TIMESTAMP NOT NULL, + source_last_verified_publish_workflow_id VARCHAR(1024) NOT NULL, + source_last_verified_at TIMESTAMP NOT NULL, + observed_tenant_id VARCHAR(36) NOT NULL, + observed_publish_type VARCHAR(32) NOT NULL, + observed_participant_key VARCHAR(64) NOT NULL, + observed_base_version_id BIGINT, + observed_scope_value VARCHAR(128) NOT NULL, + observed_applied_commit_id VARCHAR(128) NOT NULL, + observed_content_digest VARCHAR(128) NOT NULL, + observed_digest_schema_version INT NOT NULL, + actor_identity VARCHAR(256) NOT NULL, + workload_identity VARCHAR(256) NOT NULL, + outcome VARCHAR(16) NOT NULL, + committed_at TIMESTAMP NOT NULL, + CONSTRAINT uq_entity_digest_baseline_migration_operation UNIQUE (operation_id), + CONSTRAINT uq_entity_digest_baseline_migration_baseline UNIQUE (recorded_participant_digest_id), + CONSTRAINT fk_entity_digest_baseline_migration_baseline + FOREIGN KEY (recorded_participant_digest_id) + REFERENCES publish_recorded_participant_digest(id) + ON DELETE RESTRICT, + CONSTRAINT chk_entity_digest_baseline_migration_source + CHECK ( + source_publish_type = 'FULL_VERSION' + AND source_participant_key = 'ENTITY_MANAGEMENT' + AND source_base_version_id IS NULL + AND source_digest_schema_version = 1 + ), + CONSTRAINT chk_entity_digest_baseline_migration_observed + CHECK ( + observed_publish_type = 'FULL_VERSION' + AND observed_participant_key = 'ENTITY_MANAGEMENT' + AND observed_base_version_id IS NULL + AND observed_digest_schema_version = 2 + AND observed_tenant_id = source_tenant_id + AND observed_scope_value = source_scope_value + ), + CONSTRAINT chk_entity_digest_baseline_migration_outcome + CHECK (outcome = 'COMMITTED') +); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java new file mode 100644 index 0000000000..e0d4ca5cc5 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java @@ -0,0 +1,423 @@ +package net.firedevops.firemud.gamedesign.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.client.EntityManagementClient; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.repository.EntityDigestBaselineMigrationAuditRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.BaselineSummary; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.ExpectedSource; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.MigrationCommand; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.MigrationDisposition; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.MigrationResult; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.ScopeStatus; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationWriteService; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof for Entity v1 baseline enumeration, guarded migration, audit, and readback. */ +@Testcontainers(disabledWithoutDocker = true) +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.NONE, + classes = GameDesignServiceApplication.class, + properties = { + "spring.profiles.active=test", + "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "firemud.grpc.plaintext=true", + "spring.grpc.server.port=0", + "asset.store.endpoint=http://localhost:9000", + "asset.store.bucket=test-bucket", + "asset.store.region=us-east-1", + "asset.store.access-key=test-access-key", + "asset.store.secret-key=test-secret-key" + }) +@Import(NoGrpcServerTestConfiguration.class) +class EntityDigestBaselineMigrationIntegrationTest { + private static final LocalDateTime SOURCE_RECORDED_AT = + LocalDateTime.of(2025, 1, 2, 3, 4, 5, 123_456_000); + private static final LocalDateTime SOURCE_LAST_VERIFIED_AT = + LocalDateTime.of(2025, 2, 3, 4, 5, 6, 234_567_000); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "game_design_service"); + } + + @Autowired private GameRepository gameRepository; + @Autowired private VersionRepository versionRepository; + @Autowired private RecordedParticipantDigestRepository baselineRepository; + @Autowired private EntityDigestBaselineMigrationAuditRepository auditRepository; + @Autowired private EntityDigestBaselineMigrationService migrationService; + @Autowired private EntityDigestBaselineMigrationWriteService writeService; + + @MockitoBean private EntityManagementClient entityManagementClient; + + @BeforeEach + void returnDeterministicEntityV2Evidence() { + when(entityManagementClient.getDraftDesignDigestForVersion(any())) + .thenAnswer( + invocation -> { + PublicationDigestRequestBinding binding = invocation.getArgument(0); + long versionId = Long.parseLong(binding.versionId()); + return new PublishParticipantDigestDto( + PublishParticipantKey.ENTITY_MANAGEMENT.name(), + binding.versionId(), + null, + "version:" + versionId, + v2Digest(versionId), + 2, + null, + null); + }); + } + + @Test + void enumeratesMixedRowsMigratesOnlyExactTenantVersionAndReadsBackAuditAndBaseline() { + createGame("9201"); + createGame("9202"); + Version targetVersion = createVersion("9201", 1); + Version siblingVersion = createVersion("9201", 2); + Version existingV2Version = createVersion("9201", 3); + Version noDataVersion = createVersion("9201", 4); + Version otherTenantVersion = createVersion("9202", 1); + + RecordedParticipantDigest target = seedEntityBaseline("9201", targetVersion, 1); + RecordedParticipantDigest sibling = seedEntityBaseline("9201", siblingVersion, 1); + RecordedParticipantDigest existingV2 = seedEntityBaseline("9201", existingV2Version, 2); + RecordedParticipantDigest otherTenant = seedEntityBaseline("9202", otherTenantVersion, 1); + RecordedParticipantDigest otherParticipant = + seedBaseline( + "9201", + targetVersion, + PublishParticipantKey.WORLD_MANAGEMENT, + 2, + "world-digest-" + targetVersion.getId()); + + EntityDigestBaselineMigrationService.EntityV1Batch batch = + migrationService.enumerateEntityV1Batch(target.getId() - 1, 50); + assertThat(batch.baselines()) + .extracting(BaselineSummary::baselineId) + .containsExactlyInAnyOrder(target.getId(), sibling.getId(), otherTenant.getId()); + assertThat(migrationService.preflightScope("9201", targetVersion.getId()).status()) + .isEqualTo(ScopeStatus.V1_REQUIRES_MIGRATION); + assertThat(migrationService.preflightScope("9201", noDataVersion.getId()).status()) + .isEqualTo(ScopeStatus.NO_RECORDED_BASELINE); + assertThat( + baselineRepository.findEntityFullVersionBaselinesByScope( + "9202", Long.toString(otherTenantVersion.getId()))) + .extracting(RecordedParticipantDigest::getId) + .containsExactly(otherTenant.getId()); + + MigrationCommand command = command("mixed-scope-operation", "9201", target); + MigrationResult result = migrationService.migrate(command); + + assertThat(result.disposition()).isEqualTo(MigrationDisposition.APPLIED); + assertThat(result.appliedCommitId()).isEqualTo(target.getAppliedCommitId()); + assertThat(result.digestSchemaVersion()).isEqualTo(2); + RecordedParticipantDigest migrated = baselineRepository.findById(target.getId()).orElseThrow(); + EntityDigestBaselineMigrationAudit audit = + auditRepository.findByOperationId(command.operationId()).orElseThrow(); + RecordedParticipantDigest expectedMigrated = + replacement(target, command.operationId(), v2Digest(targetVersion.getId())); + expectedMigrated.setRecordedAt(audit.committedAt()); + expectedMigrated.setLastVerifiedAt(audit.committedAt()); + assertThat(migrated).usingRecursiveComparison().isEqualTo(expectedMigrated); + EntityDigestBaselineMigrationAudit expectedAudit = + audit( + target, + migrated, + command.operationId(), + command.actorIdentity(), + command.workloadIdentity(), + audit.committedAt()); + assertThat(audit).usingRecursiveComparison().ignoringFields("id").isEqualTo(expectedAudit); + assertThat(migrated.getTenantId()).isEqualTo("9201"); + assertThat(migrated.getScopeValue()).isEqualTo(Long.toString(targetVersion.getId())); + assertThat(migrated.getAppliedCommitId()).isEqualTo("version:" + targetVersion.getId()); + assertThat(migrated.getContentDigest()).isEqualTo(v2Digest(targetVersion.getId())); + assertThat(migrated.getDigestSchemaVersion()).isEqualTo(2); + assertThat(migrated.getRecordedFromPublishWorkflowId()).isEqualTo(command.operationId()); + assertThat(migrated.getLastVerifiedPublishWorkflowId()).isEqualTo(command.operationId()); + assertThat(migrated.getRecordedAt()).isEqualTo(audit.committedAt()); + assertThat(migrated.getLastVerifiedAt()).isEqualTo(audit.committedAt()); + assertThat(audit.id()).isEqualTo(result.auditId()); + assertThat(audit.recordedParticipantDigestId()).isEqualTo(target.getId()); + assertThat(audit.sourceContentDigest()).isEqualTo(target.getContentDigest()); + assertThat(audit.sourceDigestSchemaVersion()).isEqualTo(1); + assertThat(audit.sourceRecordedFromPublishWorkflowId()) + .isEqualTo(target.getRecordedFromPublishWorkflowId()); + assertThat(audit.sourceRecordedAt()).isEqualTo(target.getRecordedAt()); + assertThat(audit.sourceLastVerifiedPublishWorkflowId()) + .isEqualTo(target.getLastVerifiedPublishWorkflowId()); + assertThat(audit.sourceLastVerifiedAt()).isEqualTo(target.getLastVerifiedAt()); + assertThat(audit.observedTenantId()).isEqualTo("9201"); + assertThat(audit.observedScopeValue()).isEqualTo(Long.toString(targetVersion.getId())); + assertThat(audit.observedContentDigest()).isEqualTo(v2Digest(targetVersion.getId())); + assertThat(audit.observedDigestSchemaVersion()).isEqualTo(2); + assertThat(audit.actorIdentity()).isEqualTo(command.actorIdentity()); + assertThat(audit.workloadIdentity()).isEqualTo(command.workloadIdentity()); + assertThat(audit.outcome()).isEqualTo(EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME); + + assertBaselineUnchanged(sibling); + assertBaselineUnchanged(otherTenant); + assertBaselineUnchanged(existingV2); + assertBaselineUnchanged(otherParticipant); + } + + @Test + void exactRetryReadsCommittedEvidenceWithoutCallingEntityAgain() { + createGame("9301"); + Version version = createVersion("9301", 1); + RecordedParticipantDigest source = seedEntityBaseline("9301", version, 1); + MigrationCommand command = command("retry-operation", "9301", source); + + MigrationResult first = migrationService.migrate(command); + MigrationResult retry = migrationService.migrate(command); + + assertThat(first.disposition()).isEqualTo(MigrationDisposition.APPLIED); + assertThat(retry.disposition()).isEqualTo(MigrationDisposition.EXACT_RETRY); + assertThat(retry.auditId()).isEqualTo(first.auditId()); + assertThat(retry.baselineId()).isEqualTo(first.baselineId()); + assertThat(retry.contentDigest()).isEqualTo(first.contentDigest()); + assertThat(retry.digestSchemaVersion()).isEqualTo(2); + verify(entityManagementClient, times(1)).getDraftDesignDigestForVersion(any()); + assertThat(auditRepository.findByOperationId(command.operationId())).isPresent(); + assertThat(baselineRepository.findById(source.getId()).orElseThrow().getContentDigest()) + .isEqualTo(v2Digest(version.getId())); + } + + @Test + void compareAndSwapRejectsAChangedV1SourceRow() { + createGame("9401"); + Version version = createVersion("9401", 1); + RecordedParticipantDigest source = seedEntityBaseline("9401", version, 1); + RecordedParticipantDigest expectedOld = + baselineRepository.findById(source.getId()).orElseThrow(); + RecordedParticipantDigest changed = baselineRepository.findById(source.getId()).orElseThrow(); + changed.setContentDigest("changed-after-preflight"); + baselineRepository.save(changed); + + RecordedParticipantDigest replacement = + replacement(expectedOld, "cas-test-operation", "v2-new"); + + assertThat( + baselineRepository.migrateEntityFullVersionBaselineIfUnchanged( + expectedOld, replacement)) + .isZero(); + RecordedParticipantDigest readback = baselineRepository.findById(source.getId()).orElseThrow(); + assertThat(readback.getDigestSchemaVersion()).isEqualTo(1); + assertThat(readback.getContentDigest()).isEqualTo("changed-after-preflight"); + assertThat(auditRepository.findByOperationId("cas-test-operation")).isEmpty(); + } + + @Test + void auditInsertFailureRollsBackTheGuardedBaselineReplacement() { + createGame("9501"); + Version firstVersion = createVersion("9501", 1); + Version secondVersion = createVersion("9501", 2); + RecordedParticipantDigest firstSource = seedEntityBaseline("9501", firstVersion, 1); + RecordedParticipantDigest secondSource = seedEntityBaseline("9501", secondVersion, 1); + + MigrationCommand firstCommand = command("duplicate-operation-id", "9501", firstSource); + MigrationResult firstResult = migrationService.migrate(firstCommand); + RecordedParticipantDigest expectedOld = + baselineRepository.findById(secondSource.getId()).orElseThrow(); + LocalDateTime migrationTime = LocalDateTime.now().truncatedTo(ChronoUnit.MICROS); + RecordedParticipantDigest replacement = + replacement(expectedOld, firstCommand.operationId(), v2Digest(secondVersion.getId())); + replacement.setRecordedAt(migrationTime); + replacement.setLastVerifiedAt(migrationTime); + EntityDigestBaselineMigrationAudit duplicateAudit = + audit( + expectedOld, + replacement, + firstCommand.operationId(), + firstCommand.actorIdentity(), + firstCommand.workloadIdentity(), + migrationTime); + + assertThatThrownBy(() -> writeService.commit(expectedOld, replacement, duplicateAudit)) + .isInstanceOf(RuntimeException.class); + + RecordedParticipantDigest readback = + baselineRepository.findById(secondSource.getId()).orElseThrow(); + assertThat(readback).usingRecursiveComparison().isEqualTo(secondSource); + assertThat(auditRepository.findByOperationId(firstCommand.operationId()).orElseThrow().id()) + .isEqualTo(firstResult.auditId()); + } + + private void createGame(String tenantId) { + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("entity-baseline-migration-" + tenantId); + gameRepository.save(game); + } + + private Version createVersion(String tenantId, int versionNumber) { + Version version = new Version(); + version.setTenantId(tenantId); + version.setVersionNumber(versionNumber); + version.setNotes("Entity baseline migration integration fixture"); + return versionRepository.save(version); + } + + private RecordedParticipantDigest seedEntityBaseline( + String tenantId, Version version, int digestSchemaVersion) { + return seedBaseline( + tenantId, + version, + PublishParticipantKey.ENTITY_MANAGEMENT, + digestSchemaVersion, + "entity-v" + digestSchemaVersion + "-" + version.getId()); + } + + private RecordedParticipantDigest seedBaseline( + String tenantId, + Version version, + PublishParticipantKey participantKey, + int digestSchemaVersion, + String contentDigest) { + RecordedParticipantDigest baseline = new RecordedParticipantDigest(); + baseline.setTenantId(tenantId); + baseline.setPublishType(PublishType.FULL_VERSION); + baseline.setParticipantKey(participantKey); + baseline.setScopeValue(Long.toString(version.getId())); + baseline.setBaseVersionId(null); + baseline.setAppliedCommitId("version:" + version.getId()); + baseline.setContentDigest(contentDigest); + baseline.setDigestSchemaVersion(digestSchemaVersion); + baseline.setRecordedFromPublishWorkflowId("initial-publish-" + version.getId()); + baseline.setRecordedAt(SOURCE_RECORDED_AT); + baseline.setLastVerifiedPublishWorkflowId("last-verified-" + version.getId()); + baseline.setLastVerifiedAt(SOURCE_LAST_VERIFIED_AT); + return baselineRepository.save(baseline); + } + + private MigrationCommand command( + String operationId, String tenantId, RecordedParticipantDigest source) { + return new MigrationCommand( + operationId, + source.getId(), + tenantId, + Long.parseLong(source.getScopeValue()), + expectedSource(source), + "operator:test-actor", + "spiffe://firemud/ns/dev/sa/game-design-baseline-migrator"); + } + + private ExpectedSource expectedSource(RecordedParticipantDigest source) { + return new ExpectedSource( + source.getId(), + source.getTenantId(), + source.getPublishType(), + source.getParticipantKey(), + source.getBaseVersionId(), + source.getScopeValue(), + source.getAppliedCommitId(), + source.getContentDigest(), + source.getDigestSchemaVersion(), + source.getRecordedFromPublishWorkflowId(), + source.getRecordedAt(), + source.getLastVerifiedPublishWorkflowId(), + source.getLastVerifiedAt()); + } + + private RecordedParticipantDigest replacement( + RecordedParticipantDigest source, String operationId, String contentDigest) { + RecordedParticipantDigest replacement = new RecordedParticipantDigest(); + replacement.setId(source.getId()); + replacement.setTenantId(source.getTenantId()); + replacement.setPublishType(source.getPublishType()); + replacement.setParticipantKey(source.getParticipantKey()); + replacement.setBaseVersionId(null); + replacement.setScopeValue(source.getScopeValue()); + replacement.setAppliedCommitId(source.getAppliedCommitId()); + replacement.setContentDigest(contentDigest); + replacement.setDigestSchemaVersion(2); + replacement.setRecordedFromPublishWorkflowId(operationId); + replacement.setRecordedAt(LocalDateTime.now().truncatedTo(ChronoUnit.MICROS)); + replacement.setLastVerifiedPublishWorkflowId(operationId); + replacement.setLastVerifiedAt(replacement.getRecordedAt()); + return replacement; + } + + private EntityDigestBaselineMigrationAudit audit( + RecordedParticipantDigest source, + RecordedParticipantDigest target, + String operationId, + String actorIdentity, + String workloadIdentity, + LocalDateTime committedAt) { + return new EntityDigestBaselineMigrationAudit( + null, + operationId, + source.getId(), + source.getTenantId(), + source.getPublishType(), + source.getParticipantKey(), + source.getBaseVersionId(), + source.getScopeValue(), + source.getAppliedCommitId(), + source.getContentDigest(), + source.getDigestSchemaVersion(), + source.getRecordedFromPublishWorkflowId(), + source.getRecordedAt(), + source.getLastVerifiedPublishWorkflowId(), + source.getLastVerifiedAt(), + target.getTenantId(), + target.getPublishType(), + target.getParticipantKey(), + target.getBaseVersionId(), + target.getScopeValue(), + target.getAppliedCommitId(), + target.getContentDigest(), + target.getDigestSchemaVersion(), + actorIdentity, + workloadIdentity, + EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME, + committedAt); + } + + private void assertBaselineUnchanged(RecordedParticipantDigest expected) { + RecordedParticipantDigest actual = baselineRepository.findById(expected.getId()).orElseThrow(); + assertThat(actual).usingRecursiveComparison().isEqualTo(expected); + } + + private String v2Digest(long versionId) { + return "entity-v2-observed-" + versionId; + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java new file mode 100644 index 0000000000..b20e14109d --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java @@ -0,0 +1,60 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; + +class EntityDigestBaselineMigrationJobRunnerTest { + private static final GrpcPeerIdentity MIGRATOR = + new GrpcPeerIdentity( + "spiffe://firemud/ns/dev/sa/game-design-baseline-migrator", + "dev", + "game-design-baseline-migrator"); + + @Test + void acceptsOnlyExactDedicatedIdentityAndTargetEnvironment() { + assertThatCode( + () -> + EntityDigestBaselineMigrationJobRunner.requireJobAuthority( + "dev", "dev", "game-design-baseline-migrator", MIGRATOR)) + .doesNotThrowAnyException(); + } + + @Test + void rejectsWrongTargetServiceAccountAndCertificateIdentity() { + assertThatThrownBy( + () -> + EntityDigestBaselineMigrationJobRunner.requireJobAuthority( + "dev", "pr-12", "game-design-baseline-migrator", MIGRATOR)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + EntityDigestBaselineMigrationJobRunner.requireJobAuthority( + "dev", "dev", "firemud-app", MIGRATOR)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + EntityDigestBaselineMigrationJobRunner.requireJobAuthority( + "dev", + "dev", + "game-design-baseline-migrator", + new GrpcPeerIdentity( + "spiffe://firemud/ns/dev/sa/game-design-service", + "dev", + "game-design-service"))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + EntityDigestBaselineMigrationJobRunner.requireJobAuthority( + "dev", + "dev", + "game-design-baseline-migrator", + new GrpcPeerIdentity( + "spiffe://firemud/ns/pr-12/sa/game-design-baseline-migrator", + "pr-12", + "game-design-baseline-migrator"))) + .isInstanceOf(IllegalStateException.class); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java new file mode 100644 index 0000000000..41dec203cb --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java @@ -0,0 +1,551 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.gamedesign.client.EntityManagementClient; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; +import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.EntityDigestBaselineMigrationAuditRepository; +import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class EntityDigestBaselineMigrationServiceTest { + private static final long BASELINE_ID = 91L; + private static final long VERSION_ID = 42L; + private static final long AUDIT_ID = 701L; + private static final String OPERATION_ID = "migration-op-42"; + private static final String TENANT_ID = "tenant-7"; + private static final LocalDateTime SOURCE_RECORDED_AT = + LocalDateTime.parse("2026-09-20T12:30:00.123456"); + private static final LocalDateTime SOURCE_VERIFIED_AT = + LocalDateTime.parse("2026-09-21T12:30:00.654321"); + + @Mock private RecordedParticipantDigestRepository baselineRepository; + @Mock private EntityDigestBaselineMigrationAuditRepository auditRepository; + @Mock private VersionRepository versionRepository; + @Mock private EntityManagementClient entityManagementClient; + + private RecordedParticipantDigest source; + private EntityDigestBaselineMigrationService.ExpectedSource expectedSource; + private EntityDigestBaselineMigrationService.MigrationCommand command; + + @BeforeEach + void setUp() { + source = sourceBaseline(); + expectedSource = expectedSource(source); + command = command(expectedSource); + } + + @Test + void preflightDistinguishesNoBaselineV2AndMissingVersion() { + EntityDigestBaselineMigrationService service = serviceWithMockWriter(); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(), List.of(v2Baseline())); + + assertEquals( + EntityDigestBaselineMigrationService.ScopeStatus.NO_RECORDED_BASELINE, + service.preflightScope(TENANT_ID, VERSION_ID).status()); + assertEquals( + EntityDigestBaselineMigrationService.ScopeStatus.V2_ALREADY_RECORDED, + service.preflightScope(TENANT_ID, VERSION_ID).status()); + + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)).thenReturn(Optional.empty()); + EntityDigestBaselineMigrationService.MigrationRejectedException missingVersion = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> service.preflightScope(TENANT_ID, VERSION_ID)); + assertEquals("VERSION_MISSING", missingVersion.failureCode()); + } + + @Test + void preflightClassifiesRetainedEntityV1Row() { + EntityDigestBaselineMigrationService service = serviceWithMockWriter(); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(source)); + + EntityDigestBaselineMigrationService.ScopePreflight result = + service.preflightScope(TENANT_ID, VERSION_ID); + + assertEquals( + EntityDigestBaselineMigrationService.ScopeStatus.V1_REQUIRES_MIGRATION, result.status()); + assertEquals(BASELINE_ID, result.baselines().get(0).baselineId()); + assertEquals("version:42", result.baselines().get(0).appliedCommitId()); + } + + @Test + void preflightReportsAmbiguousScopeInsteadOfSelectingARow() { + EntityDigestBaselineMigrationService service = serviceWithMockWriter(); + RecordedParticipantDigest duplicate = sourceBaseline(); + duplicate.setId(BASELINE_ID + 1); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(source, duplicate)); + + EntityDigestBaselineMigrationService.ScopePreflight result = + service.preflightScope(TENANT_ID, VERSION_ID); + + assertEquals( + EntityDigestBaselineMigrationService.ScopeStatus.AMBIGUOUS_BASELINE, result.status()); + assertEquals(2, result.baselines().size()); + } + + @Test + void enumerationReturnsBoundedCursorPageWithExactScopeIdentities() { + EntityDigestBaselineMigrationService service = serviceWithMockWriter(); + when(baselineRepository.findEntityV1FullVersionBatchAfterId(10L, 25)) + .thenReturn(List.of(source)); + + EntityDigestBaselineMigrationService.EntityV1Batch page = + service.enumerateEntityV1Batch(10L, 25); + + assertEquals(10L, page.scannedAfterBaselineId()); + assertEquals(25, page.limit()); + assertEquals(BASELINE_ID, page.nextAfterBaselineId()); + assertEquals(TENANT_ID, page.baselines().get(0).tenantId()); + assertEquals(VERSION_ID, page.baselines().get(0).versionId()); + assertFalse(page.isEmptyAtCursor()); + } + + @Test + void migrationCommitsAndProvesExactV2BaselineAndAuditReadback() { + AtomicReference persistedBaseline = new AtomicReference<>(source); + AtomicReference persistedAudit = new AtomicReference<>(); + EntityDigestBaselineMigrationWriteService writer = + new EntityDigestBaselineMigrationWriteService(baselineRepository, auditRepository); + EntityDigestBaselineMigrationService service = + new EntityDigestBaselineMigrationService( + baselineRepository, auditRepository, versionRepository, entityManagementClient, writer); + stubInitialMigrationReads(persistedBaseline, persistedAudit); + when(entityManagementClient.getDraftDesignDigestForVersion(any())) + .thenReturn(v2Digest("v2-content", "version:42")); + when(baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(any(), any())) + .thenAnswer( + invocation -> { + RecordedParticipantDigest expected = invocation.getArgument(0); + if (!sameSource(persistedBaseline.get(), expected)) { + return 0; + } + persistedBaseline.set(invocation.getArgument(1)); + return 1; + }); + when(auditRepository.insert(any())) + .thenAnswer( + invocation -> { + EntityDigestBaselineMigrationAudit inserted = invocation.getArgument(0); + EntityDigestBaselineMigrationAudit stored = withId(inserted, AUDIT_ID); + persistedAudit.set(stored); + return stored; + }); + + EntityDigestBaselineMigrationService.MigrationResult result = service.migrate(command); + + assertEquals( + EntityDigestBaselineMigrationService.MigrationDisposition.APPLIED, result.disposition()); + assertEquals(AUDIT_ID, result.auditId()); + assertEquals(BASELINE_ID, result.baselineId()); + assertEquals("version:42", result.appliedCommitId()); + assertEquals("v2-content", result.contentDigest()); + assertEquals(2, result.digestSchemaVersion()); + assertEquals(OPERATION_ID, persistedBaseline.get().getRecordedFromPublishWorkflowId()); + assertEquals(OPERATION_ID, persistedBaseline.get().getLastVerifiedPublishWorkflowId()); + assertEquals(source.getContentDigest(), persistedAudit.get().sourceContentDigest()); + assertEquals("v2-content", persistedAudit.get().observedContentDigest()); + } + + @Test + void exactRetryReturnsOnlyAfterBaselineAndAuditReadbackWithoutRecomputing() { + RecordedParticipantDigest migrated = migratedBaseline("v2-content", "version:42", auditTime()); + EntityDigestBaselineMigrationAudit audit = audit(source, migrated, AUDIT_ID, auditTime()); + when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.of(audit)); + when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(migrated)); + + EntityDigestBaselineMigrationService.MigrationResult result = + serviceWithMockWriter().migrate(command); + + assertEquals( + EntityDigestBaselineMigrationService.MigrationDisposition.EXACT_RETRY, + result.disposition()); + assertEquals("v2-content", result.contentDigest()); + verify(entityManagementClient, never()).getDraftDesignDigestForVersion(any()); + verify(versionRepository, never()).findByTenantIdAndId(any(), any()); + } + + @Test + void operationIdReuseWithDifferentSourceIsRejected() { + EntityDigestBaselineMigrationAudit conflicting = + audit( + source, + migratedBaseline("v2-content", "version:42", auditTime()), + AUDIT_ID, + auditTime()); + conflicting = withSourceContentDigest(conflicting, "different-v1-digest"); + when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.of(conflicting)); + + EntityDigestBaselineMigrationService.MigrationRejectedException rejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> serviceWithMockWriter().migrate(command)); + + assertEquals("OPERATION_ID_CONFLICT", rejected.failureCode()); + verify(baselineRepository, never()).findById(BASELINE_ID); + verify(entityManagementClient, never()).getDraftDesignDigestForVersion(any()); + } + + @Test + void changedOldTupleIsRejectedBeforeEntityRecomputation() { + RecordedParticipantDigest changed = sourceBaseline(); + changed.setLastVerifiedAt(SOURCE_VERIFIED_AT.plusSeconds(1)); + when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.empty()); + when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(changed)); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(changed)); + + EntityDigestBaselineMigrationService.MigrationRejectedException rejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> serviceWithMockWriter().migrate(command)); + + assertEquals("SOURCE_BASELINE_CHANGED", rejected.failureCode()); + verify(entityManagementClient, never()).getDraftDesignDigestForVersion(any()); + } + + @Test + void wrongTenantBaselineIsRejectedBeforeScopeOrEntityRead() { + RecordedParticipantDigest wrongTenant = sourceBaseline(); + wrongTenant.setTenantId("tenant-other"); + when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.empty()); + when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(wrongTenant)); + + EntityDigestBaselineMigrationService.MigrationRejectedException rejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> serviceWithMockWriter().migrate(command)); + + assertEquals("BASELINE_TENANT_MISMATCH", rejected.failureCode()); + verify(entityManagementClient, never()).getDraftDesignDigestForVersion(any()); + } + + @Test + void schemaOneSourceCannotBeSilentlyReplacedWhenEntityCommitIdentityChanges() { + when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.empty()); + when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(source)); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(source)); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + when(entityManagementClient.getDraftDesignDigestForVersion(any())) + .thenReturn(v2Digest("v2-content", "version:43")); + + EntityDigestBaselineMigrationService.MigrationRejectedException rejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> serviceWithMockWriter().migrate(command)); + + assertEquals("ENTITY_APPLIED_COMMIT_MISMATCH", rejected.failureCode()); + } + + @Test + void uncertainWriterOutcomeSucceedsOnlyWhenExactCommittedReadbackIsFound() { + AtomicReference persistedBaseline = new AtomicReference<>(source); + AtomicReference persistedAudit = new AtomicReference<>(); + EntityDigestBaselineMigrationWriteService writer = + org.mockito.Mockito.mock(EntityDigestBaselineMigrationWriteService.class); + org.mockito.Mockito.doAnswer( + invocation -> { + persistedBaseline.set(invocation.getArgument(1)); + persistedAudit.set(withId(invocation.getArgument(2), AUDIT_ID)); + throw new IllegalStateException("connection lost after commit"); + }) + .when(writer) + .commit(any(), any(), any()); + when(auditRepository.findByOperationId(OPERATION_ID)) + .thenAnswer(invocation -> Optional.ofNullable(persistedAudit.get())); + when(baselineRepository.findById(BASELINE_ID)) + .thenAnswer(invocation -> Optional.ofNullable(persistedBaseline.get())); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(source)); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + when(entityManagementClient.getDraftDesignDigestForVersion(any())) + .thenReturn(v2Digest("v2-content", "version:42")); + + EntityDigestBaselineMigrationService.MigrationResult result = service(writer).migrate(command); + + assertEquals( + EntityDigestBaselineMigrationService.MigrationDisposition.RECOVERED_AFTER_WRITE_ERROR, + result.disposition()); + assertEquals(AUDIT_ID, result.auditId()); + } + + @Test + void uncertainWriterOutcomeFailsWhenReadbackCannotProveBothRows() { + EntityDigestBaselineMigrationWriteService writer = + org.mockito.Mockito.mock(EntityDigestBaselineMigrationWriteService.class); + doThrow(new IllegalStateException("commit acknowledgement lost")) + .when(writer) + .commit(any(), any(), any()); + when(auditRepository.findByOperationId(OPERATION_ID)) + .thenReturn(Optional.empty(), Optional.empty()); + when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(source)); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(source)); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + when(entityManagementClient.getDraftDesignDigestForVersion(any())) + .thenReturn(v2Digest("v2-content", "version:42")); + + EntityDigestBaselineMigrationService.MigrationRejectedException rejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> service(writer).migrate(command)); + + assertEquals("WRITE_OUTCOME_UNPROVEN", rejected.failureCode()); + assertTrue(rejected.getCause().getSuppressed().length > 0); + } + + private EntityDigestBaselineMigrationService serviceWithMockWriter() { + return service(org.mockito.Mockito.mock(EntityDigestBaselineMigrationWriteService.class)); + } + + private EntityDigestBaselineMigrationService service( + EntityDigestBaselineMigrationWriteService writer) { + return new EntityDigestBaselineMigrationService( + baselineRepository, auditRepository, versionRepository, entityManagementClient, writer); + } + + private void stubInitialMigrationReads( + AtomicReference persistedBaseline, + AtomicReference persistedAudit) { + when(auditRepository.findByOperationId(OPERATION_ID)) + .thenAnswer(invocation -> Optional.ofNullable(persistedAudit.get())); + when(baselineRepository.findById(BASELINE_ID)) + .thenAnswer(invocation -> Optional.ofNullable(persistedBaseline.get())); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenAnswer(invocation -> List.of(persistedBaseline.get())); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + } + + private boolean sameSource( + RecordedParticipantDigest current, RecordedParticipantDigest expected) { + return current != null + && current.getId().equals(expected.getId()) + && current.getAppliedCommitId().equals(expected.getAppliedCommitId()) + && current.getContentDigest().equals(expected.getContentDigest()) + && current.getDigestSchemaVersion().equals(expected.getDigestSchemaVersion()) + && current.getLastVerifiedAt().equals(expected.getLastVerifiedAt()); + } + + private RecordedParticipantDigest sourceBaseline() { + RecordedParticipantDigest baseline = new RecordedParticipantDigest(); + baseline.setId(BASELINE_ID); + baseline.setTenantId(TENANT_ID); + baseline.setPublishType(PublishType.FULL_VERSION); + baseline.setParticipantKey(PublishParticipantKey.ENTITY_MANAGEMENT); + baseline.setScopeValue(Long.toString(VERSION_ID)); + baseline.setBaseVersionId(null); + baseline.setAppliedCommitId("version:42"); + baseline.setContentDigest("v1-content"); + baseline.setDigestSchemaVersion(1); + baseline.setRecordedFromPublishWorkflowId("publish:tenant-7:old-request"); + baseline.setRecordedAt(SOURCE_RECORDED_AT); + baseline.setLastVerifiedPublishWorkflowId("publish:tenant-7:old-verification"); + baseline.setLastVerifiedAt(SOURCE_VERIFIED_AT); + return baseline; + } + + private EntityDigestBaselineMigrationService.ExpectedSource expectedSource( + RecordedParticipantDigest baseline) { + return new EntityDigestBaselineMigrationService.ExpectedSource( + baseline.getId(), + baseline.getTenantId(), + baseline.getPublishType(), + baseline.getParticipantKey(), + baseline.getBaseVersionId(), + baseline.getScopeValue(), + baseline.getAppliedCommitId(), + baseline.getContentDigest(), + baseline.getDigestSchemaVersion(), + baseline.getRecordedFromPublishWorkflowId(), + baseline.getRecordedAt(), + baseline.getLastVerifiedPublishWorkflowId(), + baseline.getLastVerifiedAt()); + } + + private EntityDigestBaselineMigrationService.MigrationCommand command( + EntityDigestBaselineMigrationService.ExpectedSource expected) { + return new EntityDigestBaselineMigrationService.MigrationCommand( + OPERATION_ID, + BASELINE_ID, + TENANT_ID, + VERSION_ID, + expected, + "operator:reviewer-1", + "job:entity-baseline"); + } + + private Version version() { + Version version = new Version(); + version.setId(VERSION_ID); + version.setTenantId(TENANT_ID); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setScriptOnly(false); + return version; + } + + private RecordedParticipantDigest v2Baseline() { + RecordedParticipantDigest baseline = sourceBaseline(); + baseline.setDigestSchemaVersion(2); + baseline.setContentDigest("already-v2"); + return baseline; + } + + private PublishParticipantDigestDto v2Digest(String digest, String appliedCommitId) { + return new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", "42", null, appliedCommitId, digest, 2, null, null); + } + + private RecordedParticipantDigest migratedBaseline( + String digest, String appliedCommitId, LocalDateTime committedAt) { + RecordedParticipantDigest baseline = sourceBaseline(); + baseline.setAppliedCommitId(appliedCommitId); + baseline.setContentDigest(digest); + baseline.setDigestSchemaVersion(2); + baseline.setRecordedFromPublishWorkflowId(OPERATION_ID); + baseline.setRecordedAt(committedAt); + baseline.setLastVerifiedPublishWorkflowId(OPERATION_ID); + baseline.setLastVerifiedAt(committedAt); + return baseline; + } + + private EntityDigestBaselineMigrationAudit audit( + RecordedParticipantDigest oldBaseline, + RecordedParticipantDigest target, + Long auditId, + LocalDateTime committedAt) { + return new EntityDigestBaselineMigrationAudit( + auditId, + OPERATION_ID, + BASELINE_ID, + oldBaseline.getTenantId(), + oldBaseline.getPublishType(), + oldBaseline.getParticipantKey(), + oldBaseline.getBaseVersionId(), + oldBaseline.getScopeValue(), + oldBaseline.getAppliedCommitId(), + oldBaseline.getContentDigest(), + oldBaseline.getDigestSchemaVersion(), + oldBaseline.getRecordedFromPublishWorkflowId(), + oldBaseline.getRecordedAt(), + oldBaseline.getLastVerifiedPublishWorkflowId(), + oldBaseline.getLastVerifiedAt(), + target.getTenantId(), + target.getPublishType(), + target.getParticipantKey(), + target.getBaseVersionId(), + target.getScopeValue(), + target.getAppliedCommitId(), + target.getContentDigest(), + target.getDigestSchemaVersion(), + "operator:reviewer-1", + "job:entity-baseline", + EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME, + committedAt); + } + + private EntityDigestBaselineMigrationAudit withId( + EntityDigestBaselineMigrationAudit audit, Long id) { + return new EntityDigestBaselineMigrationAudit( + id, + audit.operationId(), + audit.recordedParticipantDigestId(), + audit.sourceTenantId(), + audit.sourcePublishType(), + audit.sourceParticipantKey(), + audit.sourceBaseVersionId(), + audit.sourceScopeValue(), + audit.sourceAppliedCommitId(), + audit.sourceContentDigest(), + audit.sourceDigestSchemaVersion(), + audit.sourceRecordedFromPublishWorkflowId(), + audit.sourceRecordedAt(), + audit.sourceLastVerifiedPublishWorkflowId(), + audit.sourceLastVerifiedAt(), + audit.observedTenantId(), + audit.observedPublishType(), + audit.observedParticipantKey(), + audit.observedBaseVersionId(), + audit.observedScopeValue(), + audit.observedAppliedCommitId(), + audit.observedContentDigest(), + audit.observedDigestSchemaVersion(), + audit.actorIdentity(), + audit.workloadIdentity(), + audit.outcome(), + audit.committedAt()); + } + + private EntityDigestBaselineMigrationAudit withSourceContentDigest( + EntityDigestBaselineMigrationAudit audit, String contentDigest) { + return new EntityDigestBaselineMigrationAudit( + audit.id(), + audit.operationId(), + audit.recordedParticipantDigestId(), + audit.sourceTenantId(), + audit.sourcePublishType(), + audit.sourceParticipantKey(), + audit.sourceBaseVersionId(), + audit.sourceScopeValue(), + audit.sourceAppliedCommitId(), + contentDigest, + audit.sourceDigestSchemaVersion(), + audit.sourceRecordedFromPublishWorkflowId(), + audit.sourceRecordedAt(), + audit.sourceLastVerifiedPublishWorkflowId(), + audit.sourceLastVerifiedAt(), + audit.observedTenantId(), + audit.observedPublishType(), + audit.observedParticipantKey(), + audit.observedBaseVersionId(), + audit.observedScopeValue(), + audit.observedAppliedCommitId(), + audit.observedContentDigest(), + audit.observedDigestSchemaVersion(), + audit.actorIdentity(), + audit.workloadIdentity(), + audit.outcome(), + audit.committedAt()); + } + + private LocalDateTime auditTime() { + return LocalDateTime.parse("2026-09-26T01:02:03.123456"); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java new file mode 100644 index 0000000000..1dec9ff473 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java @@ -0,0 +1,111 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.LocalDateTime; +import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; +import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.repository.EntityDigestBaselineMigrationAuditRepository; +import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class EntityDigestBaselineMigrationWriteServiceTest { + @Mock private RecordedParticipantDigestRepository baselineRepository; + @Mock private EntityDigestBaselineMigrationAuditRepository auditRepository; + + private EntityDigestBaselineMigrationWriteService service; + private RecordedParticipantDigest source; + private RecordedParticipantDigest replacement; + private EntityDigestBaselineMigrationAudit audit; + + @BeforeEach + void setUp() { + service = new EntityDigestBaselineMigrationWriteService(baselineRepository, auditRepository); + LocalDateTime time = LocalDateTime.parse("2026-09-26T01:02:03.123456"); + source = baseline(1, "old", time.minusDays(1), "publish:old", "verify:old"); + replacement = baseline(2, "new", time, "migration-op", "migration-op"); + audit = audit(time); + } + + @Test + void compareAndSetAndAuditAreBothRequiredForCommit() { + when(baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(source, replacement)) + .thenReturn(1); + + service.commit(source, replacement, audit); + + verify(baselineRepository).migrateEntityFullVersionBaselineIfUnchanged(source, replacement); + verify(auditRepository).insert(audit); + } + + @Test + void changedRowPreventsAuditInsert() { + when(baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(source, replacement)) + .thenReturn(0); + + assertThrows(IllegalStateException.class, () -> service.commit(source, replacement, audit)); + + verify(auditRepository, never()).insert(any()); + } + + private RecordedParticipantDigest baseline( + int schema, String digest, LocalDateTime time, String recordedFrom, String lastVerified) { + RecordedParticipantDigest baseline = new RecordedParticipantDigest(); + baseline.setId(91L); + baseline.setTenantId("tenant-7"); + baseline.setPublishType(PublishType.FULL_VERSION); + baseline.setParticipantKey(PublishParticipantKey.ENTITY_MANAGEMENT); + baseline.setScopeValue("42"); + baseline.setBaseVersionId(null); + baseline.setAppliedCommitId("version:42"); + baseline.setContentDigest(digest); + baseline.setDigestSchemaVersion(schema); + baseline.setRecordedFromPublishWorkflowId(recordedFrom); + baseline.setRecordedAt(time); + baseline.setLastVerifiedPublishWorkflowId(lastVerified); + baseline.setLastVerifiedAt(time); + return baseline; + } + + private EntityDigestBaselineMigrationAudit audit(LocalDateTime time) { + return new EntityDigestBaselineMigrationAudit( + null, + "migration-op", + 91L, + "tenant-7", + PublishType.FULL_VERSION, + PublishParticipantKey.ENTITY_MANAGEMENT, + null, + "42", + "version:42", + "old", + 1, + "publish:old", + time.minusDays(1), + "verify:old", + time.minusDays(1), + "tenant-7", + PublishType.FULL_VERSION, + PublishParticipantKey.ENTITY_MANAGEMENT, + null, + "42", + "version:42", + "new", + 2, + "operator:reviewer-1", + "job:entity-baseline", + EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME, + time); + } +} From 9b14a49cb6975e5342bcb14e7a006490cb7470b4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 14:51:09 +1200 Subject: [PATCH 03/28] Fence the baseline migrator certificate and admission --- .../game-design-service/operations.md | 4 +- design/project-management/ai-observations.md | 5 + ...nsure-standalone-transport-certificates.sh | 129 +++++++++++++++++- ...d-identity-controller-manifest-contract.sh | 25 ++++ ...ndalone-transport-certificates-contract.sh | 121 ++++++++++++++++ .../trust-bootstrap-issuance-contract.sh | 6 +- k8s/hosted-identity-controller/admission.yaml | 51 ++++++- k8s/trust-bootstrap/issuance-admission.yaml | 42 ++++-- ...ntityDigestBaselineMigrationJobRunner.java | 4 + .../EntityDigestBaselineMigrationService.java | 4 + ...tyDigestBaselineMigrationWriteService.java | 4 + 11 files changed, 373 insertions(+), 22 deletions(-) diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 970db559bf..207ac895a3 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -34,12 +34,12 @@ The target publication boundary treats object-store export as a durable candidat Use a controlled pre-v1 publication window for the affected Entity v1 full-version scopes. Drain in-flight publication and prevent new publication on those scopes before comparing rows or deploying the writer. Deploy the migration-capable Game Design reader/reconciler image first so retained stored v1 and v2 baseline shapes can be inspected; its publish gate still requires v2 and never compares v1 content with v2 content. Then deploy Entity's v2 producer image. Because #2872 already has a v2-only gate, deploying it alone may temporarily block affected v1 publication; this is an accepted fail-closed maintenance window, not seamless dual-reader availability. Verify actual service image digests and deployment order before proceeding; if the image topology cannot maintain that sequence, stop instead of relaxing the gate. The current Entity applied-commit token is synthetic `version:` and does not prove durable applied-revision convergence. -Before invoking a Job, verify the exact Kubernetes context and namespace, the authorized operator identity and approved maintenance window, both current service image digests, database backup/recovery posture, completed in-flight publication drain, and the dedicated migrator certificate's issuer, `Ready` state, URI SAN, trust chain, projected Secret, and actual mTLS acceptance at Entity. The hosted trust/controller admission policy must include this narrowly named identity before requesting the leaf; a rendered Certificate or Secret name alone is not issuance or served-identity proof. The trusted operator must create an immutable expected-source ConfigMap or Secret from a read-only exact database row, including baseline ID, tenant, `FULL_VERSION`, `ENTITY_MANAGEMENT`, null base version, version scope, applied commit, digest, schema `1`, and both workflow IDs and timestamps. Do not place this manifest, credentials, or raw retained row values in a PR or CI artifact. Check that the source object is immutable before applying the Job. The Job's `targetNamespace`, tenant/version, operation ID, actor identity, and expected-source object are all fixed for that invocation; a changed command gets a new operation ID, never a reinterpretation of the old one. +Before invoking a Job, verify the exact Kubernetes context and namespace, the authorized operator identity and approved maintenance window, both current service image digests, database backup/recovery posture, completed in-flight publication drain, and the dedicated migrator certificate's issuer, `Ready` state, URI SAN, trust chain, projected Secret, and actual mTLS acceptance at Entity. The hosted trust/controller admission policy includes a narrow runtime-namespace exception for this identity; it does not make the migrator one of the controller's permanent certificate consumers. A trusted certificate writer must explicitly invoke `ensure-standalone-transport-certificates.sh --migrator `; a separately authorized Secret-read operator then invokes `--verify-migrator ` before the Job is enabled. The certificate writer's service account has no Secret-read permission. These opt-in operations do not alter ordinary preview transport-certificate rollout. A rendered Certificate or Secret name alone is not issuance or served-identity proof. The trusted operator must create an immutable expected-source ConfigMap or Secret from a read-only exact database row, including baseline ID, tenant, `FULL_VERSION`, `ENTITY_MANAGEMENT`, null base version, version scope, applied commit, digest, schema `1`, and both workflow IDs and timestamps. Do not place this manifest, credentials, or raw retained row values in a PR or CI artifact. Check that the source object is immutable before applying the Job. The Job's `targetNamespace`, tenant/version, operation ID, actor identity, and expected-source object are all fixed for that invocation; a changed command gets a new operation ID, never a reinterpretation of the old one. The chart's `previewStack.entityDigestBaselineMigration` values are disabled by default. From the trusted operator revision, supply an image pinned as `repository@sha256:`, exact `targetNamespace`, the dedicated `firemud-grpc-game-design-baseline-migrator` Secret, and `mode`. `enumerate` returns at most 500 Entity schema-v1 full-version rows after one baseline ID; repeat with its returned keyset cursor until an empty page proves no more rows at the quiesced snapshot. `preflight` classifies one exact tenant/version as v1, v2, absent, ambiguous, or unsupported, and refuses a missing or script-only Version. `migrate` requires one stable operation ID, exact tenant/version, actor identity, and the immutable expected-source object. The Java runner verifies its namespace, dedicated service account, and certificate URI identity before reading or writing. A missing identity, policy, input, row, version, exact-old match, or v2 Entity response fails closed. Render and inspect the operator overlay before installation; do not leave `enabled: true` in the ordinary chart values or an unattended release upgrade. Completed Jobs are deliberately not Helm hooks, so an unchanged upgrade does not rerun them; a changed immutable Job spec is rejected and needs an explicit trusted disposition. For each affected scope, retain the preflight row ID and complete source tuple privately, run `migrate`, and require its reported operation/audit/baseline IDs and disposition. The Game Design transaction conditionally replaces the exact old row and inserts an immutable before/after audit atomically. An exact retry of the same operation reads the existing audit and baseline rather than writing again; a lost acknowledgement is resolved by that same operation identity and exact readback. A changed source, ambiguous scope, different actor/workload binding, mismatched Entity v2 schema/scope/digest/commit, or unproved write outcome is a stop condition. Independently read back `publish_recorded_participant_digest` by baseline ID and `entity_digest_baseline_migration_audit` by operation ID from Game Design's PostgreSQL schema; compare the new schema/digest/commit/provenance, complete old tuple, observed v2 tuple, operation, actor/workload, outcome, and timestamp exactly. Never count Job completion alone as database proof. Keep the before/after records with the private migration log, excluding secrets and certificate keys. -If no retained Entity v1 rows exist, record the exact namespace, database/schema, query time, quiescence evidence, and an empty bounded enumeration through its terminal page; separately preflight every affected known tenant/version scope and record its state. This is a no-data boundary, not a claim that migration ran. If a migration fails or proof is incomplete, leave affected publication closed and retain the old row/audit evidence; do not restore a v1 hash over an audited v2 row or weaken the v2 publish gate. Resume only after an exact retry/readback or an explicit database recovery decision with equivalent provenance. Reopen publication only after every enumerated v1 row has a verified v2 baseline and audit (or the scoped no-data proof), the Entity v2 producer and Game Design reader remain healthy, and the normal v2 publish gate succeeds. Live retained data, PostgreSQL readback, certificate bootstrap, and served mTLS proof must be reported separately from local fixtures and static Helm renders. +If no retained Entity v1 rows exist, record the exact namespace, database/schema, query time, quiescence evidence, and an empty bounded enumeration through its terminal page; separately preflight every affected known tenant/version scope and record its state. This is a no-data boundary, not a claim that migration ran. If a migration fails or proof is incomplete, leave affected publication closed and retain the old row/audit evidence; do not restore a v1 hash over an audited v2 row or weaken the v2 publish gate. Resume only after an exact retry/readback or an explicit database recovery decision with equivalent provenance. Reopen publication only after every enumerated v1 row has a verified v2 baseline and audit (or the scoped no-data proof), the Entity v2 producer and Game Design reader remain healthy, and the normal v2 publish gate succeeds. After the approved work and readback are complete, disable the Helm migration Job and have an authorized `system:masters` operator explicitly retire its exact dedicated Certificate and Secret; the scoped writer cannot delete them. Retain the database audit and private operation evidence. Do not leave the one-shot workload identity provisioned as an ordinary Game Design credential. Live retained data, PostgreSQL readback, certificate bootstrap, served mTLS, and identity retirement proof must be reported separately from local fixtures and static Helm renders. `TestDataSeeder` populates a demo game, template, revision and version only when explicit smoke/runtime seeding is enabled through deployment config (`FIREMUD_SMOKE_SEED_DEMO_RUNTIME_ENABLED=true` in the local Compose smoke stack). Run `services/game-design-service/smoke-test.sh` to verify both REST and gRPC endpoints. The lightweight maintained application smoke now lives under `src/test/java/integration`; the old disabled GHCR-based cross-service placeholder was removed because it did not prove a meaningful current contract. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8320c31b83..0a3999801b 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -99,3 +99,8 @@ Entry format: - Context: a Game Session correction rejected unowned or ambiguous `PLAY` actors, while a shared Docker-backed WebSocket integration fixture still returned actor rows with protobuf-default playable scope. - Observation: local integration tests skipped without Docker, but CI executed them and many otherwise unrelated scenarios failed at the first `PLAY` with `PLAY_IDENTITY_UNAVAILABLE`; the fixture's missing scope and bare selection obscured the intended assertions. - Expected pattern: when actor-entry validation changes, update shared fixtures with complete tenant, account, actor, and playable-scope evidence; use explicit selection for success cases and retain a separate ambiguity-denial case. Treat compiled/skipped local tests as unproved until the composed CI cases execute. + +- `2026-09-26`: One-shot certificate issuance and readback require separate proof + - Context: the Entity baseline migrator needs a short-lived dedicated client identity without giving its certificate writer general Secret-read or deletion privileges. + - Observation: a leaf verifying against the CA bundled in the same Secret is only self-consistent; it does not show that the namespace trusts that CA, and static issuance tests do not show the live Entity server accepts the identity. + - Expected pattern: keep issuance opt-in and narrowly admitted, verify the projected leaf and chain against the namespace's independent trust projection under a separately authorized reader, then report live served-mTLS acceptance and later identity retirement as distinct proof. diff --git a/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh b/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh index 3cc0830460..688ad78618 100755 --- a/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh +++ b/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh @@ -21,22 +21,37 @@ if [[ $# -eq 1 && "$1" != --wait ]]; then elif [[ $# -eq 2 && "$1" == --wait ]]; then transport_operation='wait' namespace="$2" +elif [[ $# -eq 2 && "$1" == --migrator ]]; then + transport_operation='write-migrator' + namespace="$2" +elif [[ $# -eq 2 && "$1" == --verify-migrator ]]; then + transport_operation='verify-migrator' + namespace="$2" else - echo "usage: $0 [--wait] " >&2 + echo "usage: $0 [--wait|--migrator|--verify-migrator] " >&2 exit 2 fi -if [[ ! "$namespace" =~ ^pr-[1-9][0-9]{0,50}$ ]]; then +if [[ "$transport_operation" == write || "$transport_operation" == wait ]] && + [[ ! "$namespace" =~ ^pr-[1-9][0-9]{0,50}$ ]]; then echo "runtime namespace must be canonical pr-N: ${namespace}" >&2 exit 2 fi +if [[ ! "$namespace" =~ ^(dev|pr-[1-9][0-9]{0,50})$ ]]; then + echo "runtime namespace must be dev or canonical pr-N: ${namespace}" >&2 + exit 2 +fi + telnet_certificate="${namespace}-telnet-tls" gateway_certificate="${namespace}-gateway-internal-ws" bridge_certificate="${namespace}-tcp-proxy-bridge" public_hostname="${namespace}.${PREVIEW_DOMAIN}" gateway_dns_name="spring-cloud-gateway-mtls.${namespace}.svc.cluster.local" bridge_uri_san="spiffe://firemud/ns/${namespace}/sa/tcp-proxy-service" +migrator_certificate="${namespace}-grpc-game-design-baseline-migrator" +migrator_secret='firemud-grpc-game-design-baseline-migrator' +migrator_uri_san="spiffe://firemud/ns/${namespace}/sa/game-design-baseline-migrator" deadline=$((SECONDS + certificate_wait_timeout_seconds)) write_certificates() { @@ -121,6 +136,110 @@ spec: EOF } +write_migrator_certificate() { + cat <&2 + return 1 + fi + printf 'namespace=%s\ncertificate=%s\nready=true\n' "$namespace" "$migrator_certificate" +} + +verify_migrator_secret() { + local secret_json trusted_ca_data temp_dir san_output eku_output + if ! kubectl --namespace "$namespace" wait \ + --for=condition=Ready "certificate/${migrator_certificate}" \ + --timeout="${certificate_wait_timeout_seconds}s"; then + echo "Certificate/${migrator_certificate} is not Ready; refusing migrator identity verification." >&2 + return 1 + fi + if ! secret_json="$(kubectl --namespace "$namespace" get secret "$migrator_secret" -o json)"; then + echo "Unable to read Secret/${migrator_secret}; refusing migrator identity verification." >&2 + return 1 + fi + if ! trusted_ca_data="$(kubectl --namespace "$namespace" get secret firemud-grpc-tls \ + -o 'jsonpath={.data.ca\.crt}')" || [[ -z "$trusted_ca_data" ]]; then + echo "Unable to read the canonical firemud-grpc-tls CA projection; refusing migrator identity verification." >&2 + return 1 + fi + if ! jq -e --arg name "$migrator_secret" ' + .metadata.name == $name and + .type == "kubernetes.io/tls" and + .data["tls.crt"] != null and .data["tls.crt"] != "" and + .data["tls.key"] != null and .data["tls.key"] != "" and + .data["ca.crt"] != null and .data["ca.crt"] != "" + ' <<<"$secret_json" >/dev/null; then + echo "Secret/${migrator_secret} is not a complete dedicated TLS projection." >&2 + return 1 + fi + + temp_dir="$(mktemp -d)" + chmod 700 "$temp_dir" + trap 'rm -rf -- "$temp_dir"' RETURN + jq -r '.data["tls.crt"]' <<<"$secret_json" | base64 --decode >"$temp_dir/tls.crt" + jq -r '.data["ca.crt"]' <<<"$secret_json" | base64 --decode >"$temp_dir/ca.crt" + base64 --decode <<<"$trusted_ca_data" >"$temp_dir/trusted-ca.crt" + if ! openssl verify -CAfile "$temp_dir/ca.crt" "$temp_dir/tls.crt" >/dev/null; then + echo "Secret/${migrator_secret} leaf does not verify against its projected CA." >&2 + return 1 + fi + if ! openssl verify -CAfile "$temp_dir/trusted-ca.crt" -partial_chain \ + "$temp_dir/ca.crt" >/dev/null || + ! openssl verify -CAfile "$temp_dir/trusted-ca.crt" -untrusted "$temp_dir/ca.crt" \ + "$temp_dir/tls.crt" >/dev/null; then + echo "Secret/${migrator_secret} CA chain is not trusted by the namespace firemud-grpc-tls bundle." >&2 + return 1 + fi + san_output="$(openssl x509 -in "$temp_dir/tls.crt" -noout -ext subjectAltName 2>/dev/null | tail -n +2 | xargs)" + if [[ "$san_output" != "URI:${migrator_uri_san}" ]]; then + echo "Secret/${migrator_secret} certificate does not contain only the exact migrator SPIFFE URI SAN." >&2 + return 1 + fi + eku_output="$(openssl x509 -in "$temp_dir/tls.crt" -noout -ext extendedKeyUsage 2>/dev/null | tail -n +2 | xargs)" + if [[ "$eku_output" != 'TLS Web Client Authentication' ]]; then + echo "Secret/${migrator_secret} certificate is not clientAuth-only." >&2 + return 1 + fi + printf 'namespace=%s\nsecret=%s\nleaf-ca-match=true\nnamespace-trust-match=true\nuri-san=%s\nclient-auth-only=true\n' \ + "$namespace" "$migrator_secret" "$migrator_uri_san" +} + wait_for_certificates() { local certificate remaining for certificate in "$telnet_certificate" "$gateway_certificate" "$bridge_certificate"; do @@ -177,7 +296,11 @@ wait_for_secret_projection() { return 1 } -if [[ "$transport_operation" == write ]]; then +if [[ "$transport_operation" == write-migrator ]]; then + write_migrator_certificate +elif [[ "$transport_operation" == verify-migrator ]]; then + verify_migrator_secret +elif [[ "$transport_operation" == write ]]; then write_certificates wait_for_certificates printf 'namespace=%s\ncertificates=ready\n' "$namespace" diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index 7f1daef56d..fdda9794e1 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -1430,6 +1430,28 @@ assert "object.metadata.labels['firemud.dev/role'] == 'grpc-account-service'" in assert "object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service'" in cert_manager_expression assert "object.metadata.name == 'dev-grpc-account-service'" in cert_manager_expression assert "object.metadata.name == 'dev-grpc-game-session-service'" in cert_manager_expression +assert cert_manager_expression.count( + "request.name == 'firemud-grpc-game-design-baseline-migrator'" +) == 1, "migrator Secret admission match must be a single exact branch" +for migration_secret_gate in ( + "request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$')", + "object.metadata.name == 'firemud-grpc-game-design-baseline-migrator'", + "object.metadata.labels['firemud.dev/managed-by'] == 'entity-baseline-migration'", + "object.metadata.labels['firemud.dev/role'] == 'grpc-game-design-baseline-migrator'", + "object.metadata.labels['firemud.dev/retention'] == 'ephemeral'", + "object.metadata.annotations['cert-manager.io/certificate-name'] == request.namespace + '-grpc-game-design-baseline-migrator'", + "object.metadata.annotations['cert-manager.io/issuer-name'] == 'firemud-ca-issuer'", + "ref.name == request.namespace + '-grpc-game-design-baseline-migrator'", +): + assert migration_secret_gate in cert_manager_expression, migration_secret_gate +assert "request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')" not in ( + cert_manager_expression.split( + "object.metadata.name == 'firemud-grpc-game-design-baseline-migrator'", 1 + )[0].rsplit( + "(request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager'", + 1, + )[-1] +), "migrator Secret authorization must not include retained identity namespaces" assert "request.namespace.substring(0, request.namespace.size() - 9) + '-tls'" in cert_manager_expression assert "request.namespace.substring(0, request.namespace.size() - 9) + '-telnet-tls'" in cert_manager_expression assert "request.namespace.substring(0, request.namespace.size() - 9) + '-gateway-internal-ws'" in cert_manager_expression @@ -1451,6 +1473,7 @@ assert "request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')" in certific assert "request.operation == 'DELETE'" in certificate_namespace_match assert "request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-" in certificate_namespace_match assert "request.name.startsWith(" in certificate_namespace_match +assert "request.name == request.namespace + '-grpc-game-design-baseline-migrator'" in certificate_namespace_match assert "request.operation != 'DELETE'" in certificate_namespace_match assert "object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-" in certificate_namespace_match assert "object.metadata.name.startsWith(" in certificate_namespace_match @@ -1485,6 +1508,8 @@ assert "object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gat assert "grpc-publication-" in certificate_match assert "grpc-account-service" in certificate_match assert "grpc-game-session-service" in certificate_match +assert "system:serviceaccount:firemud-system:firemud-standalone-certificate-writer" in certificate_match +assert "object.spec.secretName == 'firemud-grpc-game-design-baseline-migrator'" in certificate_match assert "object.metadata.name == 'firemud-grpc-tls'" not in certificate_match certificate_expressions = [ diff --git a/dev-tools/tests/preview-standalone-transport-certificates-contract.sh b/dev-tools/tests/preview-standalone-transport-certificates-contract.sh index f7fd7c0319..e5adfc7ffd 100755 --- a/dev-tools/tests/preview-standalone-transport-certificates-contract.sh +++ b/dev-tools/tests/preview-standalone-transport-certificates-contract.sh @@ -37,6 +37,13 @@ case " $* " in previous="$argument" done case "$secret_name" in + firemud-grpc-tls) + if [[ -z "${FAKE_KUBECTL_TRUST_CA:-}" ]]; then + echo "canonical CA fixture is required" >&2 + exit 2 + fi + base64 -w0 "$FAKE_KUBECTL_TRUST_CA" + ;; pr-42-telnet-tls) if [[ "${FAKE_KUBECTL_INCOMPLETE:-false}" == true ]]; then printf '%s' '{"metadata":{"name":"pr-42-telnet-tls"},"data":{"tls.crt":"cert"}}' @@ -50,6 +57,13 @@ case " $* " in pr-42-tcp-proxy-bridge) printf '%s' '{"metadata":{"name":"pr-42-tcp-proxy-bridge"},"data":{"tls.crt":"cert","tls.key":"key","ca.crt":"ca"}}' ;; + firemud-grpc-game-design-baseline-migrator) + if [[ -z "${FAKE_KUBECTL_SECRET_JSON:-}" ]]; then + echo "migrator Secret fixture is required" >&2 + exit 2 + fi + cat "$FAKE_KUBECTL_SECRET_JSON" + ;; *) echo "unexpected Secret lookup: $secret_name" >&2 exit 2 @@ -82,6 +96,7 @@ assert_rejected() { assert_rejected 'runtime namespace must be canonical pr-N' pr-0 assert_rejected 'runtime namespace must be canonical pr-N' pr-42-identity assert_rejected 'runtime namespace must be canonical pr-N' dev +assert_rejected 'runtime namespace must be dev or canonical pr-N' --migrator dev-identity assert_rejected 'usage:' pr-42 ignored-override assert_rejected 'usage:' --bogus pr-42 assert_rejected 'usage:' --wait @@ -215,4 +230,110 @@ grep -Fq 'did not become key-complete' "$TEMP_DIR/incomplete.err" || { exit 1 } +runtime_calls_start="$(wc -l <"$STATE_DIR/calls")" +PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + "$SCRIPT" --migrator dev >"$TEMP_DIR/migrator-issued.out" +runtime_calls="$(tail -n +$((runtime_calls_start + 1)) "$STATE_DIR/calls")" +if grep -Fq 'get secret' <<<"$runtime_calls"; then + echo "migrator certificate writer read a Secret" >&2 + exit 1 +fi +python3 - "$STATE_DIR/applied.yaml" <<'PY' +import sys +from pathlib import Path + +import yaml + +document = yaml.safe_load(Path(sys.argv[1]).read_text(encoding="utf-8")) +if document.get("kind") != "Certificate": + raise SystemExit("migrator opt-in did not apply one Certificate") +if document["metadata"].get("name") != "dev-grpc-game-design-baseline-migrator": + raise SystemExit("migrator Certificate name is not namespace-bound") +spec = document["spec"] +if spec.get("secretName") != "firemud-grpc-game-design-baseline-migrator": + raise SystemExit("migrator Certificate does not use the dedicated Secret") +if spec.get("uris") != ["spiffe://firemud/ns/dev/sa/game-design-baseline-migrator"]: + raise SystemExit("migrator Certificate URI SAN is not exact") +if "dnsNames" in spec or spec.get("usages") != ["digital signature", "key encipherment", "client auth"]: + raise SystemExit("migrator Certificate is not URI-only clientAuth") +if spec.get("issuerRef") != { + "name": "firemud-ca-issuer", + "kind": "ClusterIssuer", + "group": "cert-manager.io", +}: + raise SystemExit("migrator Certificate must use the internal ClusterIssuer") +if spec.get("secretTemplate", {}).get("metadata", {}).get("labels") != { + "firemud.dev/managed-by": "entity-baseline-migration", + "firemud.dev/role": "grpc-game-design-baseline-migrator", + "firemud.dev/retention": "ephemeral", +}: + raise SystemExit("migrator Secret labels do not match the exact admission profile") +PY + +openssl req -x509 -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/ca.key" \ + -out "$TEMP_DIR/ca.crt" -subj '/CN=FireMUD test CA' -days 1 >/dev/null 2>&1 +openssl req -new -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/leaf.key" \ + -out "$TEMP_DIR/leaf.csr" -subj '/CN=baseline migrator' \ + -addext 'subjectAltName=URI:spiffe://firemud/ns/dev/sa/game-design-baseline-migrator' \ + -addext 'extendedKeyUsage=clientAuth' \ + -addext 'keyUsage=digitalSignature,keyEncipherment' >/dev/null 2>&1 +openssl x509 -req -in "$TEMP_DIR/leaf.csr" -CA "$TEMP_DIR/ca.crt" \ + -CAkey "$TEMP_DIR/ca.key" -CAcreateserial -days 1 -copy_extensions copy \ + -out "$TEMP_DIR/leaf.crt" >/dev/null 2>&1 +jq -n \ + --arg name firemud-grpc-game-design-baseline-migrator \ + --arg leaf "$(base64 -w0 "$TEMP_DIR/leaf.crt")" \ + --arg ca "$(base64 -w0 "$TEMP_DIR/ca.crt")" \ + '{metadata:{name:$name},type:"kubernetes.io/tls",data:{"tls.crt":$leaf,"tls.key":"c2VjcmV0","ca.crt":$ca}}' \ + >"$TEMP_DIR/migrator-secret.json" +PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + FAKE_KUBECTL_SECRET_JSON="$TEMP_DIR/migrator-secret.json" \ + FAKE_KUBECTL_TRUST_CA="$TEMP_DIR/ca.crt" \ + "$SCRIPT" --verify-migrator dev >"$TEMP_DIR/migrator-verified.out" +grep -Fq 'leaf-ca-match=true' "$TEMP_DIR/migrator-verified.out" +grep -Fq 'namespace-trust-match=true' "$TEMP_DIR/migrator-verified.out" +grep -Fq 'client-auth-only=true' "$TEMP_DIR/migrator-verified.out" +if grep -Fq 'tls.key' "$TEMP_DIR/migrator-verified.out"; then + echo "migrator verification output disclosed a private-key field" >&2 + exit 1 +fi + +openssl req -new -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/wrong-leaf.key" \ + -out "$TEMP_DIR/wrong-leaf.csr" -subj '/CN=wrong migrator' \ + -addext 'subjectAltName=URI:spiffe://firemud/ns/dev/sa/game-design-service' \ + -addext 'extendedKeyUsage=clientAuth' \ + -addext 'keyUsage=digitalSignature,keyEncipherment' >/dev/null 2>&1 +openssl x509 -req -in "$TEMP_DIR/wrong-leaf.csr" -CA "$TEMP_DIR/ca.crt" \ + -CAkey "$TEMP_DIR/ca.key" -CAcreateserial -days 1 -copy_extensions copy \ + -out "$TEMP_DIR/wrong-leaf.crt" >/dev/null 2>&1 +jq -n \ + --arg name firemud-grpc-game-design-baseline-migrator \ + --arg leaf "$(base64 -w0 "$TEMP_DIR/wrong-leaf.crt")" \ + --arg ca "$(base64 -w0 "$TEMP_DIR/ca.crt")" \ + '{metadata:{name:$name},type:"kubernetes.io/tls",data:{"tls.crt":$leaf,"tls.key":"c2VjcmV0","ca.crt":$ca}}' \ + >"$TEMP_DIR/wrong-migrator-secret.json" +if PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + FAKE_KUBECTL_SECRET_JSON="$TEMP_DIR/wrong-migrator-secret.json" \ + FAKE_KUBECTL_TRUST_CA="$TEMP_DIR/ca.crt" \ + "$SCRIPT" --verify-migrator dev >"$TEMP_DIR/wrong-migrator.out" \ + 2>"$TEMP_DIR/wrong-migrator.err"; then + echo "migrator verifier accepted a certificate for another SPIFFE identity" >&2 + exit 1 +fi +grep -Fq 'does not contain only the exact migrator SPIFFE URI SAN' \ + "$TEMP_DIR/wrong-migrator.err" + +openssl req -x509 -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/wrong-ca.key" \ + -out "$TEMP_DIR/wrong-ca.crt" -subj '/CN=Untrusted test CA' -days 1 >/dev/null 2>&1 +if PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + FAKE_KUBECTL_SECRET_JSON="$TEMP_DIR/migrator-secret.json" \ + FAKE_KUBECTL_TRUST_CA="$TEMP_DIR/wrong-ca.crt" \ + "$SCRIPT" --verify-migrator dev >"$TEMP_DIR/wrong-ca.out" \ + 2>"$TEMP_DIR/wrong-ca.err"; then + echo "migrator verifier accepted a CA not trusted by firemud-grpc-tls" >&2 + exit 1 +fi +grep -Fq 'CA chain is not trusted by the namespace firemud-grpc-tls bundle' \ + "$TEMP_DIR/wrong-ca.err" + echo "preview standalone transport certificate contract passed" diff --git a/dev-tools/tests/trust-bootstrap-issuance-contract.sh b/dev-tools/tests/trust-bootstrap-issuance-contract.sh index a7f989a065..0662af4c22 100755 --- a/dev-tools/tests/trust-bootstrap-issuance-contract.sh +++ b/dev-tools/tests/trust-bootstrap-issuance-contract.sh @@ -175,6 +175,10 @@ def check_contract(items: list[dict]) -> None: "object.spec.privateKey.rotationPolicy == 'Always'", "object.spec.usages == ['digital signature', 'key encipherment', 'server auth']", "object.spec.usages == ['digital signature', 'key encipherment', 'client auth']", + "object.spec.secretName == 'firemud-grpc-game-design-baseline-migrator'", + "object.spec.secretTemplate.metadata.labels == {", + "object.spec.secretTemplate.metadata.annotations == {", + "object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/game-design-baseline-migrator']", "firemud-hosted-identity-controller", "system:serviceaccount:kube-system:namespace-controller", "object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$')", @@ -205,7 +209,7 @@ def check_contract(items: list[dict]) -> None: fail("Certificate status denial message does not describe the allowed callers") require( certificate_validation, - "^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$", + "^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator))$", "standalone Certificate validation", ) for needle in ( diff --git a/k8s/hosted-identity-controller/admission.yaml b/k8s/hosted-identity-controller/admission.yaml index e4783b7e0d..35783a9c55 100644 --- a/k8s/hosted-identity-controller/admission.yaml +++ b/k8s/hosted-identity-controller/admission.yaml @@ -151,19 +151,22 @@ spec: expression: >- (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && request.namespace.matches('^(dev|dev-identity|pr-[1-9][0-9]{0,50}|pr-[1-9][0-9]{0,50}-identity)$')) || + (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + request.name == 'firemud-grpc-game-design-baseline-migrator') || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$')) || ((request.namespace in ['dev', 'dev-identity'] || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && ((request.operation == 'DELETE' && - (request.name == 'firemud-grpc-tls' || request.name == 'firemud-grpc-account-service' || request.name == 'firemud-grpc-game-session-service' || + (request.name == 'firemud-grpc-tls' || request.name == 'firemud-grpc-account-service' || request.name == 'firemud-grpc-game-session-service' || request.name == 'firemud-grpc-game-design-baseline-migrator' || request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') || request.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$') || request.name == 'firemud-grpc-tls-previous' || request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))-previous$'))) || (request.operation != 'DELETE' && - (object.metadata.name == 'firemud-grpc-tls' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-game-session-service' || + (object.metadata.name == 'firemud-grpc-tls' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-game-session-service' || object.metadata.name == 'firemud-grpc-game-design-baseline-migrator' || object.metadata.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$') || object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') || object.metadata.name == 'firemud-grpc-tls-previous' || @@ -179,8 +182,9 @@ spec: (request.namespace in ['dev', 'dev-identity'] || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && - request.name.matches('^(firemud-grpc-tls|firemud-grpc-tls-previous|firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)|firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)-previous|(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))(-previous)?)$') && + request.name.matches('^(firemud-grpc-tls|firemud-grpc-tls-previous|firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)|firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)-previous|firemud-grpc-game-design-baseline-migrator|(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))(-previous)?)$') && (request.name == 'firemud-grpc-tls' || request.name == 'firemud-grpc-tls-previous' || + request.name == 'firemud-grpc-game-design-baseline-migrator' || request.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)(-previous)?$') || request.name.startsWith( ((request.namespace == 'dev' || request.namespace == 'dev-identity') ? 'dev' : @@ -237,6 +241,26 @@ spec: request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$') ? request.namespace.substring(0, request.namespace.size() - 9) : request.namespace) + '-')))))))) || + (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && + request.operation in ['CREATE', 'UPDATE'] && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + object.type == 'kubernetes.io/tls' && + object.metadata.name == 'firemud-grpc-game-design-baseline-migrator' && + has(object.metadata.labels) && + object.metadata.labels['firemud.dev/managed-by'] == 'entity-baseline-migration' && + object.metadata.labels['firemud.dev/role'] == 'grpc-game-design-baseline-migrator' && + object.metadata.labels['firemud.dev/retention'] == 'ephemeral' && + has(object.metadata.annotations) && + object.metadata.annotations['firemud.dev/provenance'] == 'cert-manager' && + object.metadata.annotations['cert-manager.io/certificate-name'] == request.namespace + '-grpc-game-design-baseline-migrator' && + object.metadata.annotations['cert-manager.io/issuer-name'] == 'firemud-ca-issuer' && + object.metadata.annotations['cert-manager.io/issuer-kind'] == 'ClusterIssuer' && + object.metadata.annotations['cert-manager.io/issuer-group'] == 'cert-manager.io' && + ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || + object.metadata.ownerReferences.all(ref, + ref.apiVersion == 'cert-manager.io/v1' && + ref.kind == 'Certificate' && + ref.name == request.namespace + '-grpc-game-design-baseline-migrator'))) || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.operation in ['CREATE', 'UPDATE'] && request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$') && @@ -288,13 +312,20 @@ spec: - expression: >- request.userInfo.username != 'system:serviceaccount:cert-manager:cert-manager' || (request.operation in ['CREATE', 'UPDATE'] && - request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$') && + ((request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + object.metadata.name == 'firemud-grpc-game-design-baseline-migrator' && + ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || + object.metadata.ownerReferences.all(ref, + ref.apiVersion == 'cert-manager.io/v1' && + ref.kind == 'Certificate' && + ref.name == request.namespace + '-grpc-game-design-baseline-migrator'))) || + (request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$') && object.metadata.name != 'firemud-grpc-tls' && ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || object.metadata.ownerReferences.all(ref, ref.apiVersion == 'cert-manager.io/v1' && ref.kind == 'Certificate' && - ref.name == object.metadata.name))) + ref.name == object.metadata.name))))) message: cert-manager may not write a TLS Secret outside its exact Certificate ownership boundary reason: Forbidden --- @@ -327,6 +358,9 @@ spec: - name: hosted-identity-certificate-namespace expression: >- request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' || + (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + request.name == request.namespace + '-grpc-game-design-baseline-migrator') || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$')) || (request.userInfo.groups.exists(group, group == 'system:masters') && @@ -350,6 +384,13 @@ spec: request.subResource == '' && request.operation == 'DELETE' && (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$'))) || + (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && + request.subResource == '' && + request.operation in ['CREATE', 'UPDATE'] && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + request.name == request.namespace + '-grpc-game-design-baseline-migrator' && + object.spec.secretName == 'firemud-grpc-game-design-baseline-migrator' && + object.spec.issuerRef.name == 'firemud-ca-issuer') || (request.userInfo.username == 'system:serviceaccount:kube-system:namespace-controller' && request.subResource == '' && request.operation == 'DELETE' && diff --git a/k8s/trust-bootstrap/issuance-admission.yaml b/k8s/trust-bootstrap/issuance-admission.yaml index a831a48a98..b273c80a6a 100644 --- a/k8s/trust-bootstrap/issuance-admission.yaml +++ b/k8s/trust-bootstrap/issuance-admission.yaml @@ -57,7 +57,9 @@ spec: owner.kind == 'Certificate' && owner.controller == true && owner.blockOwnerDeletion == true && - owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$'))) + (owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') || + (request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + owner.name == request.namespace + '-grpc-game-design-baseline-migrator')))) message: internal CertificateRequests must use the canonical ClusterIssuer and be owned by a canonical Certificate reason: Forbidden - expression: >- @@ -112,7 +114,9 @@ spec: owner.kind == 'Certificate' && owner.controller == true && owner.blockOwnerDeletion == true && - owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$'))) + (owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') || + (request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + owner.name == request.namespace + '-grpc-game-design-baseline-migrator')))) message: internal CertificateRequest approval and status may not alter its canonical spec or ownership reason: Forbidden @@ -149,24 +153,24 @@ spec: (has(oldObject.spec.issuerRef) && oldObject.spec.issuerRef.name == 'firemud-ca-issuer' || ((oldObject.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$') && + (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) || (request.operation == 'CREATE' && (has(object.spec.issuerRef) && object.spec.issuerRef.name == 'firemud-ca-issuer' || ((object.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$') && + (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) || (request.operation == 'UPDATE' && (has(object.spec.issuerRef) && object.spec.issuerRef.name == 'firemud-ca-issuer' || (object.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$') && + (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$')) || (has(oldObject.spec.issuerRef) && oldObject.spec.issuerRef.name == 'firemud-ca-issuer' || (oldObject.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$') && + (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) validations: - expression: >- @@ -174,21 +178,21 @@ spec: (request.operation == 'DELETE' && request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && - request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$')) || + request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator))$')) || (request.operation == 'DELETE' && request.userInfo.username == 'system:serviceaccount:kube-system:namespace-controller' && (request.namespace == 'dev' || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && - request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$')) || + request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator))$')) || (request.operation != 'DELETE' && ((request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && (request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || object.metadata.name.contains('-grpc-')) && - object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') && + object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator))$') && object.metadata.name.startsWith(request.namespace + '-') && has(object.spec.secretName) && ((object.metadata.name.contains('-grpc-') && - object.spec.secretName.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$')) || + object.spec.secretName.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$')) || (!object.metadata.name.contains('-grpc-') && object.spec.secretName == object.metadata.name)) && has(object.spec.isCA) && @@ -264,7 +268,23 @@ spec: object.spec.issuerRef.name == 'firemud-ca-issuer' && object.spec.dnsNames == ['game-session-service', 'game-session-service.' + request.namespace, 'game-session-service.' + request.namespace + '.svc', 'game-session-service.' + request.namespace + '.svc.cluster.local'] && object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/game-session-service'] && - object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth']))) || + object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth']) || + (object.metadata.name.endsWith('-grpc-game-design-baseline-migrator') && + object.spec.secretName == 'firemud-grpc-game-design-baseline-migrator' && + object.spec.issuerRef.name == 'firemud-ca-issuer' && + has(object.spec.secretTemplate) && + has(object.spec.secretTemplate.metadata) && + object.spec.secretTemplate.metadata.labels == { + 'firemud.dev/managed-by': 'entity-baseline-migration', + 'firemud.dev/role': 'grpc-game-design-baseline-migrator', + 'firemud.dev/retention': 'ephemeral' + } && + object.spec.secretTemplate.metadata.annotations == { + 'firemud.dev/provenance': 'cert-manager' + } && + (!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && + object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/game-design-baseline-migrator'] && + object.spec.usages == ['digital signature', 'key encipherment', 'client auth']))) || (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') && diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java index b44ad926fd..cea39c5387 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.maintenance; import com.fasterxml.jackson.databind.ObjectMapper; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; @@ -20,6 +21,9 @@ /** Trusted, one-shot entry point; no HTTP, gRPC server, or user-JWT mutation route is exposed. */ @Component +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Spring collaborators are internal to the migration Job.") @ConditionalOnProperty( prefix = "firemud.entity-baseline-migration", name = "enabled", diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java index c42585eac3..f10ce76860 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamedesign.service.impl; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -24,6 +25,9 @@ /** Bounded enumeration, preflight, and one-scope recomputation for retained Entity v1 baselines. */ @Service +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Spring repositories and clients are internal collaborators.") public class EntityDigestBaselineMigrationService { private static final int SOURCE_SCHEMA_VERSION = 1; private static final int TARGET_SCHEMA_VERSION = 2; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java index a074832ef5..4c8716b35e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamedesign.service.impl; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Objects; import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; @@ -10,6 +11,9 @@ /** Commits one guarded baseline replacement and its immutable audit row in the same transaction. */ @Service +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Spring repositories are internal collaborators.") public class EntityDigestBaselineMigrationWriteService { private final RecordedParticipantDigestRepository baselineRepository; private final EntityDigestBaselineMigrationAuditRepository auditRepository; From 5a68415d7f80a557ab4e759b74016284acc664ba Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 15:17:59 +1200 Subject: [PATCH 04/28] Preserve publish provenance during Entity baseline migration --- .../game-design-service/operations.md | 2 +- .../game-design-service/version-control.md | 2 +- .../RecordedParticipantDigestRepository.java | 4 --- .../EntityDigestBaselineMigrationService.java | 29 ++++++++++--------- ...tyDigestBaselineMigrationWriteService.java | 12 +++++--- ...igestBaselineMigrationIntegrationTest.java | 29 +++++++++---------- ...ityDigestBaselineMigrationServiceTest.java | 25 +++++++--------- ...gestBaselineMigrationWriteServiceTest.java | 12 +++++++- 8 files changed, 61 insertions(+), 54 deletions(-) diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 207ac895a3..7f22d35dce 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -38,7 +38,7 @@ Before invoking a Job, verify the exact Kubernetes context and namespace, the au The chart's `previewStack.entityDigestBaselineMigration` values are disabled by default. From the trusted operator revision, supply an image pinned as `repository@sha256:`, exact `targetNamespace`, the dedicated `firemud-grpc-game-design-baseline-migrator` Secret, and `mode`. `enumerate` returns at most 500 Entity schema-v1 full-version rows after one baseline ID; repeat with its returned keyset cursor until an empty page proves no more rows at the quiesced snapshot. `preflight` classifies one exact tenant/version as v1, v2, absent, ambiguous, or unsupported, and refuses a missing or script-only Version. `migrate` requires one stable operation ID, exact tenant/version, actor identity, and the immutable expected-source object. The Java runner verifies its namespace, dedicated service account, and certificate URI identity before reading or writing. A missing identity, policy, input, row, version, exact-old match, or v2 Entity response fails closed. Render and inspect the operator overlay before installation; do not leave `enabled: true` in the ordinary chart values or an unattended release upgrade. Completed Jobs are deliberately not Helm hooks, so an unchanged upgrade does not rerun them; a changed immutable Job spec is rejected and needs an explicit trusted disposition. -For each affected scope, retain the preflight row ID and complete source tuple privately, run `migrate`, and require its reported operation/audit/baseline IDs and disposition. The Game Design transaction conditionally replaces the exact old row and inserts an immutable before/after audit atomically. An exact retry of the same operation reads the existing audit and baseline rather than writing again; a lost acknowledgement is resolved by that same operation identity and exact readback. A changed source, ambiguous scope, different actor/workload binding, mismatched Entity v2 schema/scope/digest/commit, or unproved write outcome is a stop condition. Independently read back `publish_recorded_participant_digest` by baseline ID and `entity_digest_baseline_migration_audit` by operation ID from Game Design's PostgreSQL schema; compare the new schema/digest/commit/provenance, complete old tuple, observed v2 tuple, operation, actor/workload, outcome, and timestamp exactly. Never count Job completion alone as database proof. Keep the before/after records with the private migration log, excluding secrets and certificate keys. +For each affected scope, retain the preflight row ID and complete source tuple privately, run `migrate`, and require its reported operation/audit/baseline IDs and disposition. The Game Design transaction conditionally replaces the exact old row and inserts an immutable before/after audit atomically. The live row retains its original and last real publish-workflow IDs and timestamps; only the audit's operation ID and committed time describe the maintenance transition. An exact retry of the same operation reads the existing audit and baseline rather than writing again; a lost acknowledgement is resolved by that same operation identity and exact readback. A changed source, ambiguous scope, different actor/workload binding, mismatched Entity v2 schema/scope/digest/commit, or unproved write outcome is a stop condition. Independently read back `publish_recorded_participant_digest` by baseline ID and `entity_digest_baseline_migration_audit` by operation ID from Game Design's PostgreSQL schema; compare the new schema/digest/commit and preserved publish provenance, complete old tuple, observed v2 tuple, migration operation, actor/workload, outcome, and timestamp exactly. Never count Job completion alone as database proof. Keep the before/after records with the private migration log, excluding secrets and certificate keys. If no retained Entity v1 rows exist, record the exact namespace, database/schema, query time, quiescence evidence, and an empty bounded enumeration through its terminal page; separately preflight every affected known tenant/version scope and record its state. This is a no-data boundary, not a claim that migration ran. If a migration fails or proof is incomplete, leave affected publication closed and retain the old row/audit evidence; do not restore a v1 hash over an audited v2 row or weaken the v2 publish gate. Resume only after an exact retry/readback or an explicit database recovery decision with equivalent provenance. Reopen publication only after every enumerated v1 row has a verified v2 baseline and audit (or the scoped no-data proof), the Entity v2 producer and Game Design reader remain healthy, and the normal v2 publish gate succeeds. After the approved work and readback are complete, disable the Helm migration Job and have an authorized `system:masters` operator explicitly retire its exact dedicated Certificate and Secret; the scoped writer cannot delete them. Retain the database audit and private operation evidence. Do not leave the one-shot workload identity provisioned as an ordinary Game Design credential. Live retained data, PostgreSQL readback, certificate bootstrap, served mTLS, and identity retirement proof must be reported separately from local fixtures and static Helm renders. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index be430b9647..78e2e19b3f 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -216,7 +216,7 @@ Rules: ### Digest Schema Migration -**Current implementation status:** Entity's digest producer and Game Design's publish gate use schema v2, while retained schema-v1 Entity full-version baselines are not automatically rewritten by an ordinary publish. A protected, one-shot Game Design maintenance operation enumerates those old baselines, obtains exact-scope v2 evidence from Entity, and conditionally replaces one complete expected-old tuple together with an immutable before/after audit in a single database transaction. It reports success only after exact baseline and audit readback. This reader/reconciler understands both stored baseline schemas; it never compares v1 content with v2 content for publication, and the v2-only gate remains fail closed. Deployment requires the controlled publication window and exact operator preflight in [Game Design operations](./operations.md). No live retained-row migration or no-data proof is implied by code or test fixtures. Entity's current `version:` applied-commit token remains synthetic and does not establish an applied-revision ledger. +**Current implementation status:** Entity's digest producer and Game Design's publish gate use schema v2, while retained schema-v1 Entity full-version baselines are not automatically rewritten by an ordinary publish. A protected, one-shot Game Design maintenance operation enumerates those old baselines, obtains exact-scope v2 evidence from Entity, and conditionally replaces one complete expected-old tuple together with an immutable before/after audit in a single database transaction. It changes the digest, schema, and applied-commit evidence while retaining the live row's original and last publish-workflow provenance; the separate audit records the migration operation and time. It reports success only after exact baseline and audit readback. This reader/reconciler understands both stored baseline schemas; it never compares v1 content with v2 content for publication, and the v2-only gate remains fail closed. Deployment requires the controlled publication window and exact operator preflight in [Game Design operations](./operations.md). No live retained-row migration or no-data proof is implied by code or test fixtures. Entity's current `version:` applied-commit token remains synthetic and does not establish an applied-revision ledger. Digest semantics are part of the publish safety contract. Changing which rows/fields participate in a domain digest, or how they are canonicalized, requires an explicit migration plan: diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java index 4bc0ccc195..2642fcb885 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java @@ -142,10 +142,6 @@ public int migrateEntityFullVersionBaselineIfUnchanged( .set(APPLIED_COMMIT_ID, replacement.getAppliedCommitId()) .set(CONTENT_DIGEST, replacement.getContentDigest()) .set(DIGEST_SCHEMA_VERSION, replacement.getDigestSchemaVersion()) - .set(RECORDED_FROM_PUBLISH_WORKFLOW_ID, replacement.getRecordedFromPublishWorkflowId()) - .set(RECORDED_AT, replacement.getRecordedAt()) - .set(LAST_VERIFIED_PUBLISH_WORKFLOW_ID, replacement.getLastVerifiedPublishWorkflowId()) - .set(LAST_VERIFIED_AT, replacement.getLastVerifiedAt()) .where( ID.eq(expectedOld.getId()) .and(TENANT_ID.eq(expectedOld.getTenantId())) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java index f10ce76860..e975be9d4d 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java @@ -172,8 +172,7 @@ public MigrationResult migrate(MigrationCommand command) { validateObservedDigest(observed, command); LocalDateTime migrationTime = LocalDateTime.now().truncatedTo(ChronoUnit.MICROS); - RecordedParticipantDigest replacement = - replacementFor(current, observed, command.operationId(), migrationTime); + RecordedParticipantDigest replacement = replacementFor(current, observed); EntityDigestBaselineMigrationAudit audit = auditFor(current, observed, command, migrationTime); try { writeService.commit(current, replacement, audit); @@ -306,10 +305,7 @@ private void validateObservedDigest( } private RecordedParticipantDigest replacementFor( - RecordedParticipantDigest current, - PublishParticipantDigestDto observed, - String operationId, - LocalDateTime migrationTime) { + RecordedParticipantDigest current, PublishParticipantDigestDto observed) { RecordedParticipantDigest replacement = new RecordedParticipantDigest(); replacement.setId(current.getId()); replacement.setTenantId(current.getTenantId()); @@ -320,10 +316,10 @@ private RecordedParticipantDigest replacementFor( replacement.setAppliedCommitId(observed.appliedCommitId()); replacement.setContentDigest(observed.contentDigest()); replacement.setDigestSchemaVersion(TARGET_SCHEMA_VERSION); - replacement.setRecordedFromPublishWorkflowId(operationId); - replacement.setRecordedAt(migrationTime); - replacement.setLastVerifiedPublishWorkflowId(operationId); - replacement.setLastVerifiedAt(migrationTime); + replacement.setRecordedFromPublishWorkflowId(current.getRecordedFromPublishWorkflowId()); + replacement.setRecordedAt(current.getRecordedAt()); + replacement.setLastVerifiedPublishWorkflowId(current.getLastVerifiedPublishWorkflowId()); + replacement.setLastVerifiedAt(current.getLastVerifiedAt()); return replacement; } @@ -430,10 +426,15 @@ private MigrationResult readBackCommittedResult( || !Objects.equals(actualBaseline.getContentDigest(), actualAudit.observedContentDigest()) || !Objects.equals( actualBaseline.getDigestSchemaVersion(), actualAudit.observedDigestSchemaVersion()) - || !Objects.equals(actualBaseline.getRecordedFromPublishWorkflowId(), command.operationId()) - || !Objects.equals(actualBaseline.getRecordedAt(), actualAudit.committedAt()) - || !Objects.equals(actualBaseline.getLastVerifiedPublishWorkflowId(), command.operationId()) - || !Objects.equals(actualBaseline.getLastVerifiedAt(), actualAudit.committedAt())) { + || !Objects.equals( + actualBaseline.getRecordedFromPublishWorkflowId(), + actualAudit.sourceRecordedFromPublishWorkflowId()) + || !Objects.equals(actualBaseline.getRecordedAt(), actualAudit.sourceRecordedAt()) + || !Objects.equals( + actualBaseline.getLastVerifiedPublishWorkflowId(), + actualAudit.sourceLastVerifiedPublishWorkflowId()) + || !Objects.equals( + actualBaseline.getLastVerifiedAt(), actualAudit.sourceLastVerifiedAt())) { throw rejected( "BASELINE_READBACK_MISMATCH", "persisted baseline does not exactly match its audit"); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java index 4c8716b35e..7e2023c47a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java @@ -84,10 +84,14 @@ private void validateWriteSet( || !Integer.valueOf(2).equals(replacement.getDigestSchemaVersion()) || audit.observedContentDigest() == null || audit.observedContentDigest().isBlank() - || !Objects.equals(replacement.getRecordedFromPublishWorkflowId(), audit.operationId()) - || !Objects.equals(replacement.getLastVerifiedPublishWorkflowId(), audit.operationId()) - || !Objects.equals(replacement.getRecordedAt(), audit.committedAt()) - || !Objects.equals(replacement.getLastVerifiedAt(), audit.committedAt()) + || !Objects.equals( + replacement.getRecordedFromPublishWorkflowId(), + expectedOld.getRecordedFromPublishWorkflowId()) + || !Objects.equals(replacement.getRecordedAt(), expectedOld.getRecordedAt()) + || !Objects.equals( + replacement.getLastVerifiedPublishWorkflowId(), + expectedOld.getLastVerifiedPublishWorkflowId()) + || !Objects.equals(replacement.getLastVerifiedAt(), expectedOld.getLastVerifiedAt()) || !EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME.equals(audit.outcome())) { throw new IllegalArgumentException( "migration audit and guarded baseline replacement do not describe one operation"); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java index e0d4ca5cc5..126032d27c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java @@ -152,9 +152,7 @@ void enumeratesMixedRowsMigratesOnlyExactTenantVersionAndReadsBackAuditAndBaseli EntityDigestBaselineMigrationAudit audit = auditRepository.findByOperationId(command.operationId()).orElseThrow(); RecordedParticipantDigest expectedMigrated = - replacement(target, command.operationId(), v2Digest(targetVersion.getId())); - expectedMigrated.setRecordedAt(audit.committedAt()); - expectedMigrated.setLastVerifiedAt(audit.committedAt()); + replacement(target, v2Digest(targetVersion.getId())); assertThat(migrated).usingRecursiveComparison().isEqualTo(expectedMigrated); EntityDigestBaselineMigrationAudit expectedAudit = audit( @@ -170,10 +168,12 @@ void enumeratesMixedRowsMigratesOnlyExactTenantVersionAndReadsBackAuditAndBaseli assertThat(migrated.getAppliedCommitId()).isEqualTo("version:" + targetVersion.getId()); assertThat(migrated.getContentDigest()).isEqualTo(v2Digest(targetVersion.getId())); assertThat(migrated.getDigestSchemaVersion()).isEqualTo(2); - assertThat(migrated.getRecordedFromPublishWorkflowId()).isEqualTo(command.operationId()); - assertThat(migrated.getLastVerifiedPublishWorkflowId()).isEqualTo(command.operationId()); - assertThat(migrated.getRecordedAt()).isEqualTo(audit.committedAt()); - assertThat(migrated.getLastVerifiedAt()).isEqualTo(audit.committedAt()); + assertThat(migrated.getRecordedFromPublishWorkflowId()) + .isEqualTo(target.getRecordedFromPublishWorkflowId()); + assertThat(migrated.getLastVerifiedPublishWorkflowId()) + .isEqualTo(target.getLastVerifiedPublishWorkflowId()); + assertThat(migrated.getRecordedAt()).isEqualTo(target.getRecordedAt()); + assertThat(migrated.getLastVerifiedAt()).isEqualTo(target.getLastVerifiedAt()); assertThat(audit.id()).isEqualTo(result.auditId()); assertThat(audit.recordedParticipantDigestId()).isEqualTo(target.getId()); assertThat(audit.sourceContentDigest()).isEqualTo(target.getContentDigest()); @@ -231,8 +231,7 @@ void compareAndSwapRejectsAChangedV1SourceRow() { changed.setContentDigest("changed-after-preflight"); baselineRepository.save(changed); - RecordedParticipantDigest replacement = - replacement(expectedOld, "cas-test-operation", "v2-new"); + RecordedParticipantDigest replacement = replacement(expectedOld, "v2-new"); assertThat( baselineRepository.migrateEntityFullVersionBaselineIfUnchanged( @@ -258,7 +257,7 @@ void auditInsertFailureRollsBackTheGuardedBaselineReplacement() { baselineRepository.findById(secondSource.getId()).orElseThrow(); LocalDateTime migrationTime = LocalDateTime.now().truncatedTo(ChronoUnit.MICROS); RecordedParticipantDigest replacement = - replacement(expectedOld, firstCommand.operationId(), v2Digest(secondVersion.getId())); + replacement(expectedOld, v2Digest(secondVersion.getId())); replacement.setRecordedAt(migrationTime); replacement.setLastVerifiedAt(migrationTime); EntityDigestBaselineMigrationAudit duplicateAudit = @@ -357,7 +356,7 @@ private ExpectedSource expectedSource(RecordedParticipantDigest source) { } private RecordedParticipantDigest replacement( - RecordedParticipantDigest source, String operationId, String contentDigest) { + RecordedParticipantDigest source, String contentDigest) { RecordedParticipantDigest replacement = new RecordedParticipantDigest(); replacement.setId(source.getId()); replacement.setTenantId(source.getTenantId()); @@ -368,10 +367,10 @@ private RecordedParticipantDigest replacement( replacement.setAppliedCommitId(source.getAppliedCommitId()); replacement.setContentDigest(contentDigest); replacement.setDigestSchemaVersion(2); - replacement.setRecordedFromPublishWorkflowId(operationId); - replacement.setRecordedAt(LocalDateTime.now().truncatedTo(ChronoUnit.MICROS)); - replacement.setLastVerifiedPublishWorkflowId(operationId); - replacement.setLastVerifiedAt(replacement.getRecordedAt()); + replacement.setRecordedFromPublishWorkflowId(source.getRecordedFromPublishWorkflowId()); + replacement.setRecordedAt(source.getRecordedAt()); + replacement.setLastVerifiedPublishWorkflowId(source.getLastVerifiedPublishWorkflowId()); + replacement.setLastVerifiedAt(source.getLastVerifiedAt()); return replacement; } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java index 41dec203cb..1246b2adc4 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java @@ -174,15 +174,21 @@ void migrationCommitsAndProvesExactV2BaselineAndAuditReadback() { assertEquals("version:42", result.appliedCommitId()); assertEquals("v2-content", result.contentDigest()); assertEquals(2, result.digestSchemaVersion()); - assertEquals(OPERATION_ID, persistedBaseline.get().getRecordedFromPublishWorkflowId()); - assertEquals(OPERATION_ID, persistedBaseline.get().getLastVerifiedPublishWorkflowId()); + assertEquals( + source.getRecordedFromPublishWorkflowId(), + persistedBaseline.get().getRecordedFromPublishWorkflowId()); + assertEquals(source.getRecordedAt(), persistedBaseline.get().getRecordedAt()); + assertEquals( + source.getLastVerifiedPublishWorkflowId(), + persistedBaseline.get().getLastVerifiedPublishWorkflowId()); + assertEquals(source.getLastVerifiedAt(), persistedBaseline.get().getLastVerifiedAt()); assertEquals(source.getContentDigest(), persistedAudit.get().sourceContentDigest()); assertEquals("v2-content", persistedAudit.get().observedContentDigest()); } @Test void exactRetryReturnsOnlyAfterBaselineAndAuditReadbackWithoutRecomputing() { - RecordedParticipantDigest migrated = migratedBaseline("v2-content", "version:42", auditTime()); + RecordedParticipantDigest migrated = migratedBaseline("v2-content", "version:42"); EntityDigestBaselineMigrationAudit audit = audit(source, migrated, AUDIT_ID, auditTime()); when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.of(audit)); when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(migrated)); @@ -201,11 +207,7 @@ void exactRetryReturnsOnlyAfterBaselineAndAuditReadbackWithoutRecomputing() { @Test void operationIdReuseWithDifferentSourceIsRejected() { EntityDigestBaselineMigrationAudit conflicting = - audit( - source, - migratedBaseline("v2-content", "version:42", auditTime()), - AUDIT_ID, - auditTime()); + audit(source, migratedBaseline("v2-content", "version:42"), AUDIT_ID, auditTime()); conflicting = withSourceContentDigest(conflicting, "different-v1-digest"); when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.of(conflicting)); @@ -433,16 +435,11 @@ private PublishParticipantDigestDto v2Digest(String digest, String appliedCommit "ENTITY_MANAGEMENT", "42", null, appliedCommitId, digest, 2, null, null); } - private RecordedParticipantDigest migratedBaseline( - String digest, String appliedCommitId, LocalDateTime committedAt) { + private RecordedParticipantDigest migratedBaseline(String digest, String appliedCommitId) { RecordedParticipantDigest baseline = sourceBaseline(); baseline.setAppliedCommitId(appliedCommitId); baseline.setContentDigest(digest); baseline.setDigestSchemaVersion(2); - baseline.setRecordedFromPublishWorkflowId(OPERATION_ID); - baseline.setRecordedAt(committedAt); - baseline.setLastVerifiedPublishWorkflowId(OPERATION_ID); - baseline.setLastVerifiedAt(committedAt); return baseline; } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java index 1dec9ff473..046d2e1396 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java @@ -34,7 +34,7 @@ void setUp() { service = new EntityDigestBaselineMigrationWriteService(baselineRepository, auditRepository); LocalDateTime time = LocalDateTime.parse("2026-09-26T01:02:03.123456"); source = baseline(1, "old", time.minusDays(1), "publish:old", "verify:old"); - replacement = baseline(2, "new", time, "migration-op", "migration-op"); + replacement = baseline(2, "new", time.minusDays(1), "publish:old", "verify:old"); audit = audit(time); } @@ -59,6 +59,16 @@ void changedRowPreventsAuditInsert() { verify(auditRepository, never()).insert(any()); } + @Test + void maintenanceOperationCannotReplacePublishProvenance() { + replacement.setRecordedFromPublishWorkflowId("migration-op"); + + assertThrows(IllegalArgumentException.class, () -> service.commit(source, replacement, audit)); + + verify(baselineRepository, never()).migrateEntityFullVersionBaselineIfUnchanged(any(), any()); + verify(auditRepository, never()).insert(any()); + } + private RecordedParticipantDigest baseline( int schema, String digest, LocalDateTime time, String recordedFrom, String lastVerified) { RecordedParticipantDigest baseline = new RecordedParticipantDigest(); From 60660c538265f94d70517483983d9757daacbe0f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 17:32:11 +1200 Subject: [PATCH 05/28] Return and verify generated participant baseline IDs --- .../RecordedParticipantDigestRepository.java | 10 ++++++++-- ...yDigestBaselineMigrationIntegrationTest.java | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java index 2642fcb885..902963cdff 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java @@ -236,9 +236,15 @@ public RecordedParticipantDigest save(RecordedParticipantDigest digest) { .set(RECORDED_AT, recordedAt) .set(LAST_VERIFIED_PUBLISH_WORKFLOW_ID, digest.getLastVerifiedPublishWorkflowId()) .set(LAST_VERIFIED_AT, lastVerifiedAt) - .returning() + .returning(ID) .fetchOne(); - return toEntity(record); + Long id = record == null ? null : record.get(ID); + if (id == null || id < 1) { + throw new IllegalStateException("recorded participant digest insert returned no row ID"); + } + return findById(id) + .orElseThrow( + () -> new IllegalStateException("inserted recorded participant digest is missing")); } dsl.update(TABLE_REF) .set(TENANT_ID, digest.getTenantId()) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java index 126032d27c..f0f1394901 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java @@ -105,6 +105,23 @@ void returnDeterministicEntityV2Evidence() { }); } + @Test + void insertedBaselineReturnsGeneratedIdAndExactDatabaseRow() { + createGame("9601"); + Version version = createVersion("9601", 1); + + RecordedParticipantDigest inserted = seedEntityBaseline("9601", version, 1); + + assertThat(inserted.getId()).isPositive(); + assertThat(baselineRepository.findById(inserted.getId()).orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(inserted); + assertThat(inserted.getTenantId()).isEqualTo("9601"); + assertThat(inserted.getScopeValue()).isEqualTo(Long.toString(version.getId())); + assertThat(inserted.getContentDigest()).isEqualTo("entity-v1-" + version.getId()); + assertThat(inserted.getDigestSchemaVersion()).isEqualTo(1); + } + @Test void enumeratesMixedRowsMigratesOnlyExactTenantVersionAndReadsBackAuditAndBaseline() { createGame("9201"); From c2888a13208ff8098421650ed8a339aee928c092 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 17:43:01 +1200 Subject: [PATCH 06/28] Map recorded baseline timestamps from PostgreSQL rows --- .../RecordedParticipantDigestRepository.java | 19 +++++++++++++++++-- ...igestBaselineMigrationIntegrationTest.java | 2 ++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java index 902963cdff..8717c47822 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; @@ -289,9 +290,23 @@ private RecordedParticipantDigest toEntity(Record record) { digest.setContentDigest(record.get(CONTENT_DIGEST)); digest.setDigestSchemaVersion(record.get(DIGEST_SCHEMA_VERSION)); digest.setRecordedFromPublishWorkflowId(record.get(RECORDED_FROM_PUBLISH_WORKFLOW_ID)); - digest.setRecordedAt(record.get(RECORDED_AT)); + digest.setRecordedAt(toLocalDateTime(record, RECORDED_AT)); digest.setLastVerifiedPublishWorkflowId(record.get(LAST_VERIFIED_PUBLISH_WORKFLOW_ID)); - digest.setLastVerifiedAt(record.get(LAST_VERIFIED_AT)); + digest.setLastVerifiedAt(toLocalDateTime(record, LAST_VERIFIED_AT)); return digest; } + + private LocalDateTime toLocalDateTime(Record record, Field field) { + Object value = record.get(field); + if (value == null) { + return null; + } + if (value instanceof LocalDateTime localDateTime) { + return localDateTime; + } + if (value instanceof Timestamp timestamp) { + return timestamp.toLocalDateTime(); + } + throw new IllegalStateException("unexpected timestamp type for " + field.getName()); + } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java index f0f1394901..9b0713727a 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java @@ -120,6 +120,8 @@ void insertedBaselineReturnsGeneratedIdAndExactDatabaseRow() { assertThat(inserted.getScopeValue()).isEqualTo(Long.toString(version.getId())); assertThat(inserted.getContentDigest()).isEqualTo("entity-v1-" + version.getId()); assertThat(inserted.getDigestSchemaVersion()).isEqualTo(1); + assertThat(inserted.getRecordedAt()).isEqualTo(SOURCE_RECORDED_AT); + assertThat(inserted.getLastVerifiedAt()).isEqualTo(SOURCE_LAST_VERIFIED_AT); } @Test From af5e197dfd8b62701afd82fb612c7ad6a8d20303 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 26 Sep 2026 17:50:22 +1200 Subject: [PATCH 07/28] Read back generated audit identity and SQL timestamps --- ...igestBaselineMigrationAuditRepository.java | 35 ++++++++++++++++--- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/EntityDigestBaselineMigrationAuditRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/EntityDigestBaselineMigrationAuditRepository.java index b32c9c8b13..8f8a81b941 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/EntityDigestBaselineMigrationAuditRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/EntityDigestBaselineMigrationAuditRepository.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.Optional; import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; @@ -110,9 +111,19 @@ public EntityDigestBaselineMigrationAudit insert(EntityDigestBaselineMigrationAu .set(WORKLOAD_IDENTITY, audit.workloadIdentity()) .set(OUTCOME, audit.outcome()) .set(COMMITTED_AT, audit.committedAt()) - .returning() + .returning(ID) .fetchOne(); - return toEntity(record); + Long id = record == null ? null : record.get(ID); + if (id == null || id < 1) { + throw new IllegalStateException("Entity baseline migration audit insert returned no row ID"); + } + EntityDigestBaselineMigrationAudit persisted = + findByOperationId(audit.operationId()) + .orElseThrow(() -> new IllegalStateException("inserted migration audit is missing")); + if (!id.equals(persisted.id())) { + throw new IllegalStateException("inserted migration audit ID does not match readback"); + } + return persisted; } /** Resolves a prior operation by its stable id for exact retry and readback. */ @@ -184,9 +195,9 @@ private EntityDigestBaselineMigrationAudit toEntity(Record record) { record.get(SOURCE_CONTENT_DIGEST), record.get(SOURCE_DIGEST_SCHEMA_VERSION), record.get(SOURCE_RECORDED_FROM_WORKFLOW_ID), - record.get(SOURCE_RECORDED_AT), + toLocalDateTime(record, SOURCE_RECORDED_AT), record.get(SOURCE_LAST_VERIFIED_WORKFLOW_ID), - record.get(SOURCE_LAST_VERIFIED_AT), + toLocalDateTime(record, SOURCE_LAST_VERIFIED_AT), record.get(OBSERVED_TENANT_ID), PublishType.valueOf(record.get(OBSERVED_PUBLISH_TYPE)), PublishParticipantKey.valueOf(record.get(OBSERVED_PARTICIPANT_KEY)), @@ -198,6 +209,20 @@ private EntityDigestBaselineMigrationAudit toEntity(Record record) { record.get(ACTOR_IDENTITY), record.get(WORKLOAD_IDENTITY), record.get(OUTCOME), - record.get(COMMITTED_AT)); + toLocalDateTime(record, COMMITTED_AT)); + } + + private LocalDateTime toLocalDateTime(Record record, Field field) { + Object value = record.get(field); + if (value == null) { + return null; + } + if (value instanceof LocalDateTime localDateTime) { + return localDateTime; + } + if (value instanceof Timestamp timestamp) { + return timestamp.toLocalDateTime(); + } + throw new IllegalStateException("unexpected timestamp type for " + field.getName()); } } From 995de9685e0e47cee285e6d29422d3d33ceedce4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 28 Sep 2026 10:14:25 +1300 Subject: [PATCH 08/28] Wire baseline migration Job to runtime Jackson mapper --- ...ntityDigestBaselineMigrationJobRunner.java | 2 +- ...yDigestBaselineMigrationJobRunnerTest.java | 45 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java index cea39c5387..c17bf71b94 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.gamedesign.maintenance; -import com.fasterxml.jackson.databind.ObjectMapper; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.InputStream; import java.nio.file.Files; @@ -18,6 +17,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import tools.jackson.databind.ObjectMapper; /** Trusted, one-shot entry point; no HTTP, gRPC server, or user-JWT mutation route is exposed. */ @Component diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java index b20e14109d..631eab04ec 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java @@ -1,12 +1,27 @@ package net.firedevops.firemud.gamedesign.maintenance; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService; import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.jackson.autoconfigure.JacksonAutoConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import tools.jackson.databind.ObjectMapper; class EntityDigestBaselineMigrationJobRunnerTest { + private final ApplicationContextRunner contextRunner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) + .withUserConfiguration(MigrationRunnerConfiguration.class); + private static final GrpcPeerIdentity MIGRATOR = new GrpcPeerIdentity( "spiffe://firemud/ns/dev/sa/game-design-baseline-migrator", @@ -57,4 +72,34 @@ void rejectsWrongTargetServiceAccountAndCertificateIdentity() { "game-design-baseline-migrator"))) .isInstanceOf(IllegalStateException.class); } + + @Test + void constructsWithTheRuntimeMapperWhenMigrationIsEnabled() { + contextRunner + .withPropertyValues("firemud.entity-baseline-migration.enabled=true") + .run( + context -> { + assertThat(context).hasSingleBean(EntityDigestBaselineMigrationJobRunner.class); + assertThat(context).hasSingleBean(ObjectMapper.class); + assertThat(context).hasSingleBean(EntityDigestBaselineMigrationService.class); + }); + } + + @Test + void doesNotCreateTheRunnerWhenMigrationIsDisabled() { + contextRunner + .withPropertyValues("firemud.entity-baseline-migration.enabled=false") + .run( + context -> + assertThat(context).doesNotHaveBean(EntityDigestBaselineMigrationJobRunner.class)); + } + + @Configuration(proxyBeanMethods = false) + @Import(EntityDigestBaselineMigrationJobRunner.class) + static class MigrationRunnerConfiguration { + @Bean + EntityDigestBaselineMigrationService migrationService() { + return mock(EntityDigestBaselineMigrationService.class); + } + } } From a0ed6570daa95e0d7f88c7ec39efdb09cea85bb9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 04:04:23 +1300 Subject: [PATCH 09/28] Tighten Entity v2 digest and baseline migration proof --- .../api-contracts.md | 4 +- .../runtime-and-data.md | 2 +- ...nsure-standalone-transport-certificates.sh | 16 ++++ ...ndalone-transport-certificates-contract.sh | 24 ++++- .../EntityDraftDesignDigestServiceImpl.java | 36 ++++++- ...ntityDraftDesignDigestServiceImplTest.java | 95 +++++++++++++++++++ .../EntityDigestBaselineMigrationService.java | 2 +- ...ityDigestBaselineMigrationServiceTest.java | 36 +++++++ 8 files changed, 207 insertions(+), 8 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 326145f3cd..d6db87e4b0 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -81,7 +81,7 @@ Implementation Notes: - The current implementation hashes the version-scoped entity-definition rows for the requested `(tenantId, versionId)` and returns synthetic `appliedCommitId = "version:"` until the later applied-revision ledger lands. - Current version-scoped digest inputs include `items`, `npcs`, and `crafting_recipes`; later entity-template families must join this same `(tenantId, versionId)` digest contract when introduced. -- The current item projection includes optional `equipmentSlotGroupKey`, normalized like runtime equipment admission (null/blank to empty; otherwise trim and uppercase), and reports `digestSchemaVersion=2`. Focused producer proof covers normalized equivalents, distinct slot-group constraints, and tenant/version-scoped reads; Game Design's publish gate accepts Entity v2 and rejects v1 or unsupported evidence. Previously recorded v1 evidence still requires affected-scope replay or recomputation, re-recording, and readback before publish; this code change does not perform a live-data migration. +- The current item projection includes optional `equipmentSlot` and `equipmentSlotGroupKey`, normalized like runtime equipment admission (null/blank to empty; otherwise trim and uppercase), and optional `effectPayloadJson`, canonicalized as parsed JSON with recursively stable object-key ordering (null/blank to empty; malformed nonblank JSON fails closed). It reports `digestSchemaVersion=2`. Focused producer proof covers normalized slot and slot-group equivalents, distinct slot and slot-group constraints, equivalent and distinct effect payloads, malformed payload rejection, and tenant/version-scoped reads; Game Design's publish gate accepts Entity v2 and rejects v1 or unsupported evidence. Previously recorded v1 evidence still requires affected-scope replay or recomputation, re-recording, and readback before publish; this code change does not perform a live-data migration. - Included objects: - version-scoped entity-template tables such as item, NPC, equipment, loot-table, and balance-curve definitions keyed by `(tenantId, versionId)`; @@ -93,7 +93,7 @@ Implementation Notes: - Canonicalization rules: - serialize included relations in stable table order, then primary-key order; - include only semantic fields plus stable identifiers referenced cross-service; - - normalize encoded structured fields before hashing. + - normalize encoded structured fields before hashing; for `effectPayloadJson`, parse nonblank JSON and serialize nested objects with stable lexicographic key ordering, failing closed on malformed nonblank JSON. - `digestSchemaVersion` must increment whenever included objects, semantic field selection, or serialization semantics change. For this manifest, once `v2` is deployed, `v1` is unsupported. The schema bump invalidates previously recorded participant evidence for the affected scope: publish/reconciliation must not compare a new-schema digest with a recorded `v1` digest, and Entity must reject a requested or reported unsupported version until the compatible canonicalization is deployed. The migration must explicitly replay or recompute each affected `(tenantId, versionId)` digest, re-record its `appliedCommitId`, digest, and schema version, and provide readback proof before the publish gate accepts the new version; it must not silently reinterpret or migrate old hashes in place. Publish gating must fail closed if Entity Management cannot attest a digest consistent with this manifest. diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 343f07ea42..7fb4fe27f2 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -19,7 +19,7 @@ This document defines Entity Management’s runtime model, persistence ownership - The live Entity schema does not yet represent the target namespace-stable identity for durable S1/S2 state: `characters` and `actor_resource_states` retain legacy `playable_state_key`, while `inventory`, `character_friend`, `character_equipment`, and durable holder/containment rows omit `playableStateNamespaceId` (and some omit `tenant_id` entirely). The current repositories consequently cannot enforce the target `{tenantId, playableStateNamespaceId, domainObjectId}` identity at the SQL boundary. A convergent migration, legacy-row disposition/backfill evidence, namespace-aware repository predicates, and focused isolation proof remain required; until those are complete, legacy `playable_state_key` rows (including `character_friend` associations reached through them) are not namespace-isolated proof and cutover readers must not treat them as namespace-backed survivor state. This does not change the target contract above. - The live `item_stacks` uniqueness constraint includes nullable holder columns, so PostgreSQL can accept duplicate rows for the same tenant/holder/item/fingerprint when another holder column is `NULL`. Inventory and container mutation paths still use find-then-create/save rather than an atomic conflict-safe operation. With no explicit `stackFamilyKey`, source resolution rejects more than one candidate row; with an explicit family key, the current implementation selects the first matching row and does not reject duplicate matches. Target resolution must enforce exactly one matching stack (or fail closed), alongside holder-kind-specific uniqueness or normalized non-null identity, atomic upsert/locking, and concurrent proof. - The current `characterGraph` helper caches `getWithInventory(characterId)` by character ID alone with a TTL and performs no namespace or authoritative version validation. It is not the target namespace-qualified Class A `character-cache:*` contract; until that contract is implemented and proved, this cache is not correctness authority. -- `EntityDraftDesignDigestServiceImpl` now emits `digestSchemaVersion=2` and hashes normalized item `equipmentSlotGroupKey`, matching `EquipmentServiceImpl` slot compatibility admission. Focused tests cover equivalent optional-key spellings, distinct slot-group constraints, and tenant/version-scoped reads; Game Design's publish gate requires Entity v2 and rejects v1. Existing v1 participant baselines remain invalid: affected `(tenantId, versionId)` evidence must be replayed or recomputed, re-recorded with its applied commit/digest/schema, and read back before publish. No live baseline migration or cross-service publish proof is claimed by this slice. +- `EntityDraftDesignDigestServiceImpl` now emits `digestSchemaVersion=2`, hashes normalized item `equipmentSlot` and `equipmentSlotGroupKey` to match runtime equipment admission, and canonicalizes nonblank item `effectPayloadJson` as parsed JSON with recursively stable object-key ordering; malformed nonblank JSON fails closed. Focused tests cover equivalent optional-key spellings, normalized slot and slot-group equivalents, distinct slot and slot-group constraints, equivalent and distinct effect payloads, malformed payload rejection, and tenant/version-scoped reads; Game Design's publish gate requires Entity v2 and rejects v1. Existing v1 participant baselines remain invalid: affected `(tenantId, versionId)` evidence must be replayed or recomputed, re-recorded with its applied commit/digest/schema, and read back before publish. No live baseline migration or cross-service publish proof is claimed by this slice. ## Architecture and Design Notes diff --git a/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh b/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh index 688ad78618..c0bcd94b32 100755 --- a/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh +++ b/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh @@ -213,8 +213,24 @@ verify_migrator_secret() { chmod 700 "$temp_dir" trap 'rm -rf -- "$temp_dir"' RETURN jq -r '.data["tls.crt"]' <<<"$secret_json" | base64 --decode >"$temp_dir/tls.crt" + if ! jq -r '.data["tls.key"]' <<<"$secret_json" | base64 --decode >"$temp_dir/tls.key"; then + echo "Secret/${migrator_secret} private key is not valid base64." >&2 + return 1 + fi jq -r '.data["ca.crt"]' <<<"$secret_json" | base64 --decode >"$temp_dir/ca.crt" base64 --decode <<<"$trusted_ca_data" >"$temp_dir/trusted-ca.crt" + if ! openssl pkey -in "$temp_dir/tls.key" -passin pass: -pubout -outform DER \ + -out "$temp_dir/key-public.der" >/dev/null 2>&1 || + ! openssl x509 -in "$temp_dir/tls.crt" -pubkey -noout >"$temp_dir/leaf-public.pem" 2>/dev/null || + ! openssl pkey -pubin -in "$temp_dir/leaf-public.pem" -outform DER \ + -out "$temp_dir/leaf-public.der" >/dev/null 2>&1; then + echo "Secret/${migrator_secret} private key or leaf certificate has invalid public material." >&2 + return 1 + fi + if ! cmp -s "$temp_dir/key-public.der" "$temp_dir/leaf-public.der"; then + echo "Secret/${migrator_secret} private key does not match its leaf certificate." >&2 + return 1 + fi if ! openssl verify -CAfile "$temp_dir/ca.crt" "$temp_dir/tls.crt" >/dev/null; then echo "Secret/${migrator_secret} leaf does not verify against its projected CA." >&2 return 1 diff --git a/dev-tools/tests/preview-standalone-transport-certificates-contract.sh b/dev-tools/tests/preview-standalone-transport-certificates-contract.sh index e5adfc7ffd..daa7e69cd4 100755 --- a/dev-tools/tests/preview-standalone-transport-certificates-contract.sh +++ b/dev-tools/tests/preview-standalone-transport-certificates-contract.sh @@ -283,8 +283,9 @@ openssl x509 -req -in "$TEMP_DIR/leaf.csr" -CA "$TEMP_DIR/ca.crt" \ jq -n \ --arg name firemud-grpc-game-design-baseline-migrator \ --arg leaf "$(base64 -w0 "$TEMP_DIR/leaf.crt")" \ + --arg key "$(base64 -w0 "$TEMP_DIR/leaf.key")" \ --arg ca "$(base64 -w0 "$TEMP_DIR/ca.crt")" \ - '{metadata:{name:$name},type:"kubernetes.io/tls",data:{"tls.crt":$leaf,"tls.key":"c2VjcmV0","ca.crt":$ca}}' \ + '{metadata:{name:$name},type:"kubernetes.io/tls",data:{"tls.crt":$leaf,"tls.key":$key,"ca.crt":$ca}}' \ >"$TEMP_DIR/migrator-secret.json" PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ FAKE_KUBECTL_SECRET_JSON="$TEMP_DIR/migrator-secret.json" \ @@ -306,11 +307,30 @@ openssl req -new -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/wrong-leaf.key" \ openssl x509 -req -in "$TEMP_DIR/wrong-leaf.csr" -CA "$TEMP_DIR/ca.crt" \ -CAkey "$TEMP_DIR/ca.key" -CAcreateserial -days 1 -copy_extensions copy \ -out "$TEMP_DIR/wrong-leaf.crt" >/dev/null 2>&1 +jq -n \ + --arg name firemud-grpc-game-design-baseline-migrator \ + --arg leaf "$(base64 -w0 "$TEMP_DIR/leaf.crt")" \ + --arg key "$(base64 -w0 "$TEMP_DIR/wrong-leaf.key")" \ + --arg ca "$(base64 -w0 "$TEMP_DIR/ca.crt")" \ + '{metadata:{name:$name},type:"kubernetes.io/tls",data:{"tls.crt":$leaf,"tls.key":$key,"ca.crt":$ca}}' \ + >"$TEMP_DIR/wrong-key-migrator-secret.json" +if PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + FAKE_KUBECTL_SECRET_JSON="$TEMP_DIR/wrong-key-migrator-secret.json" \ + FAKE_KUBECTL_TRUST_CA="$TEMP_DIR/ca.crt" \ + "$SCRIPT" --verify-migrator dev >"$TEMP_DIR/wrong-key-migrator.out" \ + 2>"$TEMP_DIR/wrong-key-migrator.err"; then + echo "migrator verifier accepted a private key that does not match its leaf certificate" >&2 + exit 1 +fi +grep -Fq 'private key does not match its leaf certificate' \ + "$TEMP_DIR/wrong-key-migrator.err" + jq -n \ --arg name firemud-grpc-game-design-baseline-migrator \ --arg leaf "$(base64 -w0 "$TEMP_DIR/wrong-leaf.crt")" \ + --arg key "$(base64 -w0 "$TEMP_DIR/wrong-leaf.key")" \ --arg ca "$(base64 -w0 "$TEMP_DIR/ca.crt")" \ - '{metadata:{name:$name},type:"kubernetes.io/tls",data:{"tls.crt":$leaf,"tls.key":"c2VjcmV0","ca.crt":$ca}}' \ + '{metadata:{name:$name},type:"kubernetes.io/tls",data:{"tls.crt":$leaf,"tls.key":$key,"ca.crt":$ca}}' \ >"$TEMP_DIR/wrong-migrator-secret.json" if PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ FAKE_KUBECTL_SECRET_JSON="$TEMP_DIR/wrong-migrator-secret.json" \ diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java index a8d9a6936b..da75590cd3 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java @@ -14,6 +14,7 @@ import net.firedevops.firemud.entitymanagement.repository.NpcRepository; import net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService; import org.springframework.stereotype.Service; +import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.SerializationFeature; @@ -64,7 +65,9 @@ public EntityDraftDesignDigest getDraftDesignDigest(String tenantId, String vers Map.entry("id", item.getId()), Map.entry("name", item.getName()), Map.entry("description", value(item.getDescription())), - Map.entry("equipmentSlot", value(item.getEquipmentSlot())), + Map.entry( + "equipmentSlot", + normalizeOptionalKey(item.getEquipmentSlot())), Map.entry( "equipmentSlotGroupKey", normalizeOptionalKey(item.getEquipmentSlotGroupKey())), @@ -76,7 +79,8 @@ public EntityDraftDesignDigest getDraftDesignDigest(String tenantId, String vers Map.entry( "stackVariantKey", value(item.getStackVariantKey())), Map.entry( - "effectPayloadJson", value(item.getEffectPayloadJson())))) + "effectPayloadJson", + canonicalizeOptionalJson(item.getEffectPayloadJson())))) .toList(), "npcs", npcRepository @@ -139,6 +143,34 @@ private String normalizeOptionalKey(String value) { return value == null || value.isBlank() ? "" : value.trim().toUpperCase(Locale.ROOT); } + private String canonicalizeOptionalJson(String value) { + if (value == null || value.isBlank()) { + return ""; + } + try { + return objectMapper.writeValueAsString(canonicalizeJsonNode(objectMapper.readTree(value))); + } catch (Exception ex) { + throw new IllegalStateException("effectPayloadJson is not valid JSON", ex); + } + } + + private JsonNode canonicalizeJsonNode(JsonNode node) { + if (node == null || node.isNull() || node.isValueNode()) { + return node; + } + if (node.isObject()) { + var canonicalObject = objectMapper.createObjectNode(); + node.properties().stream() + .sorted(Map.Entry.comparingByKey()) + .forEach( + entry -> canonicalObject.set(entry.getKey(), canonicalizeJsonNode(entry.getValue()))); + return canonicalObject; + } + var canonicalArray = objectMapper.createArrayNode(); + node.valueStream().map(this::canonicalizeJsonNode).forEach(canonicalArray::add); + return canonicalArray; + } + private String sha256(String value) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java index 53e0423e42..2d8766b548 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java @@ -90,6 +90,61 @@ void equipmentSlotGroupConstraintChangesTheDigest() { assertNotEquals(wingsDigest.contentDigest(), torsoDigest.contentDigest()); } + @Test + void canonicalizesEquivalentEquipmentSlotValues() { + var spacedDigest = digestForEquipmentSlot(" head "); + var normalizedDigest = digestForEquipmentSlot("HEAD"); + + assertEquals(spacedDigest.contentDigest(), normalizedDigest.contentDigest()); + } + + @Test + void distinctEquipmentSlotValuesChangeTheDigest() { + var headDigest = digestForEquipmentSlot("HEAD"); + var torsoDigest = digestForEquipmentSlot("TORSO"); + + assertNotEquals(headDigest.contentDigest(), torsoDigest.contentDigest()); + } + + @Test + void canonicalizesEquivalentEffectPayloadJson() { + var firstDigest = + digestForEffectPayload( + "{\"modifiers\":[{\"operation\":\"ADD\",\"target_key\":\"health\"," + + "\"value\":1,\"metadata\":{\"b\":2,\"a\":1}}]}"); + var equivalentDigest = + digestForEffectPayload( + " { \"modifiers\" : [ { \"metadata\" : { \"a\" : 1, \"b\" : 2 }," + + " \"value\" : 1, \"target_key\" : \"health\", \"operation\" : \"ADD\" } ] } "); + + assertEquals(firstDigest.contentDigest(), equivalentDigest.contentDigest()); + } + + @Test + void distinctEffectPayloadJsonChangesTheDigest() { + var addDigest = + digestForEffectPayload( + "{\"modifiers\":[{\"operation\":\"ADD\",\"target_key\":\"health\",\"value\":1}]}"); + var subtractDigest = + digestForEffectPayload( + "{\"modifiers\":[{\"operation\":\"SUBTRACT\",\"target_key\":\"health\",\"value\":1}]}"); + + assertNotEquals(addDigest.contentDigest(), subtractDigest.contentDigest()); + } + + @Test + void rejectsMalformedNonBlankEffectPayloadJson() { + assertThrows(IllegalStateException.class, () -> digestForEffectPayload("{\"modifiers\":[}")); + } + + @Test + void normalizesMissingAndBlankEffectPayloadJsonToTheSameDigest() { + var missingDigest = digestForEffectPayload(null); + var blankDigest = digestForEffectPayload(" \t "); + + assertEquals(missingDigest.contentDigest(), blankDigest.contentDigest()); + } + @Test void readsItemsWithinTheRequestedTenantAndVersion() { ItemRepository itemRepository = Mockito.mock(ItemRepository.class); @@ -146,6 +201,46 @@ private static EntityDraftDesignDigest digestForEquipmentSlotGroupKey(String gro return service.getDraftDesignDigest("1", "7"); } + private static EntityDraftDesignDigest digestForEffectPayload(String effectPayloadJson) { + Item item = item(11L, null); + item.setEffectPayloadJson(effectPayloadJson); + ItemRepository itemRepository = Mockito.mock(ItemRepository.class); + NpcRepository npcRepository = Mockito.mock(NpcRepository.class); + CraftingRecipeRepository craftingRecipeRepository = + Mockito.mock(CraftingRecipeRepository.class); + Mockito.when(itemRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of(item)); + Mockito.when(npcRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of()); + Mockito.when(craftingRecipeRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of()); + EntityDraftDesignDigestServiceImpl service = + new EntityDraftDesignDigestServiceImpl( + itemRepository, npcRepository, craftingRecipeRepository, new ObjectMapper()); + + return service.getDraftDesignDigest("1", "7"); + } + + private static EntityDraftDesignDigest digestForEquipmentSlot(String equipmentSlot) { + Item item = item(11L, null); + item.setEquipmentSlot(equipmentSlot); + ItemRepository itemRepository = Mockito.mock(ItemRepository.class); + NpcRepository npcRepository = Mockito.mock(NpcRepository.class); + CraftingRecipeRepository craftingRecipeRepository = + Mockito.mock(CraftingRecipeRepository.class); + Mockito.when(itemRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of(item)); + Mockito.when(npcRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of()); + Mockito.when(craftingRecipeRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of()); + EntityDraftDesignDigestServiceImpl service = + new EntityDraftDesignDigestServiceImpl( + itemRepository, npcRepository, craftingRecipeRepository, new ObjectMapper()); + + return service.getDraftDesignDigest("1", "7"); + } + private static Item item(Long id, String equipmentSlotGroupKey) { Item item = new Item(); item.setId(id); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java index e975be9d4d..7a9de48b11 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java @@ -468,7 +468,7 @@ private boolean sameAuditTarget( && Objects.equals(actual.actorIdentity(), expected.actorIdentity()) && Objects.equals(actual.workloadIdentity(), expected.workloadIdentity()) && Objects.equals(actual.outcome(), expected.outcome()) - && Objects.equals(actual.committedAt(), expected.committedAt()); + && actual.committedAt() != null; } private BaselineSummary toV1Summary(RecordedParticipantDigest row) { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java index 1246b2adc4..6fb639538f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -307,6 +308,41 @@ void uncertainWriterOutcomeSucceedsOnlyWhenExactCommittedReadbackIsFound() { assertEquals(AUDIT_ID, result.auditId()); } + @Test + void guardedWriteLoserRecoversFromWinnerAuditWithDifferentCommittedAt() { + RecordedParticipantDigest migrated = migratedBaseline("v2-content", "version:42"); + EntityDigestBaselineMigrationAudit winnerAudit = audit(source, migrated, AUDIT_ID, auditTime()); + AtomicReference attemptedAudit = new AtomicReference<>(); + EntityDigestBaselineMigrationWriteService writer = + org.mockito.Mockito.mock(EntityDigestBaselineMigrationWriteService.class); + org.mockito.Mockito.doAnswer( + invocation -> { + attemptedAudit.set(invocation.getArgument(2)); + throw new IllegalStateException("guarded migration lost race"); + }) + .when(writer) + .commit(any(), any(), any()); + when(auditRepository.findByOperationId(OPERATION_ID)) + .thenReturn(Optional.empty(), Optional.of(winnerAudit)); + when(baselineRepository.findById(BASELINE_ID)) + .thenReturn(Optional.of(source), Optional.of(migrated)); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(source)); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + when(entityManagementClient.getDraftDesignDigestForVersion(any())) + .thenReturn(v2Digest("v2-content", "version:42")); + + EntityDigestBaselineMigrationService.MigrationResult result = service(writer).migrate(command); + + assertEquals( + EntityDigestBaselineMigrationService.MigrationDisposition.RECOVERED_AFTER_WRITE_ERROR, + result.disposition()); + assertEquals(AUDIT_ID, result.auditId()); + assertEquals("v2-content", result.contentDigest()); + assertNotEquals(winnerAudit.committedAt(), attemptedAudit.get().committedAt()); + } + @Test void uncertainWriterOutcomeFailsWhenReadbackCannotProveBothRows() { EntityDigestBaselineMigrationWriteService writer = From e89143b64ed123f64df04ee20abbb30a32b980b6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:16:40 +1300 Subject: [PATCH 10/28] Apply scoped Entity digest formatter correction --- .../gamelogic/service/impl/GameLogicGrpcServiceTest.java | 3 +-- .../firemud/gamesession/client/GameDesignClient.java | 3 ++- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java index 550f9368f6..1647d1925a 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java @@ -326,8 +326,7 @@ void getDraftDesignDigestMapsUnexpectedUnsupportedOperationToInternalError() { GameLogicGrpcService service = newDigestService(digestService); AtomicReference response = new AtomicReference<>(); - runAsGameDesign( - () -> response.set(invokeDigest(service, fullDigestRequest("1", "7")))); + runAsGameDesign(() -> response.set(invokeDigest(service, fullDigestRequest("1", "7")))); assertTrue(response.get().hasError()); assertEquals("INTERNAL", response.get().getError().getCode()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java index 1396cfbd90..ca97ef1158 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java @@ -104,7 +104,8 @@ public GetPublishedScriptPatchVersionResponse getPublishedScriptPatchVersion( .setError( ErrorDetail.newBuilder() .setCode("INVALID_ARGUMENT") - .setMessage("base_version_id must be positive for script-patch publication lookup") + .setMessage( + "base_version_id must be positive for script-patch publication lookup") .build()) .build(); } From 62c2c42d74eac2103532d4b0b8f42fc1ee7f14c3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:41:27 +1300 Subject: [PATCH 11/28] Clarify Entity digest guard and migrator actor provenance --- .../microservices/entity-management-service/api-contracts.md | 2 +- .../microservices/game-design-service/operations.md | 2 +- k8s/helm/firemud/values.yaml | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index d6db87e4b0..a0a5ee1f81 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -71,7 +71,7 @@ Entity Management must also expose a read-only design-time synchronization surfa - `GetDraftDesignDigest(GetDraftDesignDigestRequest)` uses request shape `{tenantId, scope: oneof {versionId, scriptPatchVersion}}`. Entity Management supports `versionId` scope only and returns `UNSUPPORTED_SCOPE` otherwise. - Response returns `{tenantId, scope, appliedCommitId, contentDigest, digestSchemaVersion}` as described in [`world-editing-tools.md`](../game-design-service/world-editing-tools.md). -- Current drift: the digest handler has no owner/method authorization or exact Game Design publication binding beyond shared bearer parsing. The target workload, tenant/scope/request/workflow/digest context and denial proof are canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). +- Current implementation: the exact `GetDraftDesignDigest` method is JWT-exempt only for its mTLS-authenticated owner-to-owner call; the handler applies `PublicationReadGuard` to the caller, tenant, scope, and publication binding before returning digest evidence. The target workload, tenant/scope/request/workflow/digest context and denial contract remain canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). Live served-certificate and consumer-convergence proof is still required. ## Digest Input Manifest diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 7f22d35dce..1f15865fbb 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -34,7 +34,7 @@ The target publication boundary treats object-store export as a durable candidat Use a controlled pre-v1 publication window for the affected Entity v1 full-version scopes. Drain in-flight publication and prevent new publication on those scopes before comparing rows or deploying the writer. Deploy the migration-capable Game Design reader/reconciler image first so retained stored v1 and v2 baseline shapes can be inspected; its publish gate still requires v2 and never compares v1 content with v2 content. Then deploy Entity's v2 producer image. Because #2872 already has a v2-only gate, deploying it alone may temporarily block affected v1 publication; this is an accepted fail-closed maintenance window, not seamless dual-reader availability. Verify actual service image digests and deployment order before proceeding; if the image topology cannot maintain that sequence, stop instead of relaxing the gate. The current Entity applied-commit token is synthetic `version:` and does not prove durable applied-revision convergence. -Before invoking a Job, verify the exact Kubernetes context and namespace, the authorized operator identity and approved maintenance window, both current service image digests, database backup/recovery posture, completed in-flight publication drain, and the dedicated migrator certificate's issuer, `Ready` state, URI SAN, trust chain, projected Secret, and actual mTLS acceptance at Entity. The hosted trust/controller admission policy includes a narrow runtime-namespace exception for this identity; it does not make the migrator one of the controller's permanent certificate consumers. A trusted certificate writer must explicitly invoke `ensure-standalone-transport-certificates.sh --migrator `; a separately authorized Secret-read operator then invokes `--verify-migrator ` before the Job is enabled. The certificate writer's service account has no Secret-read permission. These opt-in operations do not alter ordinary preview transport-certificate rollout. A rendered Certificate or Secret name alone is not issuance or served-identity proof. The trusted operator must create an immutable expected-source ConfigMap or Secret from a read-only exact database row, including baseline ID, tenant, `FULL_VERSION`, `ENTITY_MANAGEMENT`, null base version, version scope, applied commit, digest, schema `1`, and both workflow IDs and timestamps. Do not place this manifest, credentials, or raw retained row values in a PR or CI artifact. Check that the source object is immutable before applying the Job. The Job's `targetNamespace`, tenant/version, operation ID, actor identity, and expected-source object are all fixed for that invocation; a changed command gets a new operation ID, never a reinterpretation of the old one. +Before invoking a Job, verify the exact Kubernetes context and namespace, the authorized operator identity and approved maintenance window, both current service image digests, database backup/recovery posture, completed in-flight publication drain, and the dedicated migrator certificate's issuer, `Ready` state, URI SAN, trust chain, projected Secret, and actual mTLS acceptance at Entity. The hosted trust/controller admission policy includes a narrow runtime-namespace exception for this identity; it does not make the migrator one of the controller's permanent certificate consumers. A trusted certificate writer must explicitly invoke `ensure-standalone-transport-certificates.sh --migrator `; a separately authorized Secret-read operator then invokes `--verify-migrator ` before the Job is enabled. The certificate writer's service account has no Secret-read permission. These opt-in operations do not alter ordinary preview transport-certificate rollout. A rendered Certificate or Secret name alone is not issuance or served-identity proof. The trusted operator must create an immutable expected-source ConfigMap or Secret from a read-only exact database row, including baseline ID, tenant, `FULL_VERSION`, `ENTITY_MANAGEMENT`, null base version, version scope, applied commit, digest, schema `1`, and both workflow IDs and timestamps. Do not place this manifest, credentials, or raw retained row values in a PR or CI artifact. Check that the source object is immutable before applying the Job. The Job's `targetNamespace`, tenant/version, operation ID, actor identity, and expected-source object are all fixed for that invocation; a changed command gets a new operation ID, never a reinterpretation of the old one. `actorIdentity` is an operator-supplied audit claim, not an identity attested by the Job's workload certificate. Preserve the trusted deployment audit identifying the authenticated human operator and correlate its Job UID, operation ID, values/image revision, and time with the Game Design before/after audit row; do not use that row alone as proof of the human operator's identity. The chart's `previewStack.entityDigestBaselineMigration` values are disabled by default. From the trusted operator revision, supply an image pinned as `repository@sha256:`, exact `targetNamespace`, the dedicated `firemud-grpc-game-design-baseline-migrator` Secret, and `mode`. `enumerate` returns at most 500 Entity schema-v1 full-version rows after one baseline ID; repeat with its returned keyset cursor until an empty page proves no more rows at the quiesced snapshot. `preflight` classifies one exact tenant/version as v1, v2, absent, ambiguous, or unsupported, and refuses a missing or script-only Version. `migrate` requires one stable operation ID, exact tenant/version, actor identity, and the immutable expected-source object. The Java runner verifies its namespace, dedicated service account, and certificate URI identity before reading or writing. A missing identity, policy, input, row, version, exact-old match, or v2 Entity response fails closed. Render and inspect the operator overlay before installation; do not leave `enabled: true` in the ordinary chart values or an unattended release upgrade. Completed Jobs are deliberately not Helm hooks, so an unchanged upgrade does not rerun them; a changed immutable Job spec is rejected and needs an explicit trusted disposition. diff --git a/k8s/helm/firemud/values.yaml b/k8s/helm/firemud/values.yaml index 468a69541b..ff338c1eae 100644 --- a/k8s/helm/firemud/values.yaml +++ b/k8s/helm/firemud/values.yaml @@ -11,6 +11,7 @@ previewStack: versionId: "" afterBaselineId: "0" limit: 100 + # Operator-supplied audit claim; correlate the Job invocation with trusted deployment audit. actorIdentity: "" image: "" expectedSource: From 9e250a9d6cecee348c0089fabb1260058ce160bc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:31:29 +1300 Subject: [PATCH 12/28] Block mutable Draft Entity baseline migration --- .../game-design-service/operations.md | 4 +- ...ame-authoring-publishing-and-activation.md | 2 +- .../repository/VersionRepository.java | 9 ++ .../EntityDigestBaselineMigrationService.java | 76 ++++++++++--- ...tyDigestBaselineMigrationWriteService.java | 27 ++++- ...igestBaselineMigrationIntegrationTest.java | 39 +++++++ ...nd_participant_digest_patch_scopeTest.java | 3 +- ...ityDigestBaselineMigrationServiceTest.java | 107 +++++++++++++++++- ...gestBaselineMigrationWriteServiceTest.java | 31 ++++- 9 files changed, 275 insertions(+), 23 deletions(-) diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 1f15865fbb..296f7914d5 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -30,13 +30,13 @@ The target publication boundary treats object-store export as a durable candidat ### Historical Entity digest baseline migration -**Current implementation status:** The one-shot Game Design maintenance Job and guarded owner-local v1→v2 baseline transition are implemented, but no retained row set or live certificate/consumer/readback outcome has been verified by this document. The Job is disabled in ordinary Helm releases and must be invoked only from a trusted operator context, using a reviewed immutable Game Design image digest. It is not a public API, a general admin role, or a PR-controlled executor. Its dedicated `game-design-baseline-migrator` Kubernetes service account has no Kubernetes API verbs, and its separate client certificate may read only Entity Management's bound `GetDraftDesignDigest` RPC. No Game Design, Account, or Game Session mutation API is delegated to that identity. The Job only writes Game Design's own baseline and audit tables through its guarded service operation; it never accesses Entity's database. +**Current implementation status:** The one-shot Game Design maintenance Job and guarded owner-local v1→v2 baseline transition are implemented, but no retained row set or live certificate/consumer/readback outcome has been verified by this document. A retained v1 scope whose authoritative Version is `DRAFT` is reported as `BLOCKED_DRAFT`; migrate rejects it before the Entity digest read and locks/rechecks Version state at the baseline-and-audit write boundary. A no-data scope, existing v2 row, ambiguous scope, or unsupported schema retains its separate preflight classification. This does not freeze live authoring. Publication quiescence drains publication work only and must not be treated as an authoring freeze or proof that DRAFT content cannot change. The Job is disabled in ordinary Helm releases and must be invoked only from a trusted operator context, using a reviewed immutable Game Design image digest. It is not a public API, a general admin role, or a PR-controlled executor. Its dedicated `game-design-baseline-migrator` Kubernetes service account has no Kubernetes API verbs, and its separate client certificate may read only Entity Management's bound `GetDraftDesignDigest` RPC. No Game Design, Account, or Game Session mutation API is delegated to that identity. The Job only writes Game Design's own baseline and audit tables through its guarded service operation; it never accesses Entity's database. Use a controlled pre-v1 publication window for the affected Entity v1 full-version scopes. Drain in-flight publication and prevent new publication on those scopes before comparing rows or deploying the writer. Deploy the migration-capable Game Design reader/reconciler image first so retained stored v1 and v2 baseline shapes can be inspected; its publish gate still requires v2 and never compares v1 content with v2 content. Then deploy Entity's v2 producer image. Because #2872 already has a v2-only gate, deploying it alone may temporarily block affected v1 publication; this is an accepted fail-closed maintenance window, not seamless dual-reader availability. Verify actual service image digests and deployment order before proceeding; if the image topology cannot maintain that sequence, stop instead of relaxing the gate. The current Entity applied-commit token is synthetic `version:` and does not prove durable applied-revision convergence. Before invoking a Job, verify the exact Kubernetes context and namespace, the authorized operator identity and approved maintenance window, both current service image digests, database backup/recovery posture, completed in-flight publication drain, and the dedicated migrator certificate's issuer, `Ready` state, URI SAN, trust chain, projected Secret, and actual mTLS acceptance at Entity. The hosted trust/controller admission policy includes a narrow runtime-namespace exception for this identity; it does not make the migrator one of the controller's permanent certificate consumers. A trusted certificate writer must explicitly invoke `ensure-standalone-transport-certificates.sh --migrator `; a separately authorized Secret-read operator then invokes `--verify-migrator ` before the Job is enabled. The certificate writer's service account has no Secret-read permission. These opt-in operations do not alter ordinary preview transport-certificate rollout. A rendered Certificate or Secret name alone is not issuance or served-identity proof. The trusted operator must create an immutable expected-source ConfigMap or Secret from a read-only exact database row, including baseline ID, tenant, `FULL_VERSION`, `ENTITY_MANAGEMENT`, null base version, version scope, applied commit, digest, schema `1`, and both workflow IDs and timestamps. Do not place this manifest, credentials, or raw retained row values in a PR or CI artifact. Check that the source object is immutable before applying the Job. The Job's `targetNamespace`, tenant/version, operation ID, actor identity, and expected-source object are all fixed for that invocation; a changed command gets a new operation ID, never a reinterpretation of the old one. `actorIdentity` is an operator-supplied audit claim, not an identity attested by the Job's workload certificate. Preserve the trusted deployment audit identifying the authenticated human operator and correlate its Job UID, operation ID, values/image revision, and time with the Game Design before/after audit row; do not use that row alone as proof of the human operator's identity. -The chart's `previewStack.entityDigestBaselineMigration` values are disabled by default. From the trusted operator revision, supply an image pinned as `repository@sha256:`, exact `targetNamespace`, the dedicated `firemud-grpc-game-design-baseline-migrator` Secret, and `mode`. `enumerate` returns at most 500 Entity schema-v1 full-version rows after one baseline ID; repeat with its returned keyset cursor until an empty page proves no more rows at the quiesced snapshot. `preflight` classifies one exact tenant/version as v1, v2, absent, ambiguous, or unsupported, and refuses a missing or script-only Version. `migrate` requires one stable operation ID, exact tenant/version, actor identity, and the immutable expected-source object. The Java runner verifies its namespace, dedicated service account, and certificate URI identity before reading or writing. A missing identity, policy, input, row, version, exact-old match, or v2 Entity response fails closed. Render and inspect the operator overlay before installation; do not leave `enabled: true` in the ordinary chart values or an unattended release upgrade. Completed Jobs are deliberately not Helm hooks, so an unchanged upgrade does not rerun them; a changed immutable Job spec is rejected and needs an explicit trusted disposition. +The chart's `previewStack.entityDigestBaselineMigration` values are disabled by default. From the trusted operator revision, supply an image pinned as `repository@sha256:`, exact `targetNamespace`, the dedicated `firemud-grpc-game-design-baseline-migrator` Secret, and `mode`. `enumerate` returns at most 500 Entity schema-v1 full-version rows after one baseline ID and reports each scope's migration status, including `BLOCKED_DRAFT`; repeat with its returned keyset cursor until an empty page proves no more rows at the quiesced snapshot. `preflight` classifies one exact tenant/version as v1, v2, absent, ambiguous, unsupported, or `BLOCKED_DRAFT`, and refuses a missing or script-only Version. `migrate` requires one stable operation ID, exact tenant/version, actor identity, and the immutable expected-source object. It rejects a DRAFT Version before reading the Entity digest and locks/rechecks the Version row in the same transaction as the guarded baseline update and audit insertion, closing the state-change race at that write boundary. This guard does not freeze authoring while the external digest is read. The Java runner verifies its namespace, dedicated service account, and certificate URI identity before reading or writing. A missing identity, policy, input, row, version, exact-old match, or v2 Entity response fails closed. Render and inspect the operator overlay before installation; do not leave `enabled: true` in the ordinary chart values or an unattended release upgrade. Completed Jobs are deliberately not Helm hooks, so an unchanged upgrade does not rerun them; a changed immutable Job spec is rejected and needs an explicit trusted disposition. For each affected scope, retain the preflight row ID and complete source tuple privately, run `migrate`, and require its reported operation/audit/baseline IDs and disposition. The Game Design transaction conditionally replaces the exact old row and inserts an immutable before/after audit atomically. The live row retains its original and last real publish-workflow IDs and timestamps; only the audit's operation ID and committed time describe the maintenance transition. An exact retry of the same operation reads the existing audit and baseline rather than writing again; a lost acknowledgement is resolved by that same operation identity and exact readback. A changed source, ambiguous scope, different actor/workload binding, mismatched Entity v2 schema/scope/digest/commit, or unproved write outcome is a stop condition. Independently read back `publish_recorded_participant_digest` by baseline ID and `entity_digest_baseline_migration_audit` by operation ID from Game Design's PostgreSQL schema; compare the new schema/digest/commit and preserved publish provenance, complete old tuple, observed v2 tuple, migration operation, actor/workload, outcome, and timestamp exactly. Never count Job completion alone as database proof. Keep the before/after records with the private migration log, excluding secrets and certificate keys. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 5cddf2025b..6543441ad0 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -22,7 +22,7 @@ AR-1.5 full-version publication now reserves its Draft version and PENDING attem The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open arbitrary `CompareAndSetVersionState` transition gap recorded below. -`AR-3.2` Entity digest-schema catch-up now has a dedicated historical-baseline migration path in the Game Design owner: bounded v1 full-version enumeration, exact tenant/version and expected-old preflight, v2 Entity recomputation, atomic guarded baseline/audit write, and exact persisted readback/retry. It is a protected one-shot Job, not ordinary publication or a public operator API. This code and its synthetic test rows do not prove that deployed retained v1 rows were migrated or that the live scoped row set is empty. The controlled readers-first publication window, dedicated migrator certificate issuance, live PostgreSQL readback, and later review remain rollout gates; Entity's `version:` commit token still does not prove applied-revision convergence. Keep the capability partial until those boundaries have actual evidence. +`AR-3.2` Entity digest-schema catch-up now has a dedicated historical-baseline migration path in the Game Design owner: bounded v1 full-version enumeration, exact tenant/version and expected-old preflight, v2 Entity recomputation, atomic guarded baseline/audit write, and exact persisted readback/retry. Retained v1 scopes whose Version is mutable `DRAFT` are reported `BLOCKED_DRAFT`; migrate rejects them before the Entity digest read and locks/rechecks Version state at its guarded write boundary. This one-shot guard does not freeze authoring, and publication quiescence is not an authoring freeze. It is a protected one-shot Job, not ordinary publication or a public operator API. This code and its synthetic test rows do not prove that deployed retained v1 rows were migrated or that the live scoped row set is empty. The controlled readers-first publication window, dedicated migrator certificate issuance, live PostgreSQL readback, and later review remain rollout gates; Entity's `version:` commit token still does not prove applied-revision convergence. Keep the capability partial until those boundaries have actual evidence. Asset lifecycle status remains partial: publication and artifact services provide the current bounded release-bundle and asset-storage seams, but the destructive lifecycle operations (`TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets`) still lack proved durable operation handling and owner-local epoch/CAS protection. `BeginPurgeVersionAssets` currently mints a random workflow identity, and artifact and Version saves lack DB epoch predicates/affected-row proof. The canonical lifecycle and operation contract is owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status), with [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) providing provenance. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java index 9d41b7a252..5fba18a82c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java @@ -79,6 +79,15 @@ public Optional findByTenantIdAndId(String tenantId, Long id) { .fetchOne(this::toEntity)); } + /** Reads and locks the exact version row for owner-local guarded lifecycle writes. */ + public Optional findByTenantIdAndIdForUpdate(String tenantId, Long id) { + return Optional.ofNullable( + dsl.selectFrom(VERSION_TABLE) + .where(TENANT_ID.eq(tenantId).and(ID.eq(id))) + .forUpdate() + .fetchOne(this::toEntity)); + } + /** * Returns every published script-patch candidate for an exact tenant/base/patch scope. Callers * reject anything other than one row so duplicate retained scope is fail-closed. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java index 7a9de48b11..eda2c44c58 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java @@ -18,6 +18,7 @@ import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.repository.EntityDigestBaselineMigrationAuditRepository; import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; @@ -117,14 +118,36 @@ public ScopePreflight preflightScope(String tenantId, long versionId) { } else { status = ScopeStatus.UNSUPPORTED_SCHEMA; } + if (rows.size() == 1 + && Objects.equals(rows.get(0).getDigestSchemaVersion(), SOURCE_SCHEMA_VERSION) + && version.getVersionState() == VersionLifecycleState.DRAFT) { + status = ScopeStatus.BLOCKED_DRAFT; + } + ScopeStatus reportedStatus = status; return new ScopePreflight( - tenantId, versionId, status, rows.stream().map(this::toSummary).toList()); + tenantId, + versionId, + status, + rows.stream().map(row -> toSummary(row, summaryStatus(row, reportedStatus))).toList()); } /** Recomputes and atomically re-records one exact Entity full-version v1 baseline. */ public MigrationResult migrate(MigrationCommand command) { validateCommand(command); + Version version = + versionRepository + .findByTenantIdAndId(command.tenantId(), command.versionId()) + .orElseThrow(() -> rejected("VERSION_MISSING", "tenant/version does not exist")); + if (!Objects.equals(version.getTenantId(), command.tenantId()) + || !Objects.equals(version.getId(), command.versionId()) + || version.isScriptOnly()) { + throw rejected("VERSION_SCOPE_MISMATCH", "version is outside the tenant or is script-only"); + } + if (version.getVersionState() == VersionLifecycleState.DRAFT) { + throw rejected("VERSION_DRAFT", "mutable DRAFT versions cannot be migrated"); + } + Optional priorAudit = auditRepository.findByOperationId(command.operationId()); if (priorAudit.isPresent()) { @@ -152,16 +175,6 @@ public MigrationResult migrate(MigrationCommand command) { } assertSourceMatchesCommand(current, command.expectedSource()); - Version version = - versionRepository - .findByTenantIdAndId(command.tenantId(), command.versionId()) - .orElseThrow(() -> rejected("VERSION_MISSING", "tenant/version does not exist")); - if (!Objects.equals(version.getTenantId(), command.tenantId()) - || !Objects.equals(version.getId(), command.versionId()) - || version.isScriptOnly()) { - throw rejected("VERSION_SCOPE_MISMATCH", "version is outside the tenant or is script-only"); - } - PublicationDigestRequestBinding binding = PublicationDigestRequestBinding.full( command.tenantId(), @@ -176,6 +189,11 @@ public MigrationResult migrate(MigrationCommand command) { EntityDigestBaselineMigrationAudit audit = auditFor(current, observed, command, migrationTime); try { writeService.commit(current, replacement, audit); + } catch (EntityDigestBaselineMigrationWriteService.DraftVersionException draftAtCommit) { + throw rejected( + "VERSION_DRAFT", + "version became DRAFT before the guarded migration write", + draftAtCommit); } catch (RuntimeException uncertainWrite) { try { return readBackCommittedResult( @@ -479,10 +497,21 @@ private BaselineSummary toV1Summary(RecordedParticipantDigest row) { || row.getBaseVersionId() != null) { throw new IllegalStateException("v1 batch query returned a non-Entity full-version row"); } - return toSummary(row); + Version version = + versionRepository + .findByTenantIdAndId( + row.getTenantId(), parsePositiveVersionId(row.getId(), row.getScopeValue())) + .orElse(null); + ScopeStatus status = + version == null + ? ScopeStatus.BLOCKED_VERSION_MISSING + : version.getVersionState() == VersionLifecycleState.DRAFT + ? ScopeStatus.BLOCKED_DRAFT + : ScopeStatus.V1_REQUIRES_MIGRATION; + return toSummary(row, status); } - private BaselineSummary toSummary(RecordedParticipantDigest row) { + private BaselineSummary toSummary(RecordedParticipantDigest row, ScopeStatus status) { if (row.getId() == null || row.getId() < 1) { throw new IllegalStateException("baseline query returned a row without a stable id"); } @@ -497,7 +526,21 @@ private BaselineSummary toSummary(RecordedParticipantDigest row) { row.getRecordedFromPublishWorkflowId(), row.getRecordedAt(), row.getLastVerifiedPublishWorkflowId(), - row.getLastVerifiedAt()); + row.getLastVerifiedAt(), + status); + } + + private ScopeStatus summaryStatus(RecordedParticipantDigest row, ScopeStatus scopeStatus) { + if (scopeStatus == ScopeStatus.BLOCKED_DRAFT + || scopeStatus == ScopeStatus.AMBIGUOUS_BASELINE + || scopeStatus == ScopeStatus.UNSUPPORTED_SCHEMA) { + return scopeStatus; + } + return Objects.equals(row.getDigestSchemaVersion(), TARGET_SCHEMA_VERSION) + ? ScopeStatus.V2_ALREADY_RECORDED + : Objects.equals(row.getDigestSchemaVersion(), SOURCE_SCHEMA_VERSION) + ? ScopeStatus.V1_REQUIRES_MIGRATION + : ScopeStatus.UNSUPPORTED_SCHEMA; } private long parsePositiveVersionId(long baselineId, String scopeValue) { @@ -551,6 +594,8 @@ private MigrationRejectedException rejected(String code, String message, Throwab public enum ScopeStatus { V1_REQUIRES_MIGRATION, + BLOCKED_DRAFT, + BLOCKED_VERSION_MISSING, V2_ALREADY_RECORDED, NO_RECORDED_BASELINE, AMBIGUOUS_BASELINE, @@ -597,7 +642,8 @@ public record BaselineSummary( String recordedFromPublishWorkflowId, LocalDateTime recordedAt, String lastVerifiedPublishWorkflowId, - LocalDateTime lastVerifiedAt) {} + LocalDateTime lastVerifiedAt, + ScopeStatus status) {} public record EntityV1Batch( long scannedAfterBaselineId, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java index 7e2023c47a..8228d4ec1d 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java @@ -4,8 +4,10 @@ import java.util.Objects; import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.repository.EntityDigestBaselineMigrationAuditRepository; import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -17,12 +19,15 @@ public class EntityDigestBaselineMigrationWriteService { private final RecordedParticipantDigestRepository baselineRepository; private final EntityDigestBaselineMigrationAuditRepository auditRepository; + private final VersionRepository versionRepository; public EntityDigestBaselineMigrationWriteService( RecordedParticipantDigestRepository baselineRepository, - EntityDigestBaselineMigrationAuditRepository auditRepository) { + EntityDigestBaselineMigrationAuditRepository auditRepository, + VersionRepository versionRepository) { this.baselineRepository = baselineRepository; this.auditRepository = auditRepository; + this.versionRepository = versionRepository; } @Transactional @@ -31,6 +36,20 @@ public void commit( RecordedParticipantDigest replacement, EntityDigestBaselineMigrationAudit audit) { validateWriteSet(expectedOld, replacement, audit); + long versionId; + try { + versionId = Long.parseLong(expectedOld.getScopeValue()); + } catch (RuntimeException invalidScope) { + throw new IllegalArgumentException( + "migration source has an invalid version scope", invalidScope); + } + var version = + versionRepository + .findByTenantIdAndIdForUpdate(expectedOld.getTenantId(), versionId) + .orElseThrow(() -> new IllegalStateException("migration version disappeared")); + if (version.getVersionState() == VersionLifecycleState.DRAFT) { + throw new DraftVersionException(); + } int updated = baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(expectedOld, replacement); if (updated != 1) { @@ -40,6 +59,12 @@ public void commit( auditRepository.insert(audit); } + static final class DraftVersionException extends IllegalStateException { + private DraftVersionException() { + super("mutable DRAFT versions cannot be migrated"); + } + } + private void validateWriteSet( RecordedParticipantDigest expectedOld, RecordedParticipantDigest replacement, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java index 9b0713727a..8c26c0122a 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -19,6 +20,7 @@ import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.repository.EntityDigestBaselineMigrationAuditRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; @@ -217,6 +219,38 @@ void enumeratesMixedRowsMigratesOnlyExactTenantVersionAndReadsBackAuditAndBaseli assertBaselineUnchanged(otherParticipant); } + @Test + void draftV1ScopeIsReportedBlockedAndMigrationDoesNotReadEntityDigest() { + createGame("9301"); + Version draftVersion = createVersion("9301", 1, VersionLifecycleState.DRAFT); + RecordedParticipantDigest baseline = seedEntityBaseline("9301", draftVersion, 1); + MigrationCommand command = command("draft-scope-operation", "9301", baseline); + + EntityDigestBaselineMigrationService.EntityV1Batch page = + migrationService.enumerateEntityV1Batch(baseline.getId() - 1, 10); + assertThat(page.baselines()) + .filteredOn(summary -> summary.baselineId() == baseline.getId()) + .singleElement() + .extracting(BaselineSummary::status) + .isEqualTo(ScopeStatus.BLOCKED_DRAFT); + assertThat(migrationService.preflightScope("9301", draftVersion.getId()).status()) + .isEqualTo(ScopeStatus.BLOCKED_DRAFT); + + assertThatThrownBy(() -> migrationService.migrate(command)) + .isInstanceOf(EntityDigestBaselineMigrationService.MigrationRejectedException.class) + .satisfies( + failure -> + assertThat( + ((EntityDigestBaselineMigrationService.MigrationRejectedException) failure) + .failureCode()) + .isEqualTo("VERSION_DRAFT")); + verify(entityManagementClient, never()).getDraftDesignDigestForVersion(any()); + assertThat(baselineRepository.findById(baseline.getId()).orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(baseline); + assertThat(auditRepository.findByOperationId(command.operationId())).isEmpty(); + } + @Test void exactRetryReadsCommittedEvidenceWithoutCallingEntityAgain() { createGame("9301"); @@ -306,9 +340,14 @@ private void createGame(String tenantId) { } private Version createVersion(String tenantId, int versionNumber) { + return createVersion(tenantId, versionNumber, VersionLifecycleState.PUBLISHED); + } + + private Version createVersion(String tenantId, int versionNumber, VersionLifecycleState state) { Version version = new Version(); version.setTenantId(tenantId); version.setVersionNumber(versionNumber); + version.setVersionState(state); version.setNotes("Entity baseline migration integration fixture"); return versionRepository.save(version); } diff --git a/services/game-design-service/src/test/java/unit/db/migration/V26__bind_participant_digest_patch_scopeTest.java b/services/game-design-service/src/test/java/unit/db/migration/V26__bind_participant_digest_patch_scopeTest.java index 55d3d0844a..dba5504036 100644 --- a/services/game-design-service/src/test/java/unit/db/migration/V26__bind_participant_digest_patch_scopeTest.java +++ b/services/game-design-service/src/test/java/unit/db/migration/V26__bind_participant_digest_patch_scopeTest.java @@ -154,7 +154,8 @@ void readsMigrationDocumentationFromRepositoryRootModuleAndNestedDirectories() .isEqualTo(expected); assertThat( readMigrationDoc( - repositoryRoot.resolve("services/game-design-service/src/test/java/unit/db/migration"))) + repositoryRoot.resolve( + "services/game-design-service/src/test/java/unit/db/migration"))) .isEqualTo(expected); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java index 6fb639538f..cae02450bf 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java @@ -100,6 +100,43 @@ void preflightClassifiesRetainedEntityV1Row() { assertEquals("version:42", result.baselines().get(0).appliedCommitId()); } + @Test + void preflightReportsMutableDraftAsBlocked() { + EntityDigestBaselineMigrationService service = serviceWithMockWriter(); + Version draft = version(); + draft.setVersionState(VersionLifecycleState.DRAFT); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(draft)); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(source)); + + EntityDigestBaselineMigrationService.ScopePreflight result = + service.preflightScope(TENANT_ID, VERSION_ID); + + assertEquals(EntityDigestBaselineMigrationService.ScopeStatus.BLOCKED_DRAFT, result.status()); + assertEquals( + EntityDigestBaselineMigrationService.ScopeStatus.BLOCKED_DRAFT, + result.baselines().get(0).status()); + } + + @Test + void draftPreflightPreservesNoDataAndAlreadyV2Classifications() { + EntityDigestBaselineMigrationService service = serviceWithMockWriter(); + Version draft = version(); + draft.setVersionState(VersionLifecycleState.DRAFT); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(draft)); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(), List.of(v2Baseline())); + + assertEquals( + EntityDigestBaselineMigrationService.ScopeStatus.NO_RECORDED_BASELINE, + service.preflightScope(TENANT_ID, VERSION_ID).status()); + assertEquals( + EntityDigestBaselineMigrationService.ScopeStatus.V2_ALREADY_RECORDED, + service.preflightScope(TENANT_ID, VERSION_ID).status()); + } + @Test void preflightReportsAmbiguousScopeInsteadOfSelectingARow() { EntityDigestBaselineMigrationService service = serviceWithMockWriter(); @@ -123,6 +160,10 @@ void enumerationReturnsBoundedCursorPageWithExactScopeIdentities() { EntityDigestBaselineMigrationService service = serviceWithMockWriter(); when(baselineRepository.findEntityV1FullVersionBatchAfterId(10L, 25)) .thenReturn(List.of(source)); + Version draft = version(); + draft.setVersionState(VersionLifecycleState.DRAFT); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(draft)); EntityDigestBaselineMigrationService.EntityV1Batch page = service.enumerateEntityV1Batch(10L, 25); @@ -132,19 +173,73 @@ void enumerationReturnsBoundedCursorPageWithExactScopeIdentities() { assertEquals(BASELINE_ID, page.nextAfterBaselineId()); assertEquals(TENANT_ID, page.baselines().get(0).tenantId()); assertEquals(VERSION_ID, page.baselines().get(0).versionId()); + assertEquals( + EntityDigestBaselineMigrationService.ScopeStatus.BLOCKED_DRAFT, + page.baselines().get(0).status()); assertFalse(page.isEmptyAtCursor()); } + @Test + void migrateRejectsDraftBeforeEntityDigestOrAuditRead() { + Version draft = version(); + draft.setVersionState(VersionLifecycleState.DRAFT); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(draft)); + + EntityDigestBaselineMigrationService.MigrationRejectedException rejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> serviceWithMockWriter().migrate(command)); + + assertEquals("VERSION_DRAFT", rejected.failureCode()); + verify(entityManagementClient, never()).getDraftDesignDigestForVersion(any()); + verify(auditRepository, never()).findByOperationId(OPERATION_ID); + verify(auditRepository, never()).insert(any()); + } + + @Test + void migrateRejectsDraftObservedAtGuardedWriteBoundary() { + AtomicReference persistedBaseline = new AtomicReference<>(source); + AtomicReference persistedAudit = new AtomicReference<>(); + EntityDigestBaselineMigrationWriteService writer = + new EntityDigestBaselineMigrationWriteService( + baselineRepository, auditRepository, versionRepository); + EntityDigestBaselineMigrationService service = + new EntityDigestBaselineMigrationService( + baselineRepository, auditRepository, versionRepository, entityManagementClient, writer); + stubInitialMigrationReads(persistedBaseline, persistedAudit); + Version draftAtCommit = version(); + draftAtCommit.setVersionState(VersionLifecycleState.DRAFT); + when(versionRepository.findByTenantIdAndIdForUpdate(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(draftAtCommit)); + when(entityManagementClient.getDraftDesignDigestForVersion(any())) + .thenReturn(v2Digest("v2-content", "version:42")); + + EntityDigestBaselineMigrationService.MigrationRejectedException rejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> service.migrate(command)); + + assertEquals("VERSION_DRAFT", rejected.failureCode()); + assertEquals(1, persistedBaseline.get().getDigestSchemaVersion()); + assertTrue(persistedAudit.get() == null); + verify(baselineRepository, never()).migrateEntityFullVersionBaselineIfUnchanged(any(), any()); + verify(auditRepository, never()).insert(any()); + } + @Test void migrationCommitsAndProvesExactV2BaselineAndAuditReadback() { AtomicReference persistedBaseline = new AtomicReference<>(source); AtomicReference persistedAudit = new AtomicReference<>(); EntityDigestBaselineMigrationWriteService writer = - new EntityDigestBaselineMigrationWriteService(baselineRepository, auditRepository); + new EntityDigestBaselineMigrationWriteService( + baselineRepository, auditRepository, versionRepository); EntityDigestBaselineMigrationService service = new EntityDigestBaselineMigrationService( baselineRepository, auditRepository, versionRepository, entityManagementClient, writer); stubInitialMigrationReads(persistedBaseline, persistedAudit); + when(versionRepository.findByTenantIdAndIdForUpdate(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); when(entityManagementClient.getDraftDesignDigestForVersion(any())) .thenReturn(v2Digest("v2-content", "version:42")); when(baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(any(), any())) @@ -193,6 +288,8 @@ void exactRetryReturnsOnlyAfterBaselineAndAuditReadbackWithoutRecomputing() { EntityDigestBaselineMigrationAudit audit = audit(source, migrated, AUDIT_ID, auditTime()); when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.of(audit)); when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(migrated)); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); EntityDigestBaselineMigrationService.MigrationResult result = serviceWithMockWriter().migrate(command); @@ -202,7 +299,7 @@ void exactRetryReturnsOnlyAfterBaselineAndAuditReadbackWithoutRecomputing() { result.disposition()); assertEquals("v2-content", result.contentDigest()); verify(entityManagementClient, never()).getDraftDesignDigestForVersion(any()); - verify(versionRepository, never()).findByTenantIdAndId(any(), any()); + verify(versionRepository).findByTenantIdAndId(TENANT_ID, VERSION_ID); } @Test @@ -210,6 +307,8 @@ void operationIdReuseWithDifferentSourceIsRejected() { EntityDigestBaselineMigrationAudit conflicting = audit(source, migratedBaseline("v2-content", "version:42"), AUDIT_ID, auditTime()); conflicting = withSourceContentDigest(conflicting, "different-v1-digest"); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.of(conflicting)); EntityDigestBaselineMigrationService.MigrationRejectedException rejected = @@ -227,6 +326,8 @@ void changedOldTupleIsRejectedBeforeEntityRecomputation() { RecordedParticipantDigest changed = sourceBaseline(); changed.setLastVerifiedAt(SOURCE_VERIFIED_AT.plusSeconds(1)); when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.empty()); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(changed)); when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) .thenReturn(List.of(changed)); @@ -245,6 +346,8 @@ void wrongTenantBaselineIsRejectedBeforeScopeOrEntityRead() { RecordedParticipantDigest wrongTenant = sourceBaseline(); wrongTenant.setTenantId("tenant-other"); when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.empty()); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(wrongTenant)); EntityDigestBaselineMigrationService.MigrationRejectedException rejected = diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java index 046d2e1396..6f8a0fc7ab 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java @@ -9,10 +9,13 @@ import java.time.LocalDateTime; import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; +import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.repository.EntityDigestBaselineMigrationAuditRepository; import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -23,6 +26,7 @@ class EntityDigestBaselineMigrationWriteServiceTest { @Mock private RecordedParticipantDigestRepository baselineRepository; @Mock private EntityDigestBaselineMigrationAuditRepository auditRepository; + @Mock private VersionRepository versionRepository; private EntityDigestBaselineMigrationWriteService service; private RecordedParticipantDigest source; @@ -31,15 +35,36 @@ class EntityDigestBaselineMigrationWriteServiceTest { @BeforeEach void setUp() { - service = new EntityDigestBaselineMigrationWriteService(baselineRepository, auditRepository); + service = + new EntityDigestBaselineMigrationWriteService( + baselineRepository, auditRepository, versionRepository); LocalDateTime time = LocalDateTime.parse("2026-09-26T01:02:03.123456"); source = baseline(1, "old", time.minusDays(1), "publish:old", "verify:old"); replacement = baseline(2, "new", time.minusDays(1), "publish:old", "verify:old"); audit = audit(time); } + @Test + void draftAtGuardedWriteBoundaryPreventsBaselineAndAuditWrites() { + Version draft = new Version(); + draft.setVersionState(VersionLifecycleState.DRAFT); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-7", 42L)) + .thenReturn(java.util.Optional.of(draft)); + + assertThrows( + EntityDigestBaselineMigrationWriteService.DraftVersionException.class, + () -> service.commit(source, replacement, audit)); + + verify(baselineRepository, never()).migrateEntityFullVersionBaselineIfUnchanged(any(), any()); + verify(auditRepository, never()).insert(any()); + } + @Test void compareAndSetAndAuditAreBothRequiredForCommit() { + Version version = new Version(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-7", 42L)) + .thenReturn(java.util.Optional.of(version)); when(baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(source, replacement)) .thenReturn(1); @@ -51,6 +76,10 @@ void compareAndSetAndAuditAreBothRequiredForCommit() { @Test void changedRowPreventsAuditInsert() { + Version version = new Version(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + when(versionRepository.findByTenantIdAndIdForUpdate("tenant-7", 42L)) + .thenReturn(java.util.Optional.of(version)); when(baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(source, replacement)) .thenReturn(0); From eb381e4e97b7845612be84653fe2844fe742d570 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 03:09:22 +1300 Subject: [PATCH 13/28] Preserve exact baseline migration retry after Draft transition --- .../EntityDigestBaselineMigrationService.java | 7 ++--- ...ityDigestBaselineMigrationServiceTest.java | 28 +++++++++++++++++-- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java index eda2c44c58..d2dce05bb8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java @@ -144,10 +144,6 @@ public MigrationResult migrate(MigrationCommand command) { || version.isScriptOnly()) { throw rejected("VERSION_SCOPE_MISMATCH", "version is outside the tenant or is script-only"); } - if (version.getVersionState() == VersionLifecycleState.DRAFT) { - throw rejected("VERSION_DRAFT", "mutable DRAFT versions cannot be migrated"); - } - Optional priorAudit = auditRepository.findByOperationId(command.operationId()); if (priorAudit.isPresent()) { @@ -155,6 +151,9 @@ public MigrationResult migrate(MigrationCommand command) { assertAuditSourceMatchesCommand(audit, command); return readBackCommittedResult(command, audit, MigrationDisposition.EXACT_RETRY); } + if (version.getVersionState() == VersionLifecycleState.DRAFT) { + throw rejected("VERSION_DRAFT", "mutable DRAFT versions cannot be migrated"); + } RecordedParticipantDigest current = baselineRepository diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java index cae02450bf..8cec5bc91f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java @@ -180,7 +180,7 @@ void enumerationReturnsBoundedCursorPageWithExactScopeIdentities() { } @Test - void migrateRejectsDraftBeforeEntityDigestOrAuditRead() { + void migrateRejectsNewDraftOperationBeforeEntityDigestOrBaselineRead() { Version draft = version(); draft.setVersionState(VersionLifecycleState.DRAFT); when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) @@ -193,7 +193,8 @@ void migrateRejectsDraftBeforeEntityDigestOrAuditRead() { assertEquals("VERSION_DRAFT", rejected.failureCode()); verify(entityManagementClient, never()).getDraftDesignDigestForVersion(any()); - verify(auditRepository, never()).findByOperationId(OPERATION_ID); + verify(auditRepository).findByOperationId(OPERATION_ID); + verify(baselineRepository, never()).findById(BASELINE_ID); verify(auditRepository, never()).insert(any()); } @@ -302,6 +303,29 @@ void exactRetryReturnsOnlyAfterBaselineAndAuditReadbackWithoutRecomputing() { verify(versionRepository).findByTenantIdAndId(TENANT_ID, VERSION_ID); } + @Test + void exactRetryOfCommittedOperationStillReadsBackAfterVersionBecomesDraft() { + RecordedParticipantDigest migrated = migratedBaseline("v2-content", "version:42"); + EntityDigestBaselineMigrationAudit audit = audit(source, migrated, AUDIT_ID, auditTime()); + Version draft = version(); + draft.setVersionState(VersionLifecycleState.DRAFT); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(draft)); + when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.of(audit)); + when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(migrated)); + + EntityDigestBaselineMigrationService.MigrationResult result = + serviceWithMockWriter().migrate(command); + + assertEquals( + EntityDigestBaselineMigrationService.MigrationDisposition.EXACT_RETRY, + result.disposition()); + assertEquals("v2-content", result.contentDigest()); + verify(entityManagementClient, never()).getDraftDesignDigestForVersion(any()); + verify(auditRepository, never()).insert(any()); + verify(baselineRepository, never()).migrateEntityFullVersionBaselineIfUnchanged(any(), any()); + } + @Test void operationIdReuseWithDifferentSourceIsRejected() { EntityDigestBaselineMigrationAudit conflicting = From 765e5fdde28cce5a46fec211f5b39d589b6cc4d3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 03:29:18 +1300 Subject: [PATCH 14/28] Prepare restricted database identities for baseline migration Job --- .../game-design-service/operations.md | 4 +- ...tity-digest-baseline-migration-contract.sh | 39 +++- .../entity-digest-baseline-migration-job.yaml | 14 +- ...ntityDigestBaselineMigrationJobRunner.java | 43 ++++- ...igestBaselineMigrationIntegrationTest.java | 175 ++++++++++++++++++ ...yDigestBaselineMigrationJobRunnerTest.java | 44 +++++ 6 files changed, 305 insertions(+), 14 deletions(-) diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 296f7914d5..29e6ec0769 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -36,7 +36,9 @@ Use a controlled pre-v1 publication window for the affected Entity v1 full-versi Before invoking a Job, verify the exact Kubernetes context and namespace, the authorized operator identity and approved maintenance window, both current service image digests, database backup/recovery posture, completed in-flight publication drain, and the dedicated migrator certificate's issuer, `Ready` state, URI SAN, trust chain, projected Secret, and actual mTLS acceptance at Entity. The hosted trust/controller admission policy includes a narrow runtime-namespace exception for this identity; it does not make the migrator one of the controller's permanent certificate consumers. A trusted certificate writer must explicitly invoke `ensure-standalone-transport-certificates.sh --migrator `; a separately authorized Secret-read operator then invokes `--verify-migrator ` before the Job is enabled. The certificate writer's service account has no Secret-read permission. These opt-in operations do not alter ordinary preview transport-certificate rollout. A rendered Certificate or Secret name alone is not issuance or served-identity proof. The trusted operator must create an immutable expected-source ConfigMap or Secret from a read-only exact database row, including baseline ID, tenant, `FULL_VERSION`, `ENTITY_MANAGEMENT`, null base version, version scope, applied commit, digest, schema `1`, and both workflow IDs and timestamps. Do not place this manifest, credentials, or raw retained row values in a PR or CI artifact. Check that the source object is immutable before applying the Job. The Job's `targetNamespace`, tenant/version, operation ID, actor identity, and expected-source object are all fixed for that invocation; a changed command gets a new operation ID, never a reinterpretation of the old one. `actorIdentity` is an operator-supplied audit claim, not an identity attested by the Job's workload certificate. Preserve the trusted deployment audit identifying the authenticated human operator and correlate its Job UID, operation ID, values/image revision, and time with the Game Design before/after audit row; do not use that row alone as proof of the human operator's identity. -The chart's `previewStack.entityDigestBaselineMigration` values are disabled by default. From the trusted operator revision, supply an image pinned as `repository@sha256:`, exact `targetNamespace`, the dedicated `firemud-grpc-game-design-baseline-migrator` Secret, and `mode`. `enumerate` returns at most 500 Entity schema-v1 full-version rows after one baseline ID and reports each scope's migration status, including `BLOCKED_DRAFT`; repeat with its returned keyset cursor until an empty page proves no more rows at the quiesced snapshot. `preflight` classifies one exact tenant/version as v1, v2, absent, ambiguous, unsupported, or `BLOCKED_DRAFT`, and refuses a missing or script-only Version. `migrate` requires one stable operation ID, exact tenant/version, actor identity, and the immutable expected-source object. It rejects a DRAFT Version before reading the Entity digest and locks/rechecks the Version row in the same transaction as the guarded baseline update and audit insertion, closing the state-change race at that write boundary. This guard does not freeze authoring while the external digest is read. The Java runner verifies its namespace, dedicated service account, and certificate URI identity before reading or writing. A missing identity, policy, input, row, version, exact-old match, or v2 Entity response fails closed. Render and inspect the operator overlay before installation; do not leave `enabled: true` in the ordinary chart values or an unattended release upgrade. Completed Jobs are deliberately not Helm hooks, so an unchanged upgrade does not rerun them; a changed immutable Job spec is rejected and needs an explicit trusted disposition. +The chart's `previewStack.entityDigestBaselineMigration` values are disabled by default. From the trusted operator revision, supply an image pinned as `repository@sha256:`, exact `targetNamespace`, the dedicated `firemud-grpc-game-design-baseline-migrator` Secret, and `mode`. The chart requires the separately provisioned `firemud-game-design-baseline-reader-db` Secret for `enumerate` and `preflight`, and `firemud-game-design-baseline-writer-db` for `migrate`; both must provide `FIREMUD_POSTGRES_USER` and `FIREMUD_POSTGRES_PASSWORD`. A trusted database operator provisions these least-privilege credentials; the chart does not create them, and the Job never consumes the shared `firemud-secret` bootstrap credentials. The migration Job disables Flyway. `enumerate` returns at most 500 Entity schema-v1 full-version rows after one baseline ID and reports each scope's migration status, including `BLOCKED_DRAFT`; repeat with its returned keyset cursor until an empty page proves no more rows at the quiesced snapshot. `preflight` classifies one exact tenant/version as v1, v2, absent, ambiguous, unsupported, or `BLOCKED_DRAFT`, and refuses a missing or script-only Version. `migrate` requires one stable operation ID, exact tenant/version, actor identity, and the immutable expected-source object. It rejects a DRAFT Version before reading the Entity digest and locks/rechecks the Version row in the same transaction as the guarded baseline update and audit insertion, closing the state-change race at that write boundary. This guard does not freeze authoring while the external digest is read. The Java runner verifies its namespace, dedicated service account, and certificate URI identity before reading or writing. A missing identity, policy, input, row, version, exact-old match, or v2 Entity response fails closed. Render and inspect the operator overlay before installation; do not leave `enabled: true` in the ordinary chart values or an unattended release upgrade. Completed Jobs are deliberately not Helm hooks, so an unchanged upgrade does not rerun them; a changed immutable Job spec is rejected and needs an explicit trusted disposition. + +Before enabling the Job, a trusted database operator provisions `firemud_game_design_baseline_reader` and `firemud_game_design_baseline_writer` as separate login roles with no superuser, database/role-creation, replication, bypass-RLS, inherited-role, or application-object ownership powers. Both may connect to the selected database, use `game_design_service`, and select only Game Design `version` and `publish_recorded_participant_digest`; the writer additionally needs audit-table select/insert, usage/select on `entity_digest_baseline_migration_audit_id_seq`, and column-limited update of only `applied_commit_id`, `content_digest`, and `digest_schema_version` on the baseline table. Neither role gets Entity or another service's schema access, Version or Flyway-history writes, baseline insert/delete, broad table grants, or DDL. Revoke broader/default grants first, then read back effective role attributes, memberships, ownership, table/column/sequence grants, and denied operations as the restricted users. Verify the mode-specific Secret's exact username/password authentication and V29 presence before live activation; a rendered Secret reference is not proof of those facts. Retire both Secrets and roles after final database readback and the approved rollback window. For each affected scope, retain the preflight row ID and complete source tuple privately, run `migrate`, and require its reported operation/audit/baseline IDs and disposition. The Game Design transaction conditionally replaces the exact old row and inserts an immutable before/after audit atomically. The live row retains its original and last real publish-workflow IDs and timestamps; only the audit's operation ID and committed time describe the maintenance transition. An exact retry of the same operation reads the existing audit and baseline rather than writing again; a lost acknowledgement is resolved by that same operation identity and exact readback. A changed source, ambiguous scope, different actor/workload binding, mismatched Entity v2 schema/scope/digest/commit, or unproved write outcome is a stop condition. Independently read back `publish_recorded_participant_digest` by baseline ID and `entity_digest_baseline_migration_audit` by operation ID from Game Design's PostgreSQL schema; compare the new schema/digest/commit and preserved publish provenance, complete old tuple, observed v2 tuple, migration operation, actor/workload, outcome, and timestamp exactly. Never count Job completion alone as database proof. Keep the before/after records with the private migration log, excluding secrets and certificate keys. diff --git a/dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh b/dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh index f31ea8c543..827c9ebc2a 100644 --- a/dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh +++ b/dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh @@ -75,6 +75,35 @@ def require_failure(case, override, expected_fragment): ) +def assert_database_identity(job, expected_secret_name, mode): + container = job.get("spec", {}).get("template", {}).get("spec", {}).get("containers", [])[0] + if container.get("envFrom"): + raise SystemExit(f"{mode} Job must not import a broad service environment") + env = {entry["name"]: entry for entry in container.get("env", [])} + for name in ("FIREMUD_POSTGRES_USER", "FIREMUD_POSTGRES_PASSWORD"): + ref = env.get(name, {}).get("valueFrom", {}).get("secretKeyRef", {}) + if ref.get("name") != expected_secret_name: + raise SystemExit(f"{mode} Job must use {expected_secret_name} for {name}") + if ref.get("key") != name: + raise SystemExit(f"{mode} Job must use the exact {name} Secret key") + if ref.get("optional") is not False: + raise SystemExit(f"{mode} Job must require its {name} Secret key") + if env.get("SPRING_FLYWAY_ENABLED", {}).get("value") != "false": + raise SystemExit(f"{mode} Job must disable Flyway") + + def contains_shared_secret(value): + if isinstance(value, dict): + if value.get("name") == "firemud-secret" or value.get("secretName") == "firemud-secret": + return True + return any(contains_shared_secret(child) for child in value.values()) + if isinstance(value, list): + return any(contains_shared_secret(child) for child in value) + return False + + if contains_shared_secret(job): + raise SystemExit(f"{mode} Job must not reference shared firemud-secret") + + disabled = render("migration-disabled") if disabled.returncode != 0: raise SystemExit(f"disabled chart render failed: {disabled.stderr}") @@ -121,6 +150,7 @@ job_name = "game-design-baseline-migrator-entity-v1-to-v2-pr123-v42" job = by_kind_name.get(("Job", job_name)) if job is None: raise SystemExit("enabled configuration did not render the operation-scoped Job") +assert_database_identity(job, "firemud-game-design-baseline-writer-db", "migrate") if by_kind_name.get(("ServiceAccount", "game-design-baseline-migrator"), {}).get( "automountServiceAccountToken" ) is not False: @@ -196,13 +226,6 @@ for name in ( ): if "fieldRef" not in env.get(name, {}).get("valueFrom", {}): raise SystemExit(f"Job must derive {name} from downward API identity") -for name in ( - "FIREMUD_POSTGRES_USER", - "FIREMUD_POSTGRES_PASSWORD", -): - secret_ref = env.get(name, {}).get("valueFrom", {}).get("secretKeyRef", {}) - if secret_ref.get("name") != "firemud-secret": - raise SystemExit(f"Job database credential {name} is not secret-projected") for name in ( "FIREMUD_POSTGRES_HOST", "FIREMUD_POSTGRES_PORT", @@ -306,6 +329,7 @@ preflight_docs = documents(preflight_result.stdout) preflight_job = next( item for item in preflight_docs if item.get("kind") == "Job" and item.get("metadata", {}).get("name", "").startswith("game-design-baseline-migrator-preflight-") ) +assert_database_identity(preflight_job, "firemud-game-design-baseline-reader-db", "preflight") if any(volume.get("name") == "expected-source" for volume in preflight_job["spec"]["template"]["spec"].get("volumes", [])): raise SystemExit("read-only preflight unexpectedly requires or mounts an expected-source tuple") @@ -326,6 +350,7 @@ enumerate_docs = documents(enumerate_result.stdout) enumerate_job = next( item for item in enumerate_docs if item.get("kind") == "Job" and "-enumerate-" in item.get("metadata", {}).get("name", "") ) +assert_database_identity(enumerate_job, "firemud-game-design-baseline-reader-db", "enumerate") enumerate_env = { entry["name"]: entry for entry in enumerate_job["spec"]["template"]["spec"]["containers"][0].get("env", []) diff --git a/k8s/helm/firemud/templates/entity-digest-baseline-migration-job.yaml b/k8s/helm/firemud/templates/entity-digest-baseline-migration-job.yaml index 971fe8d792..b44e4b16cb 100644 --- a/k8s/helm/firemud/templates/entity-digest-baseline-migration-job.yaml +++ b/k8s/helm/firemud/templates/entity-digest-baseline-migration-job.yaml @@ -74,6 +74,10 @@ {{- if ne $grpcIdentitySecretName "firemud-grpc-game-design-baseline-migrator" -}} {{- fail "grpcIdentitySecretName must be firemud-grpc-game-design-baseline-migrator; shared service identities are not accepted" -}} {{- end -}} +{{- $postgresCredentialSecretName := "firemud-game-design-baseline-reader-db" -}} +{{- if eq $mode "migrate" -}} +{{- $postgresCredentialSecretName = "firemud-game-design-baseline-writer-db" -}} +{{- end -}} {{- $readScopeName := printf "%s:%s:%s:%s:%s:%s" $mode $tenantId (toString $versionId) $afterBaselineId (toString $limit) $targetNamespace | sha256sum | trunc 12 -}} {{- $jobSuffix := $operationId -}} {{- if ne $mode "migrate" -}} @@ -165,8 +169,8 @@ spec: - --spring.grpc.server.enabled=false - --firemud.entity-baseline-migration.enabled=true env: - - name: SPRING_FLYWAY_TABLE - value: flyway_schema_history_game_design_service + - name: SPRING_FLYWAY_ENABLED + value: "false" - name: SERVICE_SCHEMA value: game_design_service - name: FIREMUD_POSTGRES_HOST @@ -187,13 +191,15 @@ spec: - name: FIREMUD_POSTGRES_USER valueFrom: secretKeyRef: - name: firemud-secret + name: {{ $postgresCredentialSecretName | quote }} key: FIREMUD_POSTGRES_USER + optional: false - name: FIREMUD_POSTGRES_PASSWORD valueFrom: secretKeyRef: - name: firemud-secret + name: {{ $postgresCredentialSecretName | quote }} key: FIREMUD_POSTGRES_PASSWORD + optional: false - name: FIREMUD_REDIS_ENABLED value: "false" - name: FIREMUD_TEMPORAL_ENABLED diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java index c17bf71b94..fe3baff711 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java @@ -6,6 +6,9 @@ import java.nio.file.Path; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.sql.Connection; +import java.sql.SQLException; +import javax.sql.DataSource; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService; import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.ExpectedSource; @@ -37,14 +40,17 @@ public class EntityDigestBaselineMigrationJobRunner implements ApplicationRunner private final Environment environment; private final ObjectMapper objectMapper; private final EntityDigestBaselineMigrationService migrationService; + private final DataSource dataSource; public EntityDigestBaselineMigrationJobRunner( Environment environment, ObjectMapper objectMapper, - EntityDigestBaselineMigrationService migrationService) { + EntityDigestBaselineMigrationService migrationService, + DataSource dataSource) { this.environment = environment; this.objectMapper = objectMapper; this.migrationService = migrationService; + this.dataSource = dataSource; } @Override @@ -56,6 +62,12 @@ public void run(ApplicationArguments args) throws Exception { throw new IllegalStateException( "migration Job must not start application listeners or workers"); } + String mode = required("firemud.entity-baseline-migration.mode"); + requireDatabaseAuthority( + mode, + connectedDatabaseUsername(), + environment.getProperty("spring.flyway.enabled", Boolean.class, true)); + String namespace = required("firemud.entity-baseline-migration.pod-namespace"); GrpcPeerIdentity identity = verifiedWorkloadIdentity(); requireJobAuthority( @@ -65,7 +77,6 @@ public void run(ApplicationArguments args) throws Exception { identity); String workloadIdentity = identity.uri(); - String mode = required("firemud.entity-baseline-migration.mode"); switch (mode) { case "enumerate" -> { long afterId = optionalLong("firemud.entity-baseline-migration.after-baseline-id", 0); @@ -133,6 +144,34 @@ static void requireJobAuthority( } } + static void requireDatabaseAuthority(String mode, String username, boolean flywayEnabled) { + if (flywayEnabled) { + throw new IllegalStateException("migration Job requires Flyway to be disabled"); + } + String requiredUsername = + switch (mode) { + case "enumerate", "preflight" -> "firemud_game_design_baseline_reader"; + case "migrate" -> "firemud_game_design_baseline_writer"; + default -> throw new IllegalArgumentException("unsupported migration Job mode"); + }; + if (!requiredUsername.equals(username)) { + throw new IllegalStateException("migration DB credential does not match the required mode"); + } + } + + private String connectedDatabaseUsername() { + try (Connection connection = dataSource.getConnection()) { + String username = connection.getMetaData().getUserName(); + if (username == null || username.isBlank()) { + throw new IllegalStateException("migration DB connection did not identify its user"); + } + return username; + } catch (SQLException failure) { + // Avoid surfacing driver diagnostics that can echo the configured database username. + throw new IllegalStateException("migration DB connection identity could not be verified"); + } + } + private GrpcPeerIdentity verifiedWorkloadIdentity() throws Exception { Path certificatePath = Path.of(required("FIREMUD_GRPC_CERT_CHAIN_PATH")); X509Certificate leaf; diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java index 8c26c0122a..3249cee722 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java @@ -8,6 +8,11 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; @@ -332,6 +337,176 @@ void auditInsertFailureRollsBackTheGuardedBaselineReplacement() { .isEqualTo(firstResult.auditId()); } + @Test + void databaseMigrationRolesHaveOnlyTheirDirectTablePrivileges() throws Exception { + createGame("9701"); + Version version = createVersion("9701", 1); + RecordedParticipantDigest baseline = seedEntityBaseline("9701", version, 1); + provisionMigrationDatabaseRoles(); + + try (Connection reader = connectAs("firemud_game_design_baseline_reader_test", "reader-proof")) { + assertThat(reader.getMetaData().getUserName()) + .isEqualTo("firemud_game_design_baseline_reader_test"); + assertCount(reader, "version"); + assertCount(reader, "publish_recorded_participant_digest"); + assertDenied( + reader, + "UPDATE game_design_service.publish_recorded_participant_digest " + + "SET content_digest = 'forbidden' WHERE false"); + assertDenied( + reader, + "INSERT INTO game_design_service.publish_recorded_participant_digest " + + "(tenant_id) VALUES ('forbidden')"); + assertDenied(reader, "CREATE TABLE game_design_service.reader_forbidden (id integer)"); + assertDenied( + reader, + "CREATE TABLE baseline_migration_other_schema.reader_forbidden (id integer)"); + assertDenied( + reader, + "UPDATE baseline_migration_other_schema.sentinel SET id = id WHERE false"); + } + + try (Connection writer = connectAs("firemud_game_design_baseline_writer_test", "writer-proof")) { + assertThat(writer.getMetaData().getUserName()) + .isEqualTo("firemud_game_design_baseline_writer_test"); + assertCount(writer, "version"); + assertCount(writer, "publish_recorded_participant_digest"); + assertCount(writer, "entity_digest_baseline_migration_audit"); + + try (PreparedStatement update = + writer.prepareStatement( + "UPDATE game_design_service.publish_recorded_participant_digest " + + "SET content_digest = ?, digest_schema_version = 2 " + + "WHERE id = ? AND content_digest = ? AND digest_schema_version = 1")) { + update.setString(1, "entity-v2-restricted-writer-proof"); + update.setLong(2, baseline.getId()); + update.setString(3, baseline.getContentDigest()); + assertThat(update.executeUpdate()).isEqualTo(1); + } + try (PreparedStatement insert = + writer.prepareStatement( + "INSERT INTO game_design_service.entity_digest_baseline_migration_audit (" + + "operation_id, recorded_participant_digest_id, source_tenant_id, " + + "source_publish_type, source_participant_key, source_base_version_id, " + + "source_scope_value, source_applied_commit_id, source_content_digest, " + + "source_digest_schema_version, source_recorded_from_publish_workflow_id, " + + "source_recorded_at, source_last_verified_publish_workflow_id, " + + "source_last_verified_at, observed_tenant_id, observed_publish_type, " + + "observed_participant_key, observed_base_version_id, observed_scope_value, " + + "observed_applied_commit_id, observed_content_digest, " + + "observed_digest_schema_version, actor_identity, workload_identity, outcome, " + + "committed_at) " + + "SELECT ?, id, tenant_id, publish_type, participant_key, base_version_id, " + + "scope_value, applied_commit_id, ?, 1, recorded_from_publish_workflow_id, " + + "recorded_at, last_verified_publish_workflow_id, last_verified_at, tenant_id, " + + "publish_type, participant_key, base_version_id, scope_value, " + + "applied_commit_id, content_digest, digest_schema_version, ?, ?, " + + "'COMMITTED', CURRENT_TIMESTAMP " + + "FROM game_design_service.publish_recorded_participant_digest WHERE id = ?")) { + insert.setString(1, "restricted-writer-proof-" + baseline.getId()); + insert.setString(2, baseline.getContentDigest()); + insert.setString(3, "operator:test-actor"); + insert.setString(4, "spiffe://firemud/ns/dev/sa/game-design-baseline-migrator"); + insert.setLong(5, baseline.getId()); + assertThat(insert.executeUpdate()).isEqualTo(1); + } + + assertDenied( + writer, + "UPDATE game_design_service.version SET version_state = 'DRAFT' WHERE id = " + + version.getId()); + assertDenied( + writer, + "UPDATE game_design_service.publish_recorded_participant_digest " + + "SET tenant_id = 'forbidden' WHERE id = " + + baseline.getId()); + assertDenied( + writer, + "INSERT INTO game_design_service.version (tenant_id) VALUES ('forbidden')"); + assertDenied( + writer, + "SELECT id FROM game_design_service.version WHERE id = " + + version.getId() + + " FOR UPDATE"); + assertDenied( + writer, + "UPDATE game_design_service.flyway_schema_history_game_design_service " + + "SET success = success WHERE false"); + assertDenied(writer, "CREATE TABLE game_design_service.writer_forbidden (id integer)"); + assertDenied( + writer, + "CREATE TABLE baseline_migration_other_schema.writer_forbidden (id integer)"); + assertDenied( + writer, + "UPDATE baseline_migration_other_schema.sentinel SET id = id WHERE false"); + } + } + + private void provisionMigrationDatabaseRoles() throws SQLException { + try (Connection admin = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Statement statement = admin.createStatement()) { + statement.execute( + "CREATE ROLE firemud_game_design_baseline_reader_test LOGIN NOINHERIT PASSWORD 'reader-proof'"); + statement.execute( + "CREATE ROLE firemud_game_design_baseline_writer_test LOGIN NOINHERIT PASSWORD 'writer-proof'"); + statement.execute("CREATE SCHEMA baseline_migration_other_schema"); + statement.execute( + "CREATE TABLE baseline_migration_other_schema.sentinel (id integer NOT NULL)"); + statement.execute("INSERT INTO baseline_migration_other_schema.sentinel VALUES (1)"); + statement.execute("GRANT USAGE ON SCHEMA game_design_service TO firemud_game_design_baseline_reader_test"); + statement.execute("GRANT USAGE ON SCHEMA game_design_service TO firemud_game_design_baseline_writer_test"); + statement.execute( + "GRANT SELECT ON TABLE game_design_service.version, " + + "game_design_service.publish_recorded_participant_digest " + + "TO firemud_game_design_baseline_reader_test"); + statement.execute( + "GRANT SELECT ON TABLE game_design_service.version, " + + "game_design_service.publish_recorded_participant_digest, " + + "game_design_service.entity_digest_baseline_migration_audit " + + "TO firemud_game_design_baseline_writer_test"); + statement.execute( + "GRANT UPDATE (applied_commit_id, content_digest, digest_schema_version) " + + "ON TABLE game_design_service.publish_recorded_participant_digest " + + "TO firemud_game_design_baseline_writer_test"); + statement.execute( + "GRANT INSERT ON TABLE game_design_service.entity_digest_baseline_migration_audit " + + "TO firemud_game_design_baseline_writer_test"); + statement.execute( + "GRANT USAGE, SELECT ON SEQUENCE " + + "game_design_service.entity_digest_baseline_migration_audit_id_seq " + + "TO firemud_game_design_baseline_writer_test"); + } + } + + private Connection connectAs(String username, String password) throws SQLException { + return DriverManager.getConnection( + postgres.getJdbcUrl() + "?currentSchema=game_design_service", username, password); + } + + private void assertCount(Connection connection, String tableName) throws SQLException { + try (Statement statement = connection.createStatement(); + var rows = + statement.executeQuery( + "SELECT COUNT(*) FROM game_design_service." + tableName)) { + assertThat(rows.next()).isTrue(); + assertThat(rows.getLong(1)).isGreaterThanOrEqualTo(0); + } + } + + private void assertDenied(Connection connection, String sql) throws SQLException { + try (Statement statement = connection.createStatement()) { + try { + statement.execute(sql); + } catch (SQLException denied) { + assertThat(denied.getSQLState()).isEqualTo("42501"); + return; + } + } + throw new AssertionError("restricted migration database role unexpectedly succeeded: " + sql); + } + private void createGame(String tenantId) { Game game = new Game(); game.setTenantId(tenantId); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java index 631eab04ec..777861d978 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import javax.sql.DataSource; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService; import org.junit.jupiter.api.Test; @@ -73,6 +74,44 @@ void rejectsWrongTargetServiceAccountAndCertificateIdentity() { .isInstanceOf(IllegalStateException.class); } + @Test + void requiresFlywayDisabledAndTheModeSpecificDatabaseRole() { + assertThatCode( + () -> + EntityDigestBaselineMigrationJobRunner.requireDatabaseAuthority( + "enumerate", "firemud_game_design_baseline_reader", false)) + .doesNotThrowAnyException(); + assertThatCode( + () -> + EntityDigestBaselineMigrationJobRunner.requireDatabaseAuthority( + "preflight", "firemud_game_design_baseline_reader", false)) + .doesNotThrowAnyException(); + assertThatCode( + () -> + EntityDigestBaselineMigrationJobRunner.requireDatabaseAuthority( + "migrate", "firemud_game_design_baseline_writer", false)) + .doesNotThrowAnyException(); + + assertThatThrownBy( + () -> + EntityDigestBaselineMigrationJobRunner.requireDatabaseAuthority( + "enumerate", "firemud_game_design_baseline_writer", false)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("migration DB credential does not match the required mode"); + assertThatThrownBy( + () -> + EntityDigestBaselineMigrationJobRunner.requireDatabaseAuthority( + "migrate", "firemud", false)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("migration DB credential does not match the required mode"); + assertThatThrownBy( + () -> + EntityDigestBaselineMigrationJobRunner.requireDatabaseAuthority( + "migrate", "firemud_game_design_baseline_writer", true)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("migration Job requires Flyway to be disabled"); + } + @Test void constructsWithTheRuntimeMapperWhenMigrationIsEnabled() { contextRunner @@ -101,5 +140,10 @@ static class MigrationRunnerConfiguration { EntityDigestBaselineMigrationService migrationService() { return mock(EntityDigestBaselineMigrationService.class); } + + @Bean + DataSource dataSource() { + return mock(DataSource.class); + } } } From 74297cac396e0db4a1d93b048c3cb89e181d516e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 05:23:05 +1300 Subject: [PATCH 15/28] Restrict baseline migration version lock to scoped function --- .../game-design-service/operations.md | 2 +- .../repository/VersionRepository.java | 21 +++ ...tyDigestBaselineMigrationWriteService.java | 3 +- ...ed_entity_digest_baseline_version_lock.sql | 44 +++++++ ...igestBaselineMigrationIntegrationTest.java | 121 +++++++++++++++--- ...ityDigestBaselineMigrationServiceTest.java | 12 +- ...gestBaselineMigrationWriteServiceTest.java | 12 +- 7 files changed, 190 insertions(+), 25 deletions(-) create mode 100644 services/game-design-service/src/main/resources/db/migration/V30__restricted_entity_digest_baseline_version_lock.sql diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 29e6ec0769..588581dfbe 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -38,7 +38,7 @@ Before invoking a Job, verify the exact Kubernetes context and namespace, the au The chart's `previewStack.entityDigestBaselineMigration` values are disabled by default. From the trusted operator revision, supply an image pinned as `repository@sha256:`, exact `targetNamespace`, the dedicated `firemud-grpc-game-design-baseline-migrator` Secret, and `mode`. The chart requires the separately provisioned `firemud-game-design-baseline-reader-db` Secret for `enumerate` and `preflight`, and `firemud-game-design-baseline-writer-db` for `migrate`; both must provide `FIREMUD_POSTGRES_USER` and `FIREMUD_POSTGRES_PASSWORD`. A trusted database operator provisions these least-privilege credentials; the chart does not create them, and the Job never consumes the shared `firemud-secret` bootstrap credentials. The migration Job disables Flyway. `enumerate` returns at most 500 Entity schema-v1 full-version rows after one baseline ID and reports each scope's migration status, including `BLOCKED_DRAFT`; repeat with its returned keyset cursor until an empty page proves no more rows at the quiesced snapshot. `preflight` classifies one exact tenant/version as v1, v2, absent, ambiguous, unsupported, or `BLOCKED_DRAFT`, and refuses a missing or script-only Version. `migrate` requires one stable operation ID, exact tenant/version, actor identity, and the immutable expected-source object. It rejects a DRAFT Version before reading the Entity digest and locks/rechecks the Version row in the same transaction as the guarded baseline update and audit insertion, closing the state-change race at that write boundary. This guard does not freeze authoring while the external digest is read. The Java runner verifies its namespace, dedicated service account, and certificate URI identity before reading or writing. A missing identity, policy, input, row, version, exact-old match, or v2 Entity response fails closed. Render and inspect the operator overlay before installation; do not leave `enabled: true` in the ordinary chart values or an unattended release upgrade. Completed Jobs are deliberately not Helm hooks, so an unchanged upgrade does not rerun them; a changed immutable Job spec is rejected and needs an explicit trusted disposition. -Before enabling the Job, a trusted database operator provisions `firemud_game_design_baseline_reader` and `firemud_game_design_baseline_writer` as separate login roles with no superuser, database/role-creation, replication, bypass-RLS, inherited-role, or application-object ownership powers. Both may connect to the selected database, use `game_design_service`, and select only Game Design `version` and `publish_recorded_participant_digest`; the writer additionally needs audit-table select/insert, usage/select on `entity_digest_baseline_migration_audit_id_seq`, and column-limited update of only `applied_commit_id`, `content_digest`, and `digest_schema_version` on the baseline table. Neither role gets Entity or another service's schema access, Version or Flyway-history writes, baseline insert/delete, broad table grants, or DDL. Revoke broader/default grants first, then read back effective role attributes, memberships, ownership, table/column/sequence grants, and denied operations as the restricted users. Verify the mode-specific Secret's exact username/password authentication and V29 presence before live activation; a rendered Secret reference is not proof of those facts. Retire both Secrets and roles after final database readback and the approved rollback window. +Before enabling the Job, a trusted database operator provisions `firemud_game_design_baseline_reader` and `firemud_game_design_baseline_writer` as separate login roles with no superuser, database/role-creation, replication, bypass-RLS, inherited-role, or application-object ownership powers. Both may connect to the selected database, use `game_design_service`, and select only Game Design `version` and `publish_recorded_participant_digest`; the writer additionally needs audit-table select/insert, usage/select on `entity_digest_baseline_migration_audit_id_seq`, and column-limited update of only `applied_commit_id`, `content_digest`, and `digest_schema_version` on the baseline table. Neither role gets Entity or another service's schema access, Version or Flyway-history writes, baseline insert/delete, broad table grants, or DDL. V30 creates a Game Design-owned `SECURITY DEFINER` function that locks and reads only the exact tenant/version row for the guarded migration transaction, with public execute revoked. After V30 is applied and the restricted roles exist, the trusted database operator grants `EXECUTE` on `game_design_service.lock_version_for_entity_digest_baseline_migration(VARCHAR(36), BIGINT)` only to the writer; the reader and public roles must remain denied. This narrow call replaces direct `SELECT ... FOR UPDATE`, which requires Version UPDATE privilege even when the Job changes no Version column. Revoke broader/default grants first, then read back effective role attributes, memberships, ownership, table/column/sequence/function grants, and denied direct Version lock/update operations as the restricted users. Verify the mode-specific Secret's exact username/password authentication and both V29 and V30 presence before live activation; a rendered Secret reference is not proof of those facts. Retire both Secrets and roles after final database readback and the approved rollback window. For each affected scope, retain the preflight row ID and complete source tuple privately, run `migrate`, and require its reported operation/audit/baseline IDs and disposition. The Game Design transaction conditionally replaces the exact old row and inserts an immutable before/after audit atomically. The live row retains its original and last real publish-workflow IDs and timestamps; only the audit's operation ID and committed time describe the maintenance transition. An exact retry of the same operation reads the existing audit and baseline rather than writing again; a lost acknowledgement is resolved by that same operation identity and exact readback. A changed source, ambiguous scope, different actor/workload binding, mismatched Entity v2 schema/scope/digest/commit, or unproved write outcome is a stop condition. Independently read back `publish_recorded_participant_digest` by baseline ID and `entity_digest_baseline_migration_audit` by operation ID from Game Design's PostgreSQL schema; compare the new schema/digest/commit and preserved publish provenance, complete old tuple, observed v2 tuple, migration operation, actor/workload, outcome, and timestamp exactly. Never count Job completion alone as database proof. Keep the before/after records with the private migration log, excluding secrets and certificate keys. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java index 5fba18a82c..f1b351c0e9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java @@ -20,6 +20,8 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class VersionRepository { + private static final String ENTITY_DIGEST_BASELINE_MIGRATION_VERSION_LOCK_FUNCTION = + "game_design_service.lock_version_for_entity_digest_baseline_migration"; private static final Table VERSION_TABLE = DSL.table(DSL.name("version")); private static final Field ID = DSL.field(DSL.name("id"), Long.class); private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); @@ -88,6 +90,25 @@ public Optional findByTenantIdAndIdForUpdate(String tenantId, Long id) .fetchOne(this::toEntity)); } + /** + * Reads and locks the exact version row through the restricted migration-only database function. + * The function performs the lock with its owner privileges so the migration writer need not have + * direct Version UPDATE privilege. + */ + public Optional findByTenantIdAndIdForEntityDigestBaselineMigration( + String tenantId, Long id) { + return Optional.ofNullable( + dsl.resultQuery( + "SELECT id, tenant_id, version_number, version_state, version_state_epoch, " + + "script_patch_version, base_version_id, is_script_only, notes, " + + "created_at, updated_at FROM " + + ENTITY_DIGEST_BASELINE_MIGRATION_VERSION_LOCK_FUNCTION + + "(?, ?)", + tenantId, + id) + .fetchOne(this::toEntity)); + } + /** * Returns every published script-patch candidate for an exact tenant/base/patch scope. Callers * reject anything other than one row so duplicate retained scope is fail-closed. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java index 8228d4ec1d..7e8cc456cc 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java @@ -45,7 +45,8 @@ public void commit( } var version = versionRepository - .findByTenantIdAndIdForUpdate(expectedOld.getTenantId(), versionId) + .findByTenantIdAndIdForEntityDigestBaselineMigration( + expectedOld.getTenantId(), versionId) .orElseThrow(() -> new IllegalStateException("migration version disappeared")); if (version.getVersionState() == VersionLifecycleState.DRAFT) { throw new DraftVersionException(); diff --git a/services/game-design-service/src/main/resources/db/migration/V30__restricted_entity_digest_baseline_version_lock.sql b/services/game-design-service/src/main/resources/db/migration/V30__restricted_entity_digest_baseline_version_lock.sql new file mode 100644 index 0000000000..9264781e45 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V30__restricted_entity_digest_baseline_version_lock.sql @@ -0,0 +1,44 @@ +-- [jooq ignore start] +CREATE FUNCTION game_design_service.lock_version_for_entity_digest_baseline_migration( + p_tenant_id VARCHAR(36), + p_version_id BIGINT +) +RETURNS TABLE ( + id BIGINT, + tenant_id VARCHAR(36), + version_number INTEGER, + version_state VARCHAR(32), + version_state_epoch BIGINT, + script_patch_version VARCHAR(100), + base_version_id BIGINT, + is_script_only BOOLEAN, + notes VARCHAR(255), + created_at TIMESTAMP, + updated_at TIMESTAMP +) +LANGUAGE SQL +SECURITY DEFINER +SET search_path = pg_catalog +AS $$ + SELECT + version_row.id, + version_row.tenant_id, + version_row.version_number, + version_row.version_state, + version_row.version_state_epoch, + version_row.script_patch_version, + version_row.base_version_id, + version_row.is_script_only, + version_row.notes, + version_row.created_at, + version_row.updated_at + FROM game_design_service.version AS version_row + WHERE version_row.tenant_id = p_tenant_id + AND version_row.id = p_version_id + FOR UPDATE +$$; + +REVOKE EXECUTE ON FUNCTION game_design_service.lock_version_for_entity_digest_baseline_migration( + VARCHAR(36), BIGINT +) FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java index 3249cee722..a0165149e9 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java @@ -344,11 +344,13 @@ void databaseMigrationRolesHaveOnlyTheirDirectTablePrivileges() throws Exception RecordedParticipantDigest baseline = seedEntityBaseline("9701", version, 1); provisionMigrationDatabaseRoles(); - try (Connection reader = connectAs("firemud_game_design_baseline_reader_test", "reader-proof")) { + try (Connection reader = + connectAs("firemud_game_design_baseline_reader_test", postgres.getPassword())) { assertThat(reader.getMetaData().getUserName()) .isEqualTo("firemud_game_design_baseline_reader_test"); assertCount(reader, "version"); assertCount(reader, "publish_recorded_participant_digest"); + assertVersionLockDenied(reader, "9701", version.getId()); assertDenied( reader, "UPDATE game_design_service.publish_recorded_participant_digest " @@ -359,20 +361,49 @@ void databaseMigrationRolesHaveOnlyTheirDirectTablePrivileges() throws Exception + "(tenant_id) VALUES ('forbidden')"); assertDenied(reader, "CREATE TABLE game_design_service.reader_forbidden (id integer)"); assertDenied( - reader, - "CREATE TABLE baseline_migration_other_schema.reader_forbidden (id integer)"); + reader, "CREATE TABLE baseline_migration_other_schema.reader_forbidden (id integer)"); assertDenied( - reader, - "UPDATE baseline_migration_other_schema.sentinel SET id = id WHERE false"); + reader, "UPDATE baseline_migration_other_schema.sentinel SET id = id WHERE false"); } - try (Connection writer = connectAs("firemud_game_design_baseline_writer_test", "writer-proof")) { + try (Connection writer = + connectAs("firemud_game_design_baseline_writer_test", postgres.getPassword())) { assertThat(writer.getMetaData().getUserName()) .isEqualTo("firemud_game_design_baseline_writer_test"); assertCount(writer, "version"); assertCount(writer, "publish_recorded_participant_digest"); assertCount(writer, "entity_digest_baseline_migration_audit"); + writer.setAutoCommit(false); + try (PreparedStatement lock = + writer.prepareStatement( + "SELECT id, tenant_id, version_number, version_state, version_state_epoch," + + " script_patch_version, base_version_id, is_script_only, notes, created_at," + + " updated_at FROM" + + " game_design_service.lock_version_for_entity_digest_baseline_migration(?," + + " ?)")) { + lock.setString(1, "9701"); + lock.setLong(2, version.getId()); + try (var rows = lock.executeQuery()) { + assertThat(rows.next()).isTrue(); + assertThat(rows.getLong("id")).isEqualTo(version.getId()); + assertThat(rows.getString("tenant_id")).isEqualTo("9701"); + assertThat(rows.getInt("version_number")).isEqualTo(1); + assertThat(rows.getString("version_state")).isEqualTo("PUBLISHED"); + assertThat(rows.getLong("version_state_epoch")).isEqualTo(version.getVersionStateEpoch()); + assertThat(rows.getString("script_patch_version")) + .isEqualTo(version.getScriptPatchVersion()); + assertThat(rows.getObject("base_version_id")).isNull(); + assertThat(rows.getBoolean("is_script_only")).isFalse(); + assertThat(rows.getString("notes")).isEqualTo(version.getNotes()); + assertThat(rows.next()).isFalse(); + } + } + writer.commit(); + assertNoVersionLockRow(writer, "wrong-tenant", version.getId()); + assertNoVersionLockRow(writer, "9701", version.getId() + 1_000_000L); + writer.setAutoCommit(true); + try (PreparedStatement update = writer.prepareStatement( "UPDATE game_design_service.publish_recorded_participant_digest " @@ -421,8 +452,7 @@ void databaseMigrationRolesHaveOnlyTheirDirectTablePrivileges() throws Exception + "SET tenant_id = 'forbidden' WHERE id = " + baseline.getId()); assertDenied( - writer, - "INSERT INTO game_design_service.version (tenant_id) VALUES ('forbidden')"); + writer, "INSERT INTO game_design_service.version (tenant_id) VALUES ('forbidden')"); assertDenied( writer, "SELECT id FROM game_design_service.version WHERE id = " @@ -434,11 +464,16 @@ void databaseMigrationRolesHaveOnlyTheirDirectTablePrivileges() throws Exception + "SET success = success WHERE false"); assertDenied(writer, "CREATE TABLE game_design_service.writer_forbidden (id integer)"); assertDenied( - writer, - "CREATE TABLE baseline_migration_other_schema.writer_forbidden (id integer)"); + writer, "CREATE TABLE baseline_migration_other_schema.writer_forbidden (id integer)"); assertDenied( - writer, - "UPDATE baseline_migration_other_schema.sentinel SET id = id WHERE false"); + writer, "UPDATE baseline_migration_other_schema.sentinel SET id = id WHERE false"); + } + + try (Connection unrelated = + connectAs("firemud_game_design_baseline_unrelated_test", postgres.getPassword())) { + assertThat(unrelated.getMetaData().getUserName()) + .isEqualTo("firemud_game_design_baseline_unrelated_test"); + assertVersionLockDenied(unrelated, "9701", version.getId()); } } @@ -448,15 +483,27 @@ private void provisionMigrationDatabaseRoles() throws SQLException { postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); Statement statement = admin.createStatement()) { statement.execute( - "CREATE ROLE firemud_game_design_baseline_reader_test LOGIN NOINHERIT PASSWORD 'reader-proof'"); + "CREATE ROLE firemud_game_design_baseline_reader_test LOGIN NOINHERIT PASSWORD" + + " 'test'"); + statement.execute( + "CREATE ROLE firemud_game_design_baseline_writer_test LOGIN NOINHERIT PASSWORD" + + " 'test'"); statement.execute( - "CREATE ROLE firemud_game_design_baseline_writer_test LOGIN NOINHERIT PASSWORD 'writer-proof'"); + "CREATE ROLE firemud_game_design_baseline_unrelated_test LOGIN NOINHERIT " + + "PASSWORD 'test'"); statement.execute("CREATE SCHEMA baseline_migration_other_schema"); statement.execute( "CREATE TABLE baseline_migration_other_schema.sentinel (id integer NOT NULL)"); statement.execute("INSERT INTO baseline_migration_other_schema.sentinel VALUES (1)"); - statement.execute("GRANT USAGE ON SCHEMA game_design_service TO firemud_game_design_baseline_reader_test"); - statement.execute("GRANT USAGE ON SCHEMA game_design_service TO firemud_game_design_baseline_writer_test"); + statement.execute( + "GRANT USAGE ON SCHEMA game_design_service TO " + + "firemud_game_design_baseline_reader_test"); + statement.execute( + "GRANT USAGE ON SCHEMA game_design_service TO " + + "firemud_game_design_baseline_writer_test"); + statement.execute( + "GRANT USAGE ON SCHEMA game_design_service TO" + + " firemud_game_design_baseline_unrelated_test"); statement.execute( "GRANT SELECT ON TABLE game_design_service.version, " + "game_design_service.publish_recorded_participant_digest " @@ -477,6 +524,11 @@ private void provisionMigrationDatabaseRoles() throws SQLException { "GRANT USAGE, SELECT ON SEQUENCE " + "game_design_service.entity_digest_baseline_migration_audit_id_seq " + "TO firemud_game_design_baseline_writer_test"); + statement.execute( + "GRANT EXECUTE ON FUNCTION " + + "game_design_service.lock_version_for_entity_digest_baseline_migration(" + + "VARCHAR(36), BIGINT) " + + "TO firemud_game_design_baseline_writer_test"); } } @@ -488,13 +540,46 @@ private Connection connectAs(String username, String password) throws SQLExcepti private void assertCount(Connection connection, String tableName) throws SQLException { try (Statement statement = connection.createStatement(); var rows = - statement.executeQuery( - "SELECT COUNT(*) FROM game_design_service." + tableName)) { + statement.executeQuery("SELECT COUNT(*) FROM game_design_service." + tableName)) { assertThat(rows.next()).isTrue(); assertThat(rows.getLong(1)).isGreaterThanOrEqualTo(0); } } + private void assertNoVersionLockRow(Connection connection, String tenantId, long versionId) + throws SQLException { + try (PreparedStatement lock = + connection.prepareStatement( + "SELECT id FROM " + + "game_design_service.lock_version_for_entity_digest_baseline_migration(?, ?)")) { + lock.setString(1, tenantId); + lock.setLong(2, versionId); + try (var rows = lock.executeQuery()) { + assertThat(rows.next()).isFalse(); + } + } + } + + private void assertVersionLockDenied(Connection connection, String tenantId, long versionId) + throws SQLException { + try (PreparedStatement lock = + connection.prepareStatement( + "SELECT id FROM " + + "game_design_service.lock_version_for_entity_digest_baseline_migration(?, ?)")) { + lock.setString(1, tenantId); + lock.setLong(2, versionId); + try { + try (var rows = lock.executeQuery()) { + assertThat(rows.next()).isFalse(); + } + } catch (SQLException denied) { + assertThat(denied.getSQLState()).isEqualTo("42501"); + return; + } + } + throw new AssertionError("restricted migration role unexpectedly executed version lock"); + } + private void assertDenied(Connection connection, String sql) throws SQLException { try (Statement statement = connection.createStatement()) { try { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java index 8cec5bc91f..5634dfb891 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java @@ -211,7 +211,8 @@ void migrateRejectsDraftObservedAtGuardedWriteBoundary() { stubInitialMigrationReads(persistedBaseline, persistedAudit); Version draftAtCommit = version(); draftAtCommit.setVersionState(VersionLifecycleState.DRAFT); - when(versionRepository.findByTenantIdAndIdForUpdate(TENANT_ID, VERSION_ID)) + when(versionRepository.findByTenantIdAndIdForEntityDigestBaselineMigration( + TENANT_ID, VERSION_ID)) .thenReturn(Optional.of(draftAtCommit)); when(entityManagementClient.getDraftDesignDigestForVersion(any())) .thenReturn(v2Digest("v2-content", "version:42")); @@ -226,6 +227,9 @@ void migrateRejectsDraftObservedAtGuardedWriteBoundary() { assertTrue(persistedAudit.get() == null); verify(baselineRepository, never()).migrateEntityFullVersionBaselineIfUnchanged(any(), any()); verify(auditRepository, never()).insert(any()); + verify(versionRepository) + .findByTenantIdAndIdForEntityDigestBaselineMigration(TENANT_ID, VERSION_ID); + verify(versionRepository, never()).findByTenantIdAndIdForUpdate(TENANT_ID, VERSION_ID); } @Test @@ -239,7 +243,8 @@ void migrationCommitsAndProvesExactV2BaselineAndAuditReadback() { new EntityDigestBaselineMigrationService( baselineRepository, auditRepository, versionRepository, entityManagementClient, writer); stubInitialMigrationReads(persistedBaseline, persistedAudit); - when(versionRepository.findByTenantIdAndIdForUpdate(TENANT_ID, VERSION_ID)) + when(versionRepository.findByTenantIdAndIdForEntityDigestBaselineMigration( + TENANT_ID, VERSION_ID)) .thenReturn(Optional.of(version())); when(entityManagementClient.getDraftDesignDigestForVersion(any())) .thenReturn(v2Digest("v2-content", "version:42")); @@ -281,6 +286,9 @@ void migrationCommitsAndProvesExactV2BaselineAndAuditReadback() { assertEquals(source.getLastVerifiedAt(), persistedBaseline.get().getLastVerifiedAt()); assertEquals(source.getContentDigest(), persistedAudit.get().sourceContentDigest()); assertEquals("v2-content", persistedAudit.get().observedContentDigest()); + verify(versionRepository) + .findByTenantIdAndIdForEntityDigestBaselineMigration(TENANT_ID, VERSION_ID); + verify(versionRepository, never()).findByTenantIdAndIdForUpdate(TENANT_ID, VERSION_ID); } @Test diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java index 6f8a0fc7ab..221bcc3697 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java @@ -48,7 +48,7 @@ void setUp() { void draftAtGuardedWriteBoundaryPreventsBaselineAndAuditWrites() { Version draft = new Version(); draft.setVersionState(VersionLifecycleState.DRAFT); - when(versionRepository.findByTenantIdAndIdForUpdate("tenant-7", 42L)) + when(versionRepository.findByTenantIdAndIdForEntityDigestBaselineMigration("tenant-7", 42L)) .thenReturn(java.util.Optional.of(draft)); assertThrows( @@ -57,13 +57,15 @@ void draftAtGuardedWriteBoundaryPreventsBaselineAndAuditWrites() { verify(baselineRepository, never()).migrateEntityFullVersionBaselineIfUnchanged(any(), any()); verify(auditRepository, never()).insert(any()); + verify(versionRepository).findByTenantIdAndIdForEntityDigestBaselineMigration("tenant-7", 42L); + verify(versionRepository, never()).findByTenantIdAndIdForUpdate("tenant-7", 42L); } @Test void compareAndSetAndAuditAreBothRequiredForCommit() { Version version = new Version(); version.setVersionState(VersionLifecycleState.PUBLISHED); - when(versionRepository.findByTenantIdAndIdForUpdate("tenant-7", 42L)) + when(versionRepository.findByTenantIdAndIdForEntityDigestBaselineMigration("tenant-7", 42L)) .thenReturn(java.util.Optional.of(version)); when(baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(source, replacement)) .thenReturn(1); @@ -72,13 +74,15 @@ void compareAndSetAndAuditAreBothRequiredForCommit() { verify(baselineRepository).migrateEntityFullVersionBaselineIfUnchanged(source, replacement); verify(auditRepository).insert(audit); + verify(versionRepository).findByTenantIdAndIdForEntityDigestBaselineMigration("tenant-7", 42L); + verify(versionRepository, never()).findByTenantIdAndIdForUpdate("tenant-7", 42L); } @Test void changedRowPreventsAuditInsert() { Version version = new Version(); version.setVersionState(VersionLifecycleState.PUBLISHED); - when(versionRepository.findByTenantIdAndIdForUpdate("tenant-7", 42L)) + when(versionRepository.findByTenantIdAndIdForEntityDigestBaselineMigration("tenant-7", 42L)) .thenReturn(java.util.Optional.of(version)); when(baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(source, replacement)) .thenReturn(0); @@ -86,6 +90,8 @@ void changedRowPreventsAuditInsert() { assertThrows(IllegalStateException.class, () -> service.commit(source, replacement, audit)); verify(auditRepository, never()).insert(any()); + verify(versionRepository).findByTenantIdAndIdForEntityDigestBaselineMigration("tenant-7", 42L); + verify(versionRepository, never()).findByTenantIdAndIdForUpdate("tenant-7", 42L); } @Test From 8dda4dce002fdb69f59904b7f77339d3037df12d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 05:48:57 +1300 Subject: [PATCH 16/28] Include authored equipment vocabulary in Entity v2 digest --- .../api-contracts.md | 4 +- .../runtime-and-data.md | 2 +- .../BodyLayoutSlotDefinitionRepository.java | 15 ++ .../EquipmentSlotDefinitionRepository.java | 13 ++ .../EntityDraftDesignDigestServiceImpl.java | 48 ++++ ...ntityDraftDesignDigestServiceImplTest.java | 217 ++++++++++++++++-- 6 files changed, 283 insertions(+), 16 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index a0a5ee1f81..c017daa5cb 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -80,8 +80,8 @@ Entity Management is a required publish-gate participant and must maintain a sta Implementation Notes: - The current implementation hashes the version-scoped entity-definition rows for the requested `(tenantId, versionId)` and returns synthetic `appliedCommitId = "version:"` until the later applied-revision ledger lands. -- Current version-scoped digest inputs include `items`, `npcs`, and `crafting_recipes`; later entity-template families must join this same `(tenantId, versionId)` digest contract when introduced. -- The current item projection includes optional `equipmentSlot` and `equipmentSlotGroupKey`, normalized like runtime equipment admission (null/blank to empty; otherwise trim and uppercase), and optional `effectPayloadJson`, canonicalized as parsed JSON with recursively stable object-key ordering (null/blank to empty; malformed nonblank JSON fails closed). It reports `digestSchemaVersion=2`. Focused producer proof covers normalized slot and slot-group equivalents, distinct slot and slot-group constraints, equivalent and distinct effect payloads, malformed payload rejection, and tenant/version-scoped reads; Game Design's publish gate accepts Entity v2 and rejects v1 or unsupported evidence. Previously recorded v1 evidence still requires affected-scope replay or recomputation, re-recording, and readback before publish; this code change does not perform a live-data migration. +- Current version-scoped digest inputs include `items`, `npcs`, `crafting_recipes`, `equipment_slot_definitions`, and `body_layout_slot_definitions`; later entity-template families must join this same `(tenantId, versionId)` digest contract when introduced. +- The current item projection includes optional `equipmentSlot` and `equipmentSlotGroupKey`, normalized like runtime equipment admission (null/blank to empty; otherwise trim and uppercase), and optional `effectPayloadJson`, canonicalized as parsed JSON with recursively stable object-key ordering (null/blank to empty; malformed nonblank JSON fails closed). Equipment-slot definitions contribute normalized slot and group keys plus display name; body-layout membership contributes normalized layout and slot keys. Both projections are sorted by semantic keys and exclude database row IDs and optimistic version counters. It reports `digestSchemaVersion=2`. Focused producer proof covers normalized slot and slot-group equivalents, definition-side slot/group/layout changes, row-order and optimistic-version equivalence, distinct effect payloads, malformed payload rejection, and tenant/version-scoped reads; Game Design's publish gate accepts Entity v2 and rejects v1 or unsupported evidence. Previously recorded v1 evidence still requires affected-scope replay or recomputation, re-recording, and readback before publish; this code change does not perform a live-data migration. - Included objects: - version-scoped entity-template tables such as item, NPC, equipment, loot-table, and balance-curve definitions keyed by `(tenantId, versionId)`; diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 7fb4fe27f2..8b5540bd9d 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -19,7 +19,7 @@ This document defines Entity Management’s runtime model, persistence ownership - The live Entity schema does not yet represent the target namespace-stable identity for durable S1/S2 state: `characters` and `actor_resource_states` retain legacy `playable_state_key`, while `inventory`, `character_friend`, `character_equipment`, and durable holder/containment rows omit `playableStateNamespaceId` (and some omit `tenant_id` entirely). The current repositories consequently cannot enforce the target `{tenantId, playableStateNamespaceId, domainObjectId}` identity at the SQL boundary. A convergent migration, legacy-row disposition/backfill evidence, namespace-aware repository predicates, and focused isolation proof remain required; until those are complete, legacy `playable_state_key` rows (including `character_friend` associations reached through them) are not namespace-isolated proof and cutover readers must not treat them as namespace-backed survivor state. This does not change the target contract above. - The live `item_stacks` uniqueness constraint includes nullable holder columns, so PostgreSQL can accept duplicate rows for the same tenant/holder/item/fingerprint when another holder column is `NULL`. Inventory and container mutation paths still use find-then-create/save rather than an atomic conflict-safe operation. With no explicit `stackFamilyKey`, source resolution rejects more than one candidate row; with an explicit family key, the current implementation selects the first matching row and does not reject duplicate matches. Target resolution must enforce exactly one matching stack (or fail closed), alongside holder-kind-specific uniqueness or normalized non-null identity, atomic upsert/locking, and concurrent proof. - The current `characterGraph` helper caches `getWithInventory(characterId)` by character ID alone with a TTL and performs no namespace or authoritative version validation. It is not the target namespace-qualified Class A `character-cache:*` contract; until that contract is implemented and proved, this cache is not correctness authority. -- `EntityDraftDesignDigestServiceImpl` now emits `digestSchemaVersion=2`, hashes normalized item `equipmentSlot` and `equipmentSlotGroupKey` to match runtime equipment admission, and canonicalizes nonblank item `effectPayloadJson` as parsed JSON with recursively stable object-key ordering; malformed nonblank JSON fails closed. Focused tests cover equivalent optional-key spellings, normalized slot and slot-group equivalents, distinct slot and slot-group constraints, equivalent and distinct effect payloads, malformed payload rejection, and tenant/version-scoped reads; Game Design's publish gate requires Entity v2 and rejects v1. Existing v1 participant baselines remain invalid: affected `(tenantId, versionId)` evidence must be replayed or recomputed, re-recorded with its applied commit/digest/schema, and read back before publish. No live baseline migration or cross-service publish proof is claimed by this slice. +- `EntityDraftDesignDigestServiceImpl` now emits `digestSchemaVersion=2`, hashes normalized item `equipmentSlot` and `equipmentSlotGroupKey` plus the version-scoped equipment-slot and body-layout membership definitions that affect runtime wear admission, and canonicalizes nonblank item `effectPayloadJson` as parsed JSON with recursively stable object-key ordering; malformed nonblank JSON fails closed. Definition projections sort by semantic keys, include authored slot/group/display and layout-membership values, and omit row IDs and optimistic version counters. Focused tests cover equivalent optional-key spellings, normalized slot and slot-group equivalents, distinct item and definition-side equipment constraints, equivalent and distinct effect payloads, malformed payload rejection, stable row ordering, and tenant/version-scoped reads; Game Design's publish gate requires Entity v2 and rejects v1. Existing v1 participant baselines remain invalid: affected `(tenantId, versionId)` evidence must be replayed or recomputed, re-recorded with its applied commit/digest/schema, and read back before publish. No live baseline migration or cross-service publish proof is claimed by this slice. ## Architecture and Design Notes diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/BodyLayoutSlotDefinitionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/BodyLayoutSlotDefinitionRepository.java index 5f1dd9be56..0198639247 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/BodyLayoutSlotDefinitionRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/BodyLayoutSlotDefinitionRepository.java @@ -3,6 +3,7 @@ import static net.firedevops.firemud.entitymanagement.jooq.Tables.BODY_LAYOUT_SLOT_DEFINITIONS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; import net.firedevops.firemud.entitymanagement.entity.BodyLayoutSlotDefinition; import org.jooq.DSLContext; import org.jooq.Record; @@ -46,6 +47,20 @@ public boolean existsByTenantIdAndVersionIdAndBodyLayoutKeyAndSlotKey( .and(BODY_LAYOUT_SLOT_DEFINITIONS.SLOT_KEY.eq(slotKey)))); } + public List findByTenantIdAndVersionIdOrderByBodyLayoutKeyAscSlotKeyAsc( + Long tenantId, Long versionId) { + return dsl.selectFrom(BODY_LAYOUT_SLOT_DEFINITIONS) + .where( + BODY_LAYOUT_SLOT_DEFINITIONS + .TENANT_ID + .eq(tenantId) + .and(BODY_LAYOUT_SLOT_DEFINITIONS.VERSION_ID.eq(versionId))) + .orderBy( + BODY_LAYOUT_SLOT_DEFINITIONS.BODY_LAYOUT_KEY.asc(), + BODY_LAYOUT_SLOT_DEFINITIONS.SLOT_KEY.asc()) + .fetch(this::toEntity); + } + public BodyLayoutSlotDefinition save(BodyLayoutSlotDefinition entity) { if (entity.getId() == null) { Long id = diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EquipmentSlotDefinitionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EquipmentSlotDefinitionRepository.java index b356bccbde..d83a923ed6 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EquipmentSlotDefinitionRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EquipmentSlotDefinitionRepository.java @@ -3,6 +3,7 @@ import static net.firedevops.firemud.entitymanagement.jooq.Tables.EQUIPMENT_SLOT_DEFINITIONS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; import java.util.Optional; import net.firedevops.firemud.entitymanagement.entity.EquipmentSlotDefinition; import org.jooq.DSLContext; @@ -31,6 +32,18 @@ public boolean existsByTenantIdAndVersionId(Long tenantId, Long versionId) { .and(EQUIPMENT_SLOT_DEFINITIONS.VERSION_ID.eq(versionId)))); } + public List findByTenantIdAndVersionIdOrderBySlotKeyAsc( + Long tenantId, Long versionId) { + return dsl.selectFrom(EQUIPMENT_SLOT_DEFINITIONS) + .where( + EQUIPMENT_SLOT_DEFINITIONS + .TENANT_ID + .eq(tenantId) + .and(EQUIPMENT_SLOT_DEFINITIONS.VERSION_ID.eq(versionId))) + .orderBy(EQUIPMENT_SLOT_DEFINITIONS.SLOT_KEY.asc()) + .fetch(this::toEntity); + } + public boolean existsByTenantIdAndVersionIdAndSlotKey( Long tenantId, Long versionId, String slotKey) { return dsl.fetchExists( diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java index da75590cd3..87900cd1b4 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java @@ -8,8 +8,12 @@ import java.util.Locale; import java.util.Map; import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.entitymanagement.entity.BodyLayoutSlotDefinition; import net.firedevops.firemud.entitymanagement.entity.CraftingIngredient; +import net.firedevops.firemud.entitymanagement.entity.EquipmentSlotDefinition; +import net.firedevops.firemud.entitymanagement.repository.BodyLayoutSlotDefinitionRepository; import net.firedevops.firemud.entitymanagement.repository.CraftingRecipeRepository; +import net.firedevops.firemud.entitymanagement.repository.EquipmentSlotDefinitionRepository; import net.firedevops.firemud.entitymanagement.repository.ItemRepository; import net.firedevops.firemud.entitymanagement.repository.NpcRepository; import net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService; @@ -29,16 +33,22 @@ public class EntityDraftDesignDigestServiceImpl implements EntityDraftDesignDige private final ItemRepository itemRepository; private final NpcRepository npcRepository; private final CraftingRecipeRepository craftingRecipeRepository; + private final EquipmentSlotDefinitionRepository equipmentSlotDefinitionRepository; + private final BodyLayoutSlotDefinitionRepository bodyLayoutSlotDefinitionRepository; private final ObjectMapper objectMapper; public EntityDraftDesignDigestServiceImpl( ItemRepository itemRepository, NpcRepository npcRepository, CraftingRecipeRepository craftingRecipeRepository, + EquipmentSlotDefinitionRepository equipmentSlotDefinitionRepository, + BodyLayoutSlotDefinitionRepository bodyLayoutSlotDefinitionRepository, ObjectMapper objectMapper) { this.itemRepository = itemRepository; this.npcRepository = npcRepository; this.craftingRecipeRepository = craftingRecipeRepository; + this.equipmentSlotDefinitionRepository = equipmentSlotDefinitionRepository; + this.bodyLayoutSlotDefinitionRepository = bodyLayoutSlotDefinitionRepository; this.objectMapper = objectMapper; } @@ -123,6 +133,44 @@ public EntityDraftDesignDigest getDraftDesignDigest(String tenantId, String vers "itemId", ingredient.getItem().getId(), "quantity", ingredient.getQuantity())) .toList())) + .toList(), + "equipmentSlotDefinitions", + equipmentSlotDefinitionRepository + .findByTenantIdAndVersionIdOrderBySlotKeyAsc(tenantKey, versionKey) + .stream() + .sorted( + Comparator.comparing( + (EquipmentSlotDefinition definition) -> + normalizeOptionalKey(definition.getSlotKey())) + .thenComparing(definition -> value(definition.getDisplayName())) + .thenComparing( + definition -> + normalizeOptionalKey(definition.getSlotGroupKey()))) + .map( + definition -> + Map.of( + "slotKey", normalizeOptionalKey(definition.getSlotKey()), + "displayName", value(definition.getDisplayName()), + "slotGroupKey", + normalizeOptionalKey(definition.getSlotGroupKey()))) + .toList(), + "bodyLayoutSlotDefinitions", + bodyLayoutSlotDefinitionRepository + .findByTenantIdAndVersionIdOrderByBodyLayoutKeyAscSlotKeyAsc( + tenantKey, versionKey) + .stream() + .sorted( + Comparator.comparing( + (BodyLayoutSlotDefinition definition) -> + normalizeOptionalKey(definition.getBodyLayoutKey())) + .thenComparing( + definition -> normalizeOptionalKey(definition.getSlotKey()))) + .map( + definition -> + Map.of( + "bodyLayoutKey", + normalizeOptionalKey(definition.getBodyLayoutKey()), + "slotKey", normalizeOptionalKey(definition.getSlotKey()))) .toList())); return new EntityDraftDesignDigest( tenantId, diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java index 2d8766b548..ff14fdedcd 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java @@ -5,8 +5,12 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.List; +import net.firedevops.firemud.entitymanagement.entity.BodyLayoutSlotDefinition; +import net.firedevops.firemud.entitymanagement.entity.EquipmentSlotDefinition; import net.firedevops.firemud.entitymanagement.entity.Item; +import net.firedevops.firemud.entitymanagement.repository.BodyLayoutSlotDefinitionRepository; import net.firedevops.firemud.entitymanagement.repository.CraftingRecipeRepository; +import net.firedevops.firemud.entitymanagement.repository.EquipmentSlotDefinitionRepository; import net.firedevops.firemud.entitymanagement.repository.ItemRepository; import net.firedevops.firemud.entitymanagement.repository.NpcRepository; import net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService.EntityDraftDesignDigest; @@ -22,8 +26,7 @@ void rejectsZeroTenantIdBeforeRepositoryReads() { CraftingRecipeRepository craftingRecipeRepository = Mockito.mock(CraftingRecipeRepository.class); EntityDraftDesignDigestServiceImpl service = - new EntityDraftDesignDigestServiceImpl( - itemRepository, npcRepository, craftingRecipeRepository, new ObjectMapper()); + service(itemRepository, npcRepository, craftingRecipeRepository); assertThrows(IllegalArgumentException.class, () -> service.getDraftDesignDigest("0", "7")); @@ -37,8 +40,7 @@ void rejectsZeroVersionIdBeforeRepositoryReads() { CraftingRecipeRepository craftingRecipeRepository = Mockito.mock(CraftingRecipeRepository.class); EntityDraftDesignDigestServiceImpl service = - new EntityDraftDesignDigestServiceImpl( - itemRepository, npcRepository, craftingRecipeRepository, new ObjectMapper()); + service(itemRepository, npcRepository, craftingRecipeRepository); assertThrows(IllegalArgumentException.class, () -> service.getDraftDesignDigest("1", "0")); @@ -58,8 +60,7 @@ void computesDigestFromVersionScopedTemplateRows() { Mockito.when(craftingRecipeRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) .thenReturn(List.of()); EntityDraftDesignDigestServiceImpl service = - new EntityDraftDesignDigestServiceImpl( - itemRepository, npcRepository, craftingRecipeRepository, new ObjectMapper()); + service(itemRepository, npcRepository, craftingRecipeRepository); var digest = service.getDraftDesignDigest("1", "7"); @@ -106,6 +107,122 @@ void distinctEquipmentSlotValuesChangeTheDigest() { assertNotEquals(headDigest.contentDigest(), torsoDigest.contentDigest()); } + @Test + void equipmentSlotDefinitionSemanticsChangeTheDigest() { + var head = slotDefinition("HEAD", "Head", "UPPER"); + var differentDisplayName = slotDefinition("HEAD", "Crown", "UPPER"); + var differentGroup = slotDefinition("HEAD", "Head", "LOWER"); + var differentSlot = slotDefinition("TORSO", "Head", "UPPER"); + + var original = digestForDefinitions(List.of(head), List.of()); + + assertNotEquals( + original.contentDigest(), + digestForDefinitions(List.of(differentDisplayName), List.of()).contentDigest()); + assertNotEquals( + original.contentDigest(), + digestForDefinitions(List.of(differentGroup), List.of()).contentDigest()); + assertNotEquals( + original.contentDigest(), + digestForDefinitions(List.of(differentSlot), List.of()).contentDigest()); + } + + @Test + void bodyLayoutSlotSemanticsChangeTheDigest() { + var original = digestForDefinitions(List.of(), List.of(bodyLayoutSlot("HUMANOID", "HEAD"))); + var differentLayout = + digestForDefinitions(List.of(), List.of(bodyLayoutSlot("QUADRUPED", "HEAD"))); + var differentSlot = + digestForDefinitions(List.of(), List.of(bodyLayoutSlot("HUMANOID", "TORSO"))); + + assertNotEquals(original.contentDigest(), differentLayout.contentDigest()); + assertNotEquals(original.contentDigest(), differentSlot.contentDigest()); + } + + @Test + void canonicalizesVocabularyKeysAndIgnoresRowOrderAndOptimisticVersion() { + var firstSlot = slotDefinition(" HEAD ", "Head", " upper "); + firstSlot.setVersion(2); + var secondSlot = slotDefinition("TORSO", "Torso", null); + secondSlot.setVersion(8); + var firstLayoutSlot = bodyLayoutSlot(" Humanoid ", " Head "); + firstLayoutSlot.setVersion(3); + var secondLayoutSlot = bodyLayoutSlot("HUMANOID", "TORSO"); + secondLayoutSlot.setVersion(9); + + var firstDigest = + digestForDefinitions( + List.of(firstSlot, secondSlot), List.of(firstLayoutSlot, secondLayoutSlot)); + + var normalizedSlot = slotDefinition("HEAD", "Head", "UPPER"); + normalizedSlot.setVersion(200); + var normalizedSecondSlot = slotDefinition("TORSO", "Torso", " "); + normalizedSecondSlot.setVersion(800); + var normalizedFirstLayoutSlot = bodyLayoutSlot("HUMANOID", "HEAD"); + normalizedFirstLayoutSlot.setVersion(300); + var normalizedSecondLayoutSlot = bodyLayoutSlot(" humanoid ", " torso "); + normalizedSecondLayoutSlot.setVersion(900); + + var equivalentDigest = + digestForDefinitions( + List.of(normalizedSecondSlot, normalizedSlot), + List.of(normalizedSecondLayoutSlot, normalizedFirstLayoutSlot)); + + assertEquals(firstDigest.contentDigest(), equivalentDigest.contentDigest()); + } + + @Test + void readsEquipmentVocabularyWithinRequestedTenantAndVersion() { + ItemRepository itemRepository = Mockito.mock(ItemRepository.class); + NpcRepository npcRepository = Mockito.mock(NpcRepository.class); + CraftingRecipeRepository craftingRecipeRepository = + Mockito.mock(CraftingRecipeRepository.class); + EquipmentSlotDefinitionRepository equipmentSlotDefinitionRepository = + Mockito.mock(EquipmentSlotDefinitionRepository.class); + BodyLayoutSlotDefinitionRepository bodyLayoutSlotDefinitionRepository = + Mockito.mock(BodyLayoutSlotDefinitionRepository.class); + for (long tenantId : List.of(1L, 2L)) { + for (long versionId : List.of(7L, 8L)) { + Mockito.when(itemRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantId, versionId)) + .thenReturn(List.of()); + Mockito.when(npcRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantId, versionId)) + .thenReturn(List.of()); + Mockito.when( + craftingRecipeRepository.findByTenantIdAndVersionIdOrderByIdAsc( + tenantId, versionId)) + .thenReturn(List.of()); + Mockito.when( + equipmentSlotDefinitionRepository.findByTenantIdAndVersionIdOrderBySlotKeyAsc( + tenantId, versionId)) + .thenReturn(List.of(slotDefinition("SLOT-" + tenantId + versionId, "Slot", null))); + Mockito.when( + bodyLayoutSlotDefinitionRepository + .findByTenantIdAndVersionIdOrderByBodyLayoutKeyAscSlotKeyAsc( + tenantId, versionId)) + .thenReturn(List.of(bodyLayoutSlot("LAYOUT-" + tenantId + versionId, "SLOT"))); + } + } + EntityDraftDesignDigestServiceImpl service = + new EntityDraftDesignDigestServiceImpl( + itemRepository, + npcRepository, + craftingRecipeRepository, + equipmentSlotDefinitionRepository, + bodyLayoutSlotDefinitionRepository, + new ObjectMapper()); + + var tenantOneVersionSeven = service.getDraftDesignDigest("1", "7"); + var tenantOneVersionEight = service.getDraftDesignDigest("1", "8"); + var tenantTwoVersionSeven = service.getDraftDesignDigest("2", "7"); + + assertNotEquals(tenantOneVersionSeven.contentDigest(), tenantOneVersionEight.contentDigest()); + assertNotEquals(tenantOneVersionSeven.contentDigest(), tenantTwoVersionSeven.contentDigest()); + Mockito.verify(equipmentSlotDefinitionRepository) + .findByTenantIdAndVersionIdOrderBySlotKeyAsc(1L, 7L); + Mockito.verify(bodyLayoutSlotDefinitionRepository) + .findByTenantIdAndVersionIdOrderByBodyLayoutKeyAscSlotKeyAsc(1L, 7L); + } + @Test void canonicalizesEquivalentEffectPayloadJson() { var firstDigest = @@ -168,8 +285,7 @@ void readsItemsWithinTheRequestedTenantAndVersion() { } } EntityDraftDesignDigestServiceImpl service = - new EntityDraftDesignDigestServiceImpl( - itemRepository, npcRepository, craftingRecipeRepository, new ObjectMapper()); + service(itemRepository, npcRepository, craftingRecipeRepository); var tenantOneVersionSeven = service.getDraftDesignDigest("1", "7"); var tenantOneVersionEight = service.getDraftDesignDigest("1", "8"); @@ -195,8 +311,7 @@ private static EntityDraftDesignDigest digestForEquipmentSlotGroupKey(String gro Mockito.when(craftingRecipeRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) .thenReturn(List.of()); EntityDraftDesignDigestServiceImpl service = - new EntityDraftDesignDigestServiceImpl( - itemRepository, npcRepository, craftingRecipeRepository, new ObjectMapper()); + service(itemRepository, npcRepository, craftingRecipeRepository); return service.getDraftDesignDigest("1", "7"); } @@ -214,13 +329,64 @@ private static EntityDraftDesignDigest digestForEffectPayload(String effectPaylo .thenReturn(List.of()); Mockito.when(craftingRecipeRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) .thenReturn(List.of()); + EntityDraftDesignDigestServiceImpl service = + service(itemRepository, npcRepository, craftingRecipeRepository); + + return service.getDraftDesignDigest("1", "7"); + } + + private static EntityDraftDesignDigest digestForDefinitions( + List slotDefinitions, + List bodyLayoutSlots) { + ItemRepository itemRepository = Mockito.mock(ItemRepository.class); + NpcRepository npcRepository = Mockito.mock(NpcRepository.class); + CraftingRecipeRepository craftingRecipeRepository = + Mockito.mock(CraftingRecipeRepository.class); + EquipmentSlotDefinitionRepository equipmentSlotDefinitionRepository = + Mockito.mock(EquipmentSlotDefinitionRepository.class); + BodyLayoutSlotDefinitionRepository bodyLayoutSlotDefinitionRepository = + Mockito.mock(BodyLayoutSlotDefinitionRepository.class); + Mockito.when(itemRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of()); + Mockito.when(npcRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of()); + Mockito.when(craftingRecipeRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of()); + Mockito.when( + equipmentSlotDefinitionRepository.findByTenantIdAndVersionIdOrderBySlotKeyAsc(1L, 7L)) + .thenReturn(slotDefinitions); + Mockito.when( + bodyLayoutSlotDefinitionRepository + .findByTenantIdAndVersionIdOrderByBodyLayoutKeyAscSlotKeyAsc(1L, 7L)) + .thenReturn(bodyLayoutSlots); EntityDraftDesignDigestServiceImpl service = new EntityDraftDesignDigestServiceImpl( - itemRepository, npcRepository, craftingRecipeRepository, new ObjectMapper()); + itemRepository, + npcRepository, + craftingRecipeRepository, + equipmentSlotDefinitionRepository, + bodyLayoutSlotDefinitionRepository, + new ObjectMapper()); return service.getDraftDesignDigest("1", "7"); } + private static EquipmentSlotDefinition slotDefinition( + String slotKey, String displayName, String slotGroupKey) { + EquipmentSlotDefinition definition = new EquipmentSlotDefinition(); + definition.setSlotKey(slotKey); + definition.setDisplayName(displayName); + definition.setSlotGroupKey(slotGroupKey); + return definition; + } + + private static BodyLayoutSlotDefinition bodyLayoutSlot(String bodyLayoutKey, String slotKey) { + BodyLayoutSlotDefinition definition = new BodyLayoutSlotDefinition(); + definition.setBodyLayoutKey(bodyLayoutKey); + definition.setSlotKey(slotKey); + return definition; + } + private static EntityDraftDesignDigest digestForEquipmentSlot(String equipmentSlot) { Item item = item(11L, null); item.setEquipmentSlot(equipmentSlot); @@ -235,8 +401,7 @@ private static EntityDraftDesignDigest digestForEquipmentSlot(String equipmentSl Mockito.when(craftingRecipeRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) .thenReturn(List.of()); EntityDraftDesignDigestServiceImpl service = - new EntityDraftDesignDigestServiceImpl( - itemRepository, npcRepository, craftingRecipeRepository, new ObjectMapper()); + service(itemRepository, npcRepository, craftingRecipeRepository); return service.getDraftDesignDigest("1", "7"); } @@ -248,4 +413,30 @@ private static Item item(Long id, String equipmentSlotGroupKey) { item.setEquipmentSlotGroupKey(equipmentSlotGroupKey); return item; } + + private static EntityDraftDesignDigestServiceImpl service( + ItemRepository itemRepository, + NpcRepository npcRepository, + CraftingRecipeRepository craftingRecipeRepository) { + EquipmentSlotDefinitionRepository equipmentSlotDefinitionRepository = + Mockito.mock(EquipmentSlotDefinitionRepository.class); + BodyLayoutSlotDefinitionRepository bodyLayoutSlotDefinitionRepository = + Mockito.mock(BodyLayoutSlotDefinitionRepository.class); + Mockito.when( + equipmentSlotDefinitionRepository.findByTenantIdAndVersionIdOrderBySlotKeyAsc( + Mockito.anyLong(), Mockito.anyLong())) + .thenReturn(List.of()); + Mockito.when( + bodyLayoutSlotDefinitionRepository + .findByTenantIdAndVersionIdOrderByBodyLayoutKeyAscSlotKeyAsc( + Mockito.anyLong(), Mockito.anyLong())) + .thenReturn(List.of()); + return new EntityDraftDesignDigestServiceImpl( + itemRepository, + npcRepository, + craftingRecipeRepository, + equipmentSlotDefinitionRepository, + bodyLayoutSlotDefinitionRepository, + new ObjectMapper()); + } } From 8ce4ac8731339b48d83c2e1dba14ff516a484428 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 06:05:19 +1300 Subject: [PATCH 17/28] Run baseline migration Helm contract in CI --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7507732ae8..f16d7b61c1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -382,6 +382,7 @@ jobs: bash ./dev-tools/tests/backup-verifier-image-contract.sh bash ./dev-tools/tests/kubectl-version-skew-contract.sh bash ./dev-tools/tests/helm-transaction-proof-contract.sh + bash ./dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh bash ./dev-tools/tests/preview-image-tag-contract.sh bash ./dev-tools/tests/preview-merge-image-tag-contract.sh bash ./dev-tools/tests/overlay-preflight-contract.sh From 43dc6b34d6dea62401360c0d87c452d649074fed Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 09:06:30 +1300 Subject: [PATCH 18/28] Fence baseline migration across version lifecycle changes --- .../game-design-service/operations.md | 2 +- .../EntityDigestBaselineMigrationService.java | 13 +++++- ...tyDigestBaselineMigrationWriteService.java | 15 +++++- ...igestBaselineMigrationIntegrationTest.java | 5 +- ...ityDigestBaselineMigrationServiceTest.java | 46 +++++++++++++++++-- ...gestBaselineMigrationWriteServiceTest.java | 26 +++++++++-- 6 files changed, 96 insertions(+), 11 deletions(-) diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 588581dfbe..6d5a823fcd 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -36,7 +36,7 @@ Use a controlled pre-v1 publication window for the affected Entity v1 full-versi Before invoking a Job, verify the exact Kubernetes context and namespace, the authorized operator identity and approved maintenance window, both current service image digests, database backup/recovery posture, completed in-flight publication drain, and the dedicated migrator certificate's issuer, `Ready` state, URI SAN, trust chain, projected Secret, and actual mTLS acceptance at Entity. The hosted trust/controller admission policy includes a narrow runtime-namespace exception for this identity; it does not make the migrator one of the controller's permanent certificate consumers. A trusted certificate writer must explicitly invoke `ensure-standalone-transport-certificates.sh --migrator `; a separately authorized Secret-read operator then invokes `--verify-migrator ` before the Job is enabled. The certificate writer's service account has no Secret-read permission. These opt-in operations do not alter ordinary preview transport-certificate rollout. A rendered Certificate or Secret name alone is not issuance or served-identity proof. The trusted operator must create an immutable expected-source ConfigMap or Secret from a read-only exact database row, including baseline ID, tenant, `FULL_VERSION`, `ENTITY_MANAGEMENT`, null base version, version scope, applied commit, digest, schema `1`, and both workflow IDs and timestamps. Do not place this manifest, credentials, or raw retained row values in a PR or CI artifact. Check that the source object is immutable before applying the Job. The Job's `targetNamespace`, tenant/version, operation ID, actor identity, and expected-source object are all fixed for that invocation; a changed command gets a new operation ID, never a reinterpretation of the old one. `actorIdentity` is an operator-supplied audit claim, not an identity attested by the Job's workload certificate. Preserve the trusted deployment audit identifying the authenticated human operator and correlate its Job UID, operation ID, values/image revision, and time with the Game Design before/after audit row; do not use that row alone as proof of the human operator's identity. -The chart's `previewStack.entityDigestBaselineMigration` values are disabled by default. From the trusted operator revision, supply an image pinned as `repository@sha256:`, exact `targetNamespace`, the dedicated `firemud-grpc-game-design-baseline-migrator` Secret, and `mode`. The chart requires the separately provisioned `firemud-game-design-baseline-reader-db` Secret for `enumerate` and `preflight`, and `firemud-game-design-baseline-writer-db` for `migrate`; both must provide `FIREMUD_POSTGRES_USER` and `FIREMUD_POSTGRES_PASSWORD`. A trusted database operator provisions these least-privilege credentials; the chart does not create them, and the Job never consumes the shared `firemud-secret` bootstrap credentials. The migration Job disables Flyway. `enumerate` returns at most 500 Entity schema-v1 full-version rows after one baseline ID and reports each scope's migration status, including `BLOCKED_DRAFT`; repeat with its returned keyset cursor until an empty page proves no more rows at the quiesced snapshot. `preflight` classifies one exact tenant/version as v1, v2, absent, ambiguous, unsupported, or `BLOCKED_DRAFT`, and refuses a missing or script-only Version. `migrate` requires one stable operation ID, exact tenant/version, actor identity, and the immutable expected-source object. It rejects a DRAFT Version before reading the Entity digest and locks/rechecks the Version row in the same transaction as the guarded baseline update and audit insertion, closing the state-change race at that write boundary. This guard does not freeze authoring while the external digest is read. The Java runner verifies its namespace, dedicated service account, and certificate URI identity before reading or writing. A missing identity, policy, input, row, version, exact-old match, or v2 Entity response fails closed. Render and inspect the operator overlay before installation; do not leave `enabled: true` in the ordinary chart values or an unattended release upgrade. Completed Jobs are deliberately not Helm hooks, so an unchanged upgrade does not rerun them; a changed immutable Job spec is rejected and needs an explicit trusted disposition. +The chart's `previewStack.entityDigestBaselineMigration` values are disabled by default. From the trusted operator revision, supply an image pinned as `repository@sha256:`, exact `targetNamespace`, the dedicated `firemud-grpc-game-design-baseline-migrator` Secret, and `mode`. The chart requires the separately provisioned `firemud-game-design-baseline-reader-db` Secret for `enumerate` and `preflight`, and `firemud-game-design-baseline-writer-db` for `migrate`; both must provide `FIREMUD_POSTGRES_USER` and `FIREMUD_POSTGRES_PASSWORD`. A trusted database operator provisions these least-privilege credentials; the chart does not create them, and the Job never consumes the shared `firemud-secret` bootstrap credentials. The migration Job disables Flyway. `enumerate` returns at most 500 Entity schema-v1 full-version rows after one baseline ID and reports each scope's migration status, including `BLOCKED_DRAFT`; repeat with its returned keyset cursor until an empty page proves no more rows at the quiesced snapshot. `preflight` classifies one exact tenant/version as v1, v2, absent, ambiguous, unsupported, or `BLOCKED_DRAFT`, and refuses a missing or script-only Version. `migrate` requires one stable operation ID, exact tenant/version, actor identity, and the immutable expected-source object. It rejects a DRAFT Version before reading the Entity digest, captures the non-DRAFT Version's state epoch, then locks the Version row and requires both non-DRAFT state and the same epoch in the transaction that performs the guarded baseline update and audit insertion. A lifecycle transition during the external digest read therefore fails closed before either write, even if the Version returns to Published. This guard does not freeze authoring while the external digest is read. The Java runner verifies its namespace, dedicated service account, and certificate URI identity before reading or writing. A missing identity, policy, input, row, version, exact-old match, or v2 Entity response fails closed. Render and inspect the operator overlay before installation; do not leave `enabled: true` in the ordinary chart values or an unattended release upgrade. Completed Jobs are deliberately not Helm hooks, so an unchanged upgrade does not rerun them; a changed immutable Job spec is rejected and needs an explicit trusted disposition. Before enabling the Job, a trusted database operator provisions `firemud_game_design_baseline_reader` and `firemud_game_design_baseline_writer` as separate login roles with no superuser, database/role-creation, replication, bypass-RLS, inherited-role, or application-object ownership powers. Both may connect to the selected database, use `game_design_service`, and select only Game Design `version` and `publish_recorded_participant_digest`; the writer additionally needs audit-table select/insert, usage/select on `entity_digest_baseline_migration_audit_id_seq`, and column-limited update of only `applied_commit_id`, `content_digest`, and `digest_schema_version` on the baseline table. Neither role gets Entity or another service's schema access, Version or Flyway-history writes, baseline insert/delete, broad table grants, or DDL. V30 creates a Game Design-owned `SECURITY DEFINER` function that locks and reads only the exact tenant/version row for the guarded migration transaction, with public execute revoked. After V30 is applied and the restricted roles exist, the trusted database operator grants `EXECUTE` on `game_design_service.lock_version_for_entity_digest_baseline_migration(VARCHAR(36), BIGINT)` only to the writer; the reader and public roles must remain denied. This narrow call replaces direct `SELECT ... FOR UPDATE`, which requires Version UPDATE privilege even when the Job changes no Version column. Revoke broader/default grants first, then read back effective role attributes, memberships, ownership, table/column/sequence/function grants, and denied direct Version lock/update operations as the restricted users. Verify the mode-specific Secret's exact username/password authentication and both V29 and V30 presence before live activation; a rendered Secret reference is not proof of those facts. Retire both Secrets and roles after final database readback and the approved rollback window. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java index d2dce05bb8..8368bee60f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java @@ -154,6 +154,10 @@ public MigrationResult migrate(MigrationCommand command) { if (version.getVersionState() == VersionLifecycleState.DRAFT) { throw rejected("VERSION_DRAFT", "mutable DRAFT versions cannot be migrated"); } + Long versionStateEpoch = version.getVersionStateEpoch(); + if (versionStateEpoch == null || versionStateEpoch < 1L) { + throw rejected("VERSION_STATE_EPOCH_MISSING", "version has no valid lifecycle state epoch"); + } RecordedParticipantDigest current = baselineRepository @@ -187,12 +191,19 @@ public MigrationResult migrate(MigrationCommand command) { RecordedParticipantDigest replacement = replacementFor(current, observed); EntityDigestBaselineMigrationAudit audit = auditFor(current, observed, command, migrationTime); try { - writeService.commit(current, replacement, audit); + writeService.commit(current, replacement, audit, versionStateEpoch); } catch (EntityDigestBaselineMigrationWriteService.DraftVersionException draftAtCommit) { throw rejected( "VERSION_DRAFT", "version became DRAFT before the guarded migration write", draftAtCommit); + } catch ( + EntityDigestBaselineMigrationWriteService.VersionStateEpochChangedException + epochChangedAtCommit) { + throw rejected( + "VERSION_STATE_EPOCH_CHANGED", + "version lifecycle changed while the Entity digest was being recomputed", + epochChangedAtCommit); } catch (RuntimeException uncertainWrite) { try { return readBackCommittedResult( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java index 7e8cc456cc..5576f5ab2d 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java @@ -34,8 +34,12 @@ public EntityDigestBaselineMigrationWriteService( public void commit( RecordedParticipantDigest expectedOld, RecordedParticipantDigest replacement, - EntityDigestBaselineMigrationAudit audit) { + EntityDigestBaselineMigrationAudit audit, + long expectedVersionStateEpoch) { validateWriteSet(expectedOld, replacement, audit); + if (expectedVersionStateEpoch < 1L) { + throw new IllegalArgumentException("expected version state epoch must be positive"); + } long versionId; try { versionId = Long.parseLong(expectedOld.getScopeValue()); @@ -51,6 +55,9 @@ public void commit( if (version.getVersionState() == VersionLifecycleState.DRAFT) { throw new DraftVersionException(); } + if (!Objects.equals(version.getVersionStateEpoch(), expectedVersionStateEpoch)) { + throw new VersionStateEpochChangedException(); + } int updated = baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(expectedOld, replacement); if (updated != 1) { @@ -66,6 +73,12 @@ private DraftVersionException() { } } + static final class VersionStateEpochChangedException extends IllegalStateException { + private VersionStateEpochChangedException() { + super("version lifecycle changed while the Entity digest was being recomputed"); + } + } + private void validateWriteSet( RecordedParticipantDigest expectedOld, RecordedParticipantDigest replacement, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java index a0165149e9..f47fdbb504 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java @@ -327,7 +327,10 @@ void auditInsertFailureRollsBackTheGuardedBaselineReplacement() { firstCommand.workloadIdentity(), migrationTime); - assertThatThrownBy(() -> writeService.commit(expectedOld, replacement, duplicateAudit)) + assertThatThrownBy( + () -> + writeService.commit( + expectedOld, replacement, duplicateAudit, secondVersion.getVersionStateEpoch())) .isInstanceOf(RuntimeException.class); RecordedParticipantDigest readback = diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java index 5634dfb891..a1ecf07092 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -232,6 +233,45 @@ void migrateRejectsDraftObservedAtGuardedWriteBoundary() { verify(versionRepository, never()).findByTenantIdAndIdForUpdate(TENANT_ID, VERSION_ID); } + @Test + void migrateRejectsVersionEpochChangedDuringExternalDigestRead() { + AtomicReference persistedBaseline = new AtomicReference<>(source); + AtomicReference persistedAudit = new AtomicReference<>(); + EntityDigestBaselineMigrationWriteService writer = + new EntityDigestBaselineMigrationWriteService( + baselineRepository, auditRepository, versionRepository); + EntityDigestBaselineMigrationService service = + new EntityDigestBaselineMigrationService( + baselineRepository, auditRepository, versionRepository, entityManagementClient, writer); + stubInitialMigrationReads(persistedBaseline, persistedAudit); + AtomicReference lockedVersion = new AtomicReference<>(version()); + Version versionAfterInterveningTransition = version(); + versionAfterInterveningTransition.setVersionStateEpoch(2L); + when(versionRepository.findByTenantIdAndIdForEntityDigestBaselineMigration( + TENANT_ID, VERSION_ID)) + .thenAnswer(invocation -> Optional.of(lockedVersion.get())); + when(entityManagementClient.getDraftDesignDigestForVersion(any())) + .thenAnswer( + invocation -> { + lockedVersion.set(versionAfterInterveningTransition); + return v2Digest("v2-content", "version:42"); + }); + + EntityDigestBaselineMigrationService.MigrationRejectedException rejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> service.migrate(command)); + + assertEquals("VERSION_STATE_EPOCH_CHANGED", rejected.failureCode()); + assertTrue(rejected.getMessage().contains("lifecycle changed")); + assertEquals(1, persistedBaseline.get().getDigestSchemaVersion()); + assertTrue(persistedAudit.get() == null); + verify(baselineRepository, never()).migrateEntityFullVersionBaselineIfUnchanged(any(), any()); + verify(auditRepository, never()).insert(any()); + verify(versionRepository) + .findByTenantIdAndIdForEntityDigestBaselineMigration(TENANT_ID, VERSION_ID); + } + @Test void migrationCommitsAndProvesExactV2BaselineAndAuditReadback() { AtomicReference persistedBaseline = new AtomicReference<>(source); @@ -423,7 +463,7 @@ void uncertainWriterOutcomeSucceedsOnlyWhenExactCommittedReadbackIsFound() { throw new IllegalStateException("connection lost after commit"); }) .when(writer) - .commit(any(), any(), any()); + .commit(any(), any(), any(), anyLong()); when(auditRepository.findByOperationId(OPERATION_ID)) .thenAnswer(invocation -> Optional.ofNullable(persistedAudit.get())); when(baselineRepository.findById(BASELINE_ID)) @@ -456,7 +496,7 @@ void guardedWriteLoserRecoversFromWinnerAuditWithDifferentCommittedAt() { throw new IllegalStateException("guarded migration lost race"); }) .when(writer) - .commit(any(), any(), any()); + .commit(any(), any(), any(), anyLong()); when(auditRepository.findByOperationId(OPERATION_ID)) .thenReturn(Optional.empty(), Optional.of(winnerAudit)); when(baselineRepository.findById(BASELINE_ID)) @@ -484,7 +524,7 @@ void uncertainWriterOutcomeFailsWhenReadbackCannotProveBothRows() { org.mockito.Mockito.mock(EntityDigestBaselineMigrationWriteService.class); doThrow(new IllegalStateException("commit acknowledgement lost")) .when(writer) - .commit(any(), any(), any()); + .commit(any(), any(), any(), anyLong()); when(auditRepository.findByOperationId(OPERATION_ID)) .thenReturn(Optional.empty(), Optional.empty()); when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(source)); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java index 221bcc3697..fcd283c83b 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java @@ -53,7 +53,7 @@ void draftAtGuardedWriteBoundaryPreventsBaselineAndAuditWrites() { assertThrows( EntityDigestBaselineMigrationWriteService.DraftVersionException.class, - () -> service.commit(source, replacement, audit)); + () -> service.commit(source, replacement, audit, 1L)); verify(baselineRepository, never()).migrateEntityFullVersionBaselineIfUnchanged(any(), any()); verify(auditRepository, never()).insert(any()); @@ -65,12 +65,13 @@ void draftAtGuardedWriteBoundaryPreventsBaselineAndAuditWrites() { void compareAndSetAndAuditAreBothRequiredForCommit() { Version version = new Version(); version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(7L); when(versionRepository.findByTenantIdAndIdForEntityDigestBaselineMigration("tenant-7", 42L)) .thenReturn(java.util.Optional.of(version)); when(baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(source, replacement)) .thenReturn(1); - service.commit(source, replacement, audit); + service.commit(source, replacement, audit, 7L); verify(baselineRepository).migrateEntityFullVersionBaselineIfUnchanged(source, replacement); verify(auditRepository).insert(audit); @@ -78,6 +79,22 @@ void compareAndSetAndAuditAreBothRequiredForCommit() { verify(versionRepository, never()).findByTenantIdAndIdForUpdate("tenant-7", 42L); } + @Test + void changedVersionStateEpochPreventsBaselineAndAuditWrites() { + Version version = new Version(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(8L); + when(versionRepository.findByTenantIdAndIdForEntityDigestBaselineMigration("tenant-7", 42L)) + .thenReturn(java.util.Optional.of(version)); + + assertThrows( + EntityDigestBaselineMigrationWriteService.VersionStateEpochChangedException.class, + () -> service.commit(source, replacement, audit, 7L)); + + verify(baselineRepository, never()).migrateEntityFullVersionBaselineIfUnchanged(any(), any()); + verify(auditRepository, never()).insert(any()); + } + @Test void changedRowPreventsAuditInsert() { Version version = new Version(); @@ -87,7 +104,7 @@ void changedRowPreventsAuditInsert() { when(baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(source, replacement)) .thenReturn(0); - assertThrows(IllegalStateException.class, () -> service.commit(source, replacement, audit)); + assertThrows(IllegalStateException.class, () -> service.commit(source, replacement, audit, 1L)); verify(auditRepository, never()).insert(any()); verify(versionRepository).findByTenantIdAndIdForEntityDigestBaselineMigration("tenant-7", 42L); @@ -98,7 +115,8 @@ void changedRowPreventsAuditInsert() { void maintenanceOperationCannotReplacePublishProvenance() { replacement.setRecordedFromPublishWorkflowId("migration-op"); - assertThrows(IllegalArgumentException.class, () -> service.commit(source, replacement, audit)); + assertThrows( + IllegalArgumentException.class, () -> service.commit(source, replacement, audit, 1L)); verify(baselineRepository, never()).migrateEntityFullVersionBaselineIfUnchanged(any(), any()); verify(auditRepository, never()).insert(any()); From eb9f582f752b2a9b487be7d023f22365040c04fb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 09:47:32 +1300 Subject: [PATCH 19/28] Serialize version lifecycle writers for baseline epoch fencing --- .../game-design-service/README.md | 2 +- .../game-design-service/api-contracts.md | 8 +- .../game-design-service/version-control.md | 2 +- .../system-architecture-versioning-runtime.md | 2 +- ...ame-authoring-publishing-and-activation.md | 4 +- .../VersionPublishCommandServiceImpl.java | 18 ++- .../service/impl/VersionServiceImpl.java | 30 ++++- ...igestBaselineMigrationIntegrationTest.java | 120 ++++++++++++++++++ .../VersionPublishCommandServiceImplTest.java | 8 ++ .../service/impl/VersionServiceImplTest.java | 36 ++++++ 10 files changed, 215 insertions(+), 15 deletions(-) diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index 5087b788a6..9c40d81e3e 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -29,7 +29,7 @@ Current capability and proof gaps remain: Game Session's exact pin/epoch persist - **Target state:** Runtime discovery of derived artifacts uses the version `manifest.json` attested by `published_release_bundle`. The target canonical attestation shape includes `artifactDigests[]`, `requiredManifestAssetKeys[]`, and `manifestHash`; the current persisted bundle is narrower and lacks those complete target fields, so consumers must not treat current output as complete release proof or depend on undocumented bucket key conventions. - Own version lifecycle state and CAS epoch metadata (`versionState`, `versionStateEpoch`) and expose control-plane APIs; target activation/retirement-safe transition guards remain unimplemented, as recorded in the implementation status. - Expose control-plane integrity APIs such as `GetDesignControlPlaneDigest` and `CanDeleteVersionAssets` used by publish gating and asset-retention workflows. -- **Target state:** Expose CAS-guarded asset purge APIs (`BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`) so purge eligibility re-check and artifact-state transitions are race-safe. The current repositories update by row ID after service-memory epoch checks without database epoch predicates or affected-row proof; current lifecycle APIs are not race-safe. +- **Target state:** Expose CAS-guarded asset purge APIs (`BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`) so purge eligibility re-check and artifact-state transitions are race-safe. The known Version lifecycle writers now serialize on an exact Version-row lock, but separate purge/repair paths still update by row ID without their required predicate/lock and affected-row proof; current asset lifecycle APIs are not race-safe. - Expose a deterministic launch-resolution API or equivalent control-plane workflow that produces an immutable resolved launch descriptor before instance creation begins. Launch resolution must be keyed by `controlPlaneRequestId` so retries of the same launch attempt return the same descriptor values, and caller-supplied runtime overrides may only fill fields the template leaves unset. If the template already supplies a default, any caller-supplied value for that field must fail deterministically. ## Architecture / Design Notes diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 2833932f5a..f2798411ab 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -50,11 +50,11 @@ The current script-patch publication/read path is also narrower than the target The target tenant-scoped `GetTemplateReferencePhase` surface is not implemented: it has no current proto RPC, handler, or durable tenant phase authority. The live launch path checks only each `game_templates.template_reference_phase` value (`ENFORCED` or legacy `LEGACY`), not the target monotonic `BACKFILLING`/`VALIDATED`/`ENFORCED` cutover phase consumed by launch and retirement tooling. The API index below marks this surface target-only; no current launch or retirement proof may treat the per-template field as the target tenant phase. -The live `CompareAndSetVersionState` path has an additional safety gap beyond its non-atomic epoch check: after loading a tenant-scoped version and checking the expected epoch in service memory, it accepts any non-null lifecycle enum and saves it. It does not enforce the target legal transition matrix, require a committed release bundle/artifact for `DRAFT -> PUBLISHED`, or apply retirement predicates for active instances, templates, and in-flight activation. Therefore the live API must not be treated as an activation- or retirement-safe transition authority; transition validation and focused proof remain blocked. +The live `CompareAndSetVersionState` path locks the exact tenant/version row before checking the expected epoch and saving; both publication finalizers take that Version lock after their existing Game lock. This closes the known same-epoch lifecycle-writer race needed by the baseline migration fence, although local PostgreSQL concurrency tests are Docker-gated. It still accepts any non-null lifecycle enum and does not enforce the target legal transition matrix, require a committed release bundle/artifact for `DRAFT -> PUBLISHED`, or apply retirement predicates for active instances, templates, and in-flight activation. Therefore the live API must not be treated as an activation- or retirement-safe transition authority; transition validation and focused proof remain blocked. The current `SaveRevision` path is not the complete target Draft-concurrency contract from [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md). It lacks a Game Design-owned durable commit/proposal record bound to exact base and canonical digest, complete affected-scope capture, per-owner apply status, and a creator-visible synchronized read fence. Owner storage-level compare-and-swap and partial-application isolation also remain implementation and proof gaps. -Asset lifecycle API status requires the same distinction: the target `CompareAndSetVersionState`, `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets` contracts require database epoch predicates/locks, affected-row proof, and the shared ADR 0048 operation envelope with caller-supplied identity, canonical digest, exact replay, and conflict outcomes. The current service compares epochs in memory and then saves artifact and Version rows by ID without those predicates or affected-row checks; it has no shared lifecycle operation ledger, and `BeginPurgeVersionAssets` mints a random workflow ID. The target asset upload guardrails (25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer) are likewise not implemented or proved: the live upload path buffers `MultipartFile.getBytes()` without matching size/quota settings, so upload admission remains blocked. The API entries below describe target semantics and must not be read as current race-safe or idempotent proof. See [Asset Storage](asset-storage.md#implementation-status) for the current upload, repair, release-bundle, and purge boundaries. +Asset lifecycle API status requires the same distinction: the target `CompareAndSetVersionState`, `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets` contracts require database epoch predicates/locks, affected-row proof, and the shared ADR 0048 operation envelope with caller-supplied identity, canonical digest, exact replay, and conflict outcomes. `CompareAndSetVersionState` now locks its exact Version row for the epoch comparison; the separate asset-purge and repair paths still save artifact and Version rows by ID without the required predicate/lock and affected-row proof. There is no shared lifecycle operation ledger, and `BeginPurgeVersionAssets` mints a random workflow ID. The target asset upload guardrails (25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer) are likewise not implemented or proved: the live upload path buffers `MultipartFile.getBytes()` without matching size/quota settings, so upload admission remains blocked. The API entries below describe target semantics and must not be read as complete race-safe or idempotent proof. See [Asset Storage](asset-storage.md#implementation-status) for the current upload, repair, release-bundle, and purge boundaries. The current SaveRevision ordering is verified in `RevisionServiceImpl` and its focused tests: after Draft/version and payload validation, an optional `worldDesignMutation` is sent to World Management before the Game Design revision entity is mapped and saved. World Management applies the mutation, advances its owner epochs, and writes its revision ledger in its own transaction. A World Management validation or Draft-epoch failure therefore reaches no Game Design revision save; the focused tests verify invalid Game Design payloads and published-version rejection before the client call, while World Management tests verify stale-epoch failure without an aggregate write. If World Management applies successfully but the later Game Design revision save fails, the World mutation, epochs, and ledger can remain committed while the Game Design revision is absent: the separate service transactions provide no cross-owner rollback. This is a current partial-application gap, not an atomicity guarantee. @@ -80,7 +80,7 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e - `GetPublishedPluginVersion` – authoritative design-time read API for plugin publication lifecycle and compatibility metadata. - `ListPluginVersionStatuses` – authoritative broader plugin publication listing surface for operator and authoring tooling. - `ListVersions` – enumerates published versions for selection when creating a game instance. -- `GetVersionState` / `CompareAndSetVersionState` – authoritative control-plane version lifecycle reads and target CAS transitions. These APIs are live in the proto/service path and are the canonical owner for `versionStateEpoch`; current Version saves do not provide the target database epoch predicate/affected-row fence. +- `GetVersionState` / `CompareAndSetVersionState` – authoritative control-plane version lifecycle reads and target CAS transitions. These APIs are live in the proto/service path and are the canonical owner for `versionStateEpoch`; the known lifecycle writers now use an exact Version-row lock before epoch comparison/save, but legal transition and complete activation/retirement guards remain absent. - `GetVersionAssetArtifactState` – live authoritative read of the persisted version-asset artifact lifecycle/proof row; the target read authorization and complete frozen proof remain unimplemented or unproved. - `AbandonFailedVersionAssets` / `GetFailedVersionAssetAbandonment` – **Target state only; absent from the current proto and implementation:** illustrative owner-local operation/read names for recording and reading durable failed-candidate abandonment proof; see [Asset Storage](asset-storage.md#api). - `TombstoneVersionAssets` – live lifecycle mutation endpoint, but the current implementation supports only the `FAILED`/`PURGE_FAILED` cases and lacks the target retired-`PUBLISHED` authority checks, durable abandonment proof, and database CAS fence. @@ -132,7 +132,7 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `ListPluginVersionStatuses(ListPluginVersionStatusesRequest) returns (ListPluginVersionStatusesResponse)` – lists immutable plugin publication rows for a tenant with optional `pluginId`, `publicationState`, `changedAfterMs`, `changedBeforeMs`, and bounded `limit` filters. Target rows expose the same composed `verifiedSignatures[]` view; current rows expose only the singular selected `signerKeyId`. - `ListVersions(ListVersionsRequest) returns (ListVersionsResponse)` – lists available versions. - `GetVersionState(GetVersionStateRequest) returns (GetVersionStateResponse)` – reads authoritative version lifecycle state and CAS epoch. -- `CompareAndSetVersionState(CompareAndSetVersionStateRequest) returns (CompareAndSetVersionStateResponse)` – **Target state:** performs database CAS-guarded lifecycle transitions; the current implementation checks the epoch in service memory and saves by row ID without an epoch predicate or affected-row proof. +- `CompareAndSetVersionState(CompareAndSetVersionStateRequest) returns (CompareAndSetVersionStateResponse)` – **Target state:** performs database CAS-guarded, legal lifecycle transitions; the current implementation locks the exact Version row for its epoch comparison/save, but does not enforce the legal transition, release-artifact, or retirement predicates. - `GetDesignControlPlaneDigest(GetDesignControlPlaneDigestRequest) returns (GetDesignControlPlaneDigestResponse)` – returns normalized metadata digest used by publish gates. - `GetTemplateReferencePhase(GetTemplateReferencePhaseRequest) returns (GetTemplateReferencePhaseResponse)` – **Target state only; the current proto has no such RPC:** returns the persisted normalized-reference enforcement phase (`BACKFILLING`, `VALIDATED`, `ENFORCED`) used by instance-creation and retirement workflows. - `GetPublishedReleaseBundle(GetPublishedReleaseBundleRequest) returns (GetPublishedReleaseBundleResponse)` – **Target response:** returns the immutable `(tenantId, versionId)` release attestation including participant digests, the dedicated Game Logic-owned `abilitySchemaDigest` for the same target commit (using Game Logic's existing participant `digestSchemaVersion` and canonicalization evidence), any required `artifactDigests[]` and `requiredManifestAssetKeys[]` for exported derived assets, `manifestHash`, `generationConfigRevision`, and the canonical publish workflow runtime metadata (`publishWorkflowId`, `workflowRunId`, `workflowStatus`). **Current live response/compatibility path:** the implementation still uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest in place of the dedicated ability-schema field; that aggregate is not ability-schema proof, so consumers must fail closed until the target field and evidence converge. Missing, unsupported, or mismatched ability-schema evidence fails closed. Missing attestation must surface as `NOT_FOUND`, and unreadable attestation schema must surface as `SCHEMA_VERSION_UNSUPPORTED`. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index c366d89015..229b26ba8d 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -8,7 +8,7 @@ Game Design is the canonical authored-history, publication-coordination, release External Git synchronization and canonical multi-branch merge semantics are not implemented. Current authoring uses Game Design-owned revision APIs with optimistic validation and ordered mutation calls, but `SaveRevision` does not provide deterministic replay: it lacks durable request/revision deduplication and can leave a World mutation committed without its corresponding Game Design revision when the later local save fails. ADR 0129's durable multi-owner coordinator, owner-local compare-and-swap application, synchronized commit fence, and proof that partially applied owner rows remain invisible to ordinary Draft reads are also not implemented. Current release-bundle schema and plugin publication/activation code incorrectly reuse Automation & Scripting's aggregate participant `contentDigest` where the dedicated Game Logic-owned `abilitySchemaDigest` is required; exact ability-schema compatibility therefore remains an implementation and proof gap. Plugin publication currently uses signed-only intake; [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md)'s approved unsigned provenance remains target-only. The plugin publication path now rejects terminal-state reuse: an uploaded `SUPERSEDED` or `REVOKED_DESIGN` row cannot be republished under the same `pluginVersionId`; target rollback still uses a new immutable plugin version and leaves the prior terminal row unchanged, while new-version rollback proof remains absent. Duplicate signed plugin `assetId` values are likewise not rejected before export and can produce ambiguous distribution-manifest keys; target intake rejects them deterministically before publication/export. The live World Management design handoff adds a separate lifecycle race: it checks Game Design's authoritative remote version state (`GetVersionState(...).versionState=DRAFT`) before its own transaction, but has no durable owner-local publication freeze or exact Game Design version-state epoch/fence in the mutation request. That remote state check is not proof that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). -Migration V28 corrects the historical V13 default by retaining every affected row while moving only non-script-only rows whose exact V13 marker remains (`version_state=PUBLISHED`, `version_state_epoch=1`) and whose exact `(tenant_id, version_id)` `published_release_bundle` is absent to `FAILED`, incrementing the epoch and refreshing `updated_at`. Bundled full versions and script-only publication rows are untouched, and the marker predicate makes the correction idempotent. Validation follows the shared [Validation and Runtime Proof](../../../developer-workflows/validation-and-runtime-proof.md) workflow; PostgreSQL retained-row execution remains a required migration gate. This data correction is separate from the still-open `CompareAndSetVersionState` transition gap: the live path still accepts any non-null lifecycle state after its in-memory epoch check and does not enforce release-bundle/artifact or retirement guards. +Migration V28 corrects the historical V13 default by retaining every affected row while moving only non-script-only rows whose exact V13 marker remains (`version_state=PUBLISHED`, `version_state_epoch=1`) and whose exact `(tenant_id, version_id)` `published_release_bundle` is absent to `FAILED`, incrementing the epoch and refreshing `updated_at`. Bundled full versions and script-only publication rows are untouched, and the marker predicate makes the correction idempotent. Validation follows the shared [Validation and Runtime Proof](../../../developer-workflows/validation-and-runtime-proof.md) workflow; PostgreSQL retained-row execution remains a required migration gate. This data correction is separate from the still-open `CompareAndSetVersionState` transition gap: the live path locks the exact Version row for its epoch check but still accepts any non-null lifecycle state and does not enforce release-bundle/artifact or retirement guards. V26's participant-scope and V27's effective-identity migrations are deliberately coordinated/recreate and roll-forward-only. A pre-V26 writer cannot supply `base_version_id` to the recorded script-patch participant row, and a pre-V26 reader cannot distinguish the base-scoped identities that V26 permits; mixed generations would therefore either fail writes or misread retained evidence. The Kubernetes base and hosted Helm manifests use `Recreate` for Game Design to enforce stop-before-start, but this strategy is not trusted writer-quiescence proof. Before activating V26 or V27, the trusted deployment path must close Game Design writer Service admission with a verified nonmatching selector, prove the selector readback and empty EndpointSlices, scale old Game Design writers to zero, and prove no old writer Pods remain; then complete the [documented schema and retained-data preflight](../../system-architecture-database-migrations.md#game-design-script-patch-identity-migration-preflight). These are the canonical production activation prerequisites. For an activation admitted by the trusted dev-demo classifier, the flow implements that admission/drain boundary before its participant-first Helm upgrade and keeps admission closed on closure, drain, or participant rollout failure; a successful participant-ready upgrade is the only path that restores Game Design. It does not substitute for the retained-data preflight. The current trusted dev-demo classifier only admits first additions of the supported Account V25, Game Session V2, and Automation V2 migrations; it rejects V26/V27 before namespace mutation, so the staged dev-demo admission/drain flow does not currently activate these Game Design migrations. The current hosted PR candidate-preview path likewise rejects unsupported V26/V27 migration activation fail-closed and does not prove those live gates. A pre-V26 binary must not be rolled back after V26 migrates the database. Deployments outside the trusted path must establish equivalent admission, drain, and preflight proof before activation. diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index 883588f441..835ae53104 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -203,7 +203,7 @@ Required control-plane APIs: `versionStateEpoch` increments on any lifecycle transition that can affect activation eligibility (for example `Published -> Retired`, `Failed -> Draft`, or admin policy transitions). -The target `CompareAndSetVersionState` contract requires a database epoch predicate and affected-row/lock proof, not only a service-memory comparison. The current `VersionService` checks the loaded epoch and then performs an unconditional row-ID save, so concurrent state writers can overwrite one another; this is an implementation gap that blocks treating `expectedVersionStateEpoch` as abandonment or purge invalidation evidence. +The target `CompareAndSetVersionState` contract requires a database epoch predicate or exact-row lock with affected-row/lock proof, not only a service-memory comparison. The current `VersionService` locks the exact tenant/version row before comparing the epoch and saving; both publication finalizers also lock that Version row after their existing Game lock. This serializes the known live lifecycle writers, but local PostgreSQL concurrency tests remain Docker-gated and legal transition, release-artifact, retirement, and purge predicates are not implemented. The epoch alone is not abandonment or purge authorization evidence. Normative CAS call flow for activation and rollback: diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 6543441ad0..7228db1666 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -22,11 +22,11 @@ AR-1.5 full-version publication now reserves its Draft version and PENDING attem The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open arbitrary `CompareAndSetVersionState` transition gap recorded below. -`AR-3.2` Entity digest-schema catch-up now has a dedicated historical-baseline migration path in the Game Design owner: bounded v1 full-version enumeration, exact tenant/version and expected-old preflight, v2 Entity recomputation, atomic guarded baseline/audit write, and exact persisted readback/retry. Retained v1 scopes whose Version is mutable `DRAFT` are reported `BLOCKED_DRAFT`; migrate rejects them before the Entity digest read and locks/rechecks Version state at its guarded write boundary. This one-shot guard does not freeze authoring, and publication quiescence is not an authoring freeze. It is a protected one-shot Job, not ordinary publication or a public operator API. This code and its synthetic test rows do not prove that deployed retained v1 rows were migrated or that the live scoped row set is empty. The controlled readers-first publication window, dedicated migrator certificate issuance, live PostgreSQL readback, and later review remain rollout gates; Entity's `version:` commit token still does not prove applied-revision convergence. Keep the capability partial until those boundaries have actual evidence. +`AR-3.2` Entity digest-schema catch-up now has a dedicated historical-baseline migration path in the Game Design owner: bounded v1 full-version enumeration, exact tenant/version and expected-old preflight, v2 Entity recomputation, atomic guarded baseline/audit write, and exact persisted readback/retry. Retained v1 scopes whose Version is mutable `DRAFT` are reported `BLOCKED_DRAFT`; migrate rejects them before the Entity digest read and locks/rechecks Version state and its initially observed epoch at the guarded write boundary. Known lifecycle writers lock the exact Version row so a transient Draft transition cannot reuse that epoch; local PostgreSQL interleaving tests remain Docker-gated. This one-shot guard does not freeze authoring, and publication quiescence is not an authoring freeze. It is a protected one-shot Job, not ordinary publication or a public operator API. This code and its synthetic test rows do not prove that deployed retained v1 rows were migrated or that the live scoped row set is empty. The controlled readers-first publication window, dedicated migrator certificate issuance, live PostgreSQL readback, and later review remain rollout gates; Entity's `version:` commit token still does not prove applied-revision convergence. Keep the capability partial until those boundaries have actual evidence. Asset lifecycle status remains partial: publication and artifact services provide the current bounded release-bundle and asset-storage seams, but the destructive lifecycle operations (`TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets`) still lack proved durable operation handling and owner-local epoch/CAS protection. `BeginPurgeVersionAssets` currently mints a random workflow identity, and artifact and Version saves lack DB epoch predicates/affected-row proof. The canonical lifecycle and operation contract is owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status), with [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) providing provenance. -The live `CompareAndSetVersionState` path has an additional transition-safety gap: it accepts any non-null lifecycle enum after its in-memory epoch check, without requiring a committed release bundle/artifact for `DRAFT -> PUBLISHED` or enforcing active-instance/template/in-flight-activation predicates before retirement. It must not be rated as activation- or retirement-safe until the legal transition matrix, guards, and focused proof are implemented. Purge failure status is likewise not durable today: `FinalizePurgeVersionAssets` saves `PURGE_FAILED`/failed-workflow markers and rethrows inside `@Transactional`, so rollback can discard those markers after object deletion, leaving durable `PURGE_IN_PROGRESS` without reliable resume evidence. Target recovery needs an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused deletion/post-delete-save proof. +The live `CompareAndSetVersionState` path now locks the exact Version row for its epoch comparison, and both known publication finalizers lock that row after the Game lock; the local PostgreSQL concurrency proof remains Docker-gated. Its transition-safety gap remains: it accepts any non-null lifecycle enum without requiring a committed release bundle/artifact for `DRAFT -> PUBLISHED` or enforcing active-instance/template/in-flight-activation predicates before retirement. It must not be rated as activation- or retirement-safe until the legal transition matrix, guards, and focused proof are implemented. Purge failure status is likewise not durable today: `FinalizePurgeVersionAssets` saves `PURGE_FAILED`/failed-workflow markers and rethrows inside `@Transactional`, so rollback can discard those markers after object deletion, leaving durable `PURGE_IN_PROGRESS` without reliable resume evidence. Target recovery needs an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused deletion/post-delete-save proof. `AR-1.5` retained revision/version lineage blocker (non-normative): [V5](../../../services/game-design-service/src/main/resources/db/migration/V5__update_version_table.sql) drops the legacy `version.revision_ids` relationship before [V17](../../../services/game-design-service/src/main/resources/db/migration/V17__revision_version_scope.sql) assigns each retained revision to the latest tenant version. This historical lineage is not proven by the current publication seams. Before migration cleanup or any completion claim, the owner must record either a verified no-data boundary or an explicit retained-row disposition/mapping, perform exact readback of the affected version/revision rows, and attach lineage proof to those implementation anchors. No recovery of dropped arrays is implied. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index 9fa50110c4..fd21695d65 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -265,7 +265,7 @@ private PublishWorkflowSnapshot finalizeFullVersion( throw pendingReconciliation("full-version attempt is no longer pending"); } - Version version = requireAttemptVersion(attempt, request); + Version version = requireAttemptVersionForUpdate(attempt, request); PublicationReadback existingPublication = readPublication(request, attempt); if (existingPublication.isComplete()) { assertCommittedBundleMayMarkSuccess(request, existingPublication); @@ -608,6 +608,22 @@ private Version requireAttemptVersion(PublishAttempt attempt, PublishWorkflowReq return version; } + private Version requireAttemptVersionForUpdate( + PublishAttempt attempt, PublishWorkflowRequest request) { + validateFullVersionAttempt(attempt, request); + Version version = + versionRepository + .findByTenantIdAndIdForUpdate(request.tenantId(), attempt.getVersionId()) + .orElseThrow(() -> new IllegalArgumentException("version not found")); + if (!Objects.equals(version.getTenantId(), request.tenantId()) + || version.getVersionNumber() != attempt.getVersionNumber() + || version.isScriptOnly()) { + throw new IllegalStateException( + "PUBLISH_ATTEMPT_SCOPE_MISMATCH: referenced version evidence does not match request"); + } + return version; + } + private PublicationReadback readPublication( PublishWorkflowRequest request, PublishAttempt attempt) { Optional version = diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java index 70e8908ec0..c2eee8cf47 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java @@ -340,7 +340,7 @@ private ScriptPatchFinalization finalizeScriptPatch( return new ScriptPatchFinalization( attempt.getStatus(), null, attempt.getFailureCode(), attempt.getFailureMessage()); } - Version saved = requireAttemptVersion(attempt, patchBinding); + Version saved = requireAttemptVersionForUpdate(attempt, patchBinding); if (saved.getVersionState() != VersionLifecycleState.DRAFT) { throw new IllegalStateException( "PUBLISH_ATTEMPT_PENDING_RECONCILIATION_REQUIRED: pending attempt does not reference a draft version"); @@ -380,7 +380,8 @@ private ScriptPatchFinalization failScriptPatch( attempt.getStatus(), null, attempt.getFailureCode(), attempt.getFailureMessage()); } Optional draft = - versionRepository.findByTenantIdAndId(patchBinding.tenantId(), attempt.getVersionId()); + versionRepository.findByTenantIdAndIdForUpdate( + patchBinding.tenantId(), attempt.getVersionId()); if (draft.isPresent() && draft.get().getVersionState() != VersionLifecycleState.DRAFT) { throw new IllegalStateException( "PUBLISH_ATTEMPT_INCONSISTENT: pending attempt references a non-draft version"); @@ -425,13 +426,26 @@ private void validateExistingScriptPatchAttempt( private Version requireAttemptVersion( PublishAttempt attempt, PublicationDigestRequestBinding patchBinding) { + return requireAttemptVersion(attempt, patchBinding, false); + } + + private Version requireAttemptVersionForUpdate( + PublishAttempt attempt, PublicationDigestRequestBinding patchBinding) { + return requireAttemptVersion(attempt, patchBinding, true); + } + + private Version requireAttemptVersion( + PublishAttempt attempt, PublicationDigestRequestBinding patchBinding, boolean forUpdate) { if (attempt.getVersionId() == null || attempt.getVersionNumber() <= 0) { throw new IllegalStateException( "PUBLISH_ATTEMPT_INCOMPLETE: attempt is missing its durable version evidence"); } Version version = - versionRepository - .findByTenantIdAndId(patchBinding.tenantId(), attempt.getVersionId()) + (forUpdate + ? versionRepository.findByTenantIdAndIdForUpdate( + patchBinding.tenantId(), attempt.getVersionId()) + : versionRepository.findByTenantIdAndId( + patchBinding.tenantId(), attempt.getVersionId())) .orElseThrow( () -> new IllegalStateException( @@ -803,7 +817,7 @@ public VersionStateDto compareAndSetVersionState( long expectedVersionStateEpoch, VersionLifecycleState newState, String reason) { - Version version = requireTenantVersion(tenantId, versionId); + Version version = requireTenantVersionForUpdate(tenantId, versionId); if (newState == null) { throw new IllegalArgumentException("INVALID_ARGUMENT: new version state is required"); } @@ -839,6 +853,12 @@ private int calculateNextNumber(String tenantId) { + 1; } + private Version requireTenantVersionForUpdate(String tenantId, long versionId) { + return versionRepository + .findByTenantIdAndIdForUpdate(tenantId, versionId) + .orElseThrow(() -> new IllegalArgumentException("version not found")); + } + private String publishFailureCode(RuntimeException ex) { if (ex instanceof PublishGateFailureException publishGateFailureException) { return publishGateFailureException.failureCode().name(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java index f47fdbb504..d9a294db90 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -15,10 +16,18 @@ import java.sql.Statement; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; +import java.util.List; +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 net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; import net.firedevops.firemud.gamedesign.client.EntityManagementClient; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.VersionStateDto; import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; @@ -90,6 +99,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private EntityDigestBaselineMigrationAuditRepository auditRepository; @Autowired private EntityDigestBaselineMigrationService migrationService; @Autowired private EntityDigestBaselineMigrationWriteService writeService; + @Autowired private VersionService versionService; @MockitoBean private EntityManagementClient entityManagementClient; @@ -256,6 +266,107 @@ void draftV1ScopeIsReportedBlockedAndMigrationDoesNotReadEntityDigest() { assertThat(auditRepository.findByOperationId(command.operationId())).isEmpty(); } + @Test + void competingSameEpochCasTransitionsAllowOnlyOneWriter() throws Exception { + Version version = createVersion("cas-tenant", 1, VersionLifecycleState.PUBLISHED); + CountDownLatch start = new CountDownLatch(1); + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + List> transitions = + List.of( + executor.submit( + () -> { + awaitLatch(start); + return versionService.compareAndSetVersionState( + "cas-tenant", version.getId(), 1L, VersionLifecycleState.DRAFT, "cas-1"); + }), + executor.submit( + () -> { + awaitLatch(start); + return versionService.compareAndSetVersionState( + "cas-tenant", version.getId(), 1L, VersionLifecycleState.RETIRED, "cas-2"); + })); + start.countDown(); + + int successes = 0; + int staleFailures = 0; + for (Future transition : transitions) { + try { + transition.get(5, TimeUnit.SECONDS); + successes++; + } catch (ExecutionException failure) { + assertThat(failure.getCause()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("VERSION_STATE_EPOCH_STALE:"); + staleFailures++; + } + } + assertThat(successes).isOne(); + assertThat(staleFailures).isOne(); + } + + Version finalVersion = + versionRepository.findByTenantIdAndId("cas-tenant", version.getId()).orElseThrow(); + assertThat(finalVersion.getVersionStateEpoch()).isEqualTo(2L); + assertThat(finalVersion.getVersionState()) + .isIn(VersionLifecycleState.DRAFT, VersionLifecycleState.RETIRED); + } + + @Test + void migrationDigestOverlapWithLifecycleTransitionRejectsStaleEpoch() throws Exception { + String tenantId = "migration-race-tenant"; + createGame(tenantId); + Version version = createVersion(tenantId, 1, VersionLifecycleState.PUBLISHED); + RecordedParticipantDigest baseline = seedEntityBaseline(tenantId, version, 1); + MigrationCommand command = command("migration-race-operation", tenantId, baseline); + CountDownLatch digestRead = new CountDownLatch(1); + CountDownLatch releaseDigest = new CountDownLatch(1); + doAnswer( + invocation -> { + digestRead.countDown(); + awaitLatch(releaseDigest); + PublicationDigestRequestBinding binding = invocation.getArgument(0); + long versionId = Long.parseLong(binding.versionId()); + return new PublishParticipantDigestDto( + PublishParticipantKey.ENTITY_MANAGEMENT.name(), + binding.versionId(), + null, + "version:" + versionId, + v2Digest(versionId), + 2, + null, + null); + }) + .when(entityManagementClient) + .getDraftDesignDigestForVersion(any()); + + try (ExecutorService executor = Executors.newSingleThreadExecutor()) { + Future migration = executor.submit(() -> migrationService.migrate(command)); + assertThat(digestRead.await(5, TimeUnit.SECONDS)).isTrue(); + + VersionStateDto transitioned = + versionService.compareAndSetVersionState( + tenantId, version.getId(), 1L, VersionLifecycleState.ACTIVE, "migration-race"); + assertThat(transitioned.versionState()).isEqualTo(VersionLifecycleState.ACTIVE); + assertThat(transitioned.versionStateEpoch()).isEqualTo(2L); + releaseDigest.countDown(); + + assertThatThrownBy(() -> migration.get(5, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasCauseInstanceOf(EntityDigestBaselineMigrationService.MigrationRejectedException.class) + .hasRootCauseMessage( + "version lifecycle changed while the Entity digest was being recomputed"); + } finally { + releaseDigest.countDown(); + } + + assertBaselineUnchanged(baseline); + assertThat(auditRepository.findByOperationId(command.operationId())).isEmpty(); + Version finalVersion = + versionRepository.findByTenantIdAndId(tenantId, version.getId()).orElseThrow(); + assertThat(finalVersion.getVersionState()).isEqualTo(VersionLifecycleState.ACTIVE); + assertThat(finalVersion.getVersionStateEpoch()).isEqualTo(2L); + } + @Test void exactRetryReadsCommittedEvidenceWithoutCallingEntityAgain() { createGame("9301"); @@ -737,6 +848,15 @@ private void assertBaselineUnchanged(RecordedParticipantDigest expected) { assertThat(actual).usingRecursiveComparison().isEqualTo(expected); } + private static void awaitLatch(CountDownLatch latch) { + try { + assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new AssertionError("Interrupted while waiting for test coordination", exception); + } + } + private String v2Digest(long versionId) { return "entity-v2-observed-" + versionId; } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 2044c3b2c7..bc6312a05e 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -71,6 +71,11 @@ void setup() { .thenReturn(Optional.empty()); when(versionAssetArtifactService.findState(any(String.class), any(Long.class))) .thenReturn(Optional.empty()); + when(versionRepository.findByTenantIdAndIdForUpdate(any(String.class), any(Long.class))) + .thenAnswer( + invocation -> + versionRepository.findByTenantIdAndId( + invocation.getArgument(0), invocation.getArgument(1))); org.mockito.Mockito.doAnswer( invocation -> { try { @@ -227,6 +232,9 @@ void publishFullVersionUsesTenantScopedVersionSequence() { assertEquals(8, dto.versionNumber()); assertEquals(VersionLifecycleState.PUBLISHED, dto.versionState()); assertEquals(2L, dto.versionStateEpoch()); + InOrder versionOrder = inOrder(versionRepository); + versionOrder.verify(versionRepository).findByTenantIdAndIdForUpdate("tenant-1", 10L); + versionOrder.verify(versionRepository).save(any(Version.class)); verify(publishAttemptService) .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); verify(assetExportService).exportAssets("tenant-1", 8); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index dcc1f96486..399f926219 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -5,8 +5,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -57,6 +60,7 @@ import org.junit.jupiter.params.provider.EnumSource; import org.mapstruct.factory.Mappers; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.data.domain.Pageable; @@ -91,6 +95,11 @@ void setup() throws Exception { .thenAnswer(invocation -> invocation.getArgument(0)); when(publishAttemptService.findByPublishWorkflowId(any(String.class))) .thenReturn(Optional.empty()); + when(versionRepository.findByTenantIdAndIdForUpdate(any(String.class), any(Long.class))) + .thenAnswer( + invocation -> + versionRepository.findByTenantIdAndId( + invocation.getArgument(0), invocation.getArgument(1))); doAnswer( invocation -> { try { @@ -133,6 +142,30 @@ void publishVersionWithoutDurableWorkflowDoesNotMutate() { .publishFullVersion(any(), any(), any(), any()); } + @Test + void compareAndSetVersionStateLocksExactVersionBeforeSaving() { + Version version = new Version(); + version.setId(7L); + version.setTenantId("tenant-1"); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + doReturn(Optional.of(version)) + .when(versionRepository) + .findByTenantIdAndIdForUpdate("tenant-1", 7L); + when(versionRepository.save(any(Version.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + clearInvocations(versionRepository); + + service.compareAndSetVersionState( + "tenant-1", 7L, 1L, VersionLifecycleState.PUBLISHED, "unit-test"); + + InOrder versionOrder = inOrder(versionRepository); + versionOrder.verify(versionRepository).findByTenantIdAndIdForUpdate("tenant-1", 7L); + versionOrder.verify(versionRepository).save(version); + verify(versionRepository, org.mockito.Mockito.never()).findByTenantIdAndId("tenant-1", 7L); + } + @Test void publishScriptPatchVersionNotifiesAfterPersistingVersion() throws Exception { Game game = new Game(); @@ -205,6 +238,9 @@ void publishScriptPatchVersionNotifiesAfterPersistingVersion() throws Exception assertEquals(8, dto.versionNumber()); assertEquals(VersionLifecycleState.PUBLISHED, dto.versionState()); verify(versionRepository, times(2)).save(any(Version.class)); + InOrder versionOrder = inOrder(versionRepository); + versionOrder.verify(versionRepository).findByTenantIdAndIdForUpdate("tenant-1", 11L); + versionOrder.verify(versionRepository).save(any(Version.class)); verify(publishAttemptService) .createScriptPatchAttempt( any(VersionDto.class), From 0e0172ddb491b4532813a4608f55004656ed1f8d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 10:25:44 +1300 Subject: [PATCH 20/28] Lock version during publication digest reconciliation --- .../service/impl/VersionPublishCommandServiceImpl.java | 1 + .../service/impl/VersionPublishCommandServiceImplTest.java | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index fd21695d65..1087888f7b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -373,6 +373,7 @@ private void recordVerifiedAndSucceed( && current.getStatus() != PublishAttemptStatus.SUCCEEDED) { throw pendingReconciliation("full-version attempt is no longer pending"); } + requireAttemptVersionForUpdate(current, request); PublicationReadback currentReadback = readPublication(request, current); if (!currentReadback.isComplete()) { throw pendingReconciliation( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index bc6312a05e..5b35c02fa6 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -801,6 +801,12 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { verify(recordedParticipantDigestService) .recordVerifiedDigests( "tenant-1", PublishType.FULL_VERSION, workflowId, participantDigests); + InOrder reconciliationOrder = inOrder(versionRepository, recordedParticipantDigestService); + reconciliationOrder.verify(versionRepository).findByTenantIdAndIdForUpdate("tenant-1", 10L); + reconciliationOrder + .verify(recordedParticipantDigestService) + .recordVerifiedDigests( + "tenant-1", PublishType.FULL_VERSION, workflowId, participantDigests); verify(publishAttemptService).markFullVersionSucceeded(workflowId); } From 9d2ded9e19657a750c1d5d8bd25cf5cb3ad007cb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 14:21:08 +1300 Subject: [PATCH 21/28] Format reconciled publication order proof --- .../service/impl/VersionServiceImplTest.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index cb65548f22..883fca9a26 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -248,18 +248,18 @@ void publishScriptPatchPersistsBeforeNotificationAndFinalizesAfterAutomation() t verify(versionRepository, times(2)).save(any(Version.class)); InOrder publicationOrder = inOrder(versionRepository, publishAttemptService, scriptingClient); publicationOrder.verify(versionRepository).save(any(Version.class)); - publicationOrder.verify(publishAttemptService).createScriptPatchAttempt( - any(VersionDto.class), - org.mockito.ArgumentMatchers.eq( - "publish-script-patch:tenant-1:publish-request:" + PUBLISH_REQUEST_ID), - org.mockito.ArgumentMatchers.eq(3L), - org.mockito.ArgumentMatchers.eq(binding.requestDigest())); + publicationOrder + .verify(publishAttemptService) + .createScriptPatchAttempt( + any(VersionDto.class), + org.mockito.ArgumentMatchers.eq( + "publish-script-patch:tenant-1:publish-request:" + PUBLISH_REQUEST_ID), + org.mockito.ArgumentMatchers.eq(3L), + org.mockito.ArgumentMatchers.eq(binding.requestDigest())); publicationOrder .verify(scriptingClient) .notifyScriptVersionUpdate("tenant-1", 3L, "patch-2", java.util.List.of()); - publicationOrder - .verify(versionRepository) - .findByTenantIdAndIdForUpdate("tenant-1", 11L); + publicationOrder.verify(versionRepository).findByTenantIdAndIdForUpdate("tenant-1", 11L); publicationOrder .verify(publishAttemptService) .recordScriptPatchParticipantDigests( From 26506be6849cd11f9a7526e6360c843ed96d3558 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 15:26:17 +1300 Subject: [PATCH 22/28] Allow exact operator retirement of ephemeral migrator Secret --- ...d-identity-controller-manifest-contract.sh | 133 +++++++++++++++++- .../trust-bootstrap-issuance-contract.sh | 45 ++++++ k8s/hosted-identity-controller/admission.yaml | 10 +- 3 files changed, 186 insertions(+), 2 deletions(-) diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index 6c6b0d81b9..12a5b8e4b8 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -1385,6 +1385,131 @@ secret_expressions = [ validation["expression"] for validation in secret_policy["spec"]["validations"] ] +migrator_secret_retirement_allowance = ( + "(request.userInfo.groups.exists(group, group == 'system:masters') && " + "request.subResource == '' && request.operation == 'DELETE' && " + "request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && " + "request.name == 'firemud-grpc-game-design-baseline-migrator')" +) + + +def assert_migrator_secret_retirement_contract(candidate_secret_policy): + candidate_spec = candidate_secret_policy.get("spec", {}) + candidate_validations = candidate_spec.get("validations", []) + assert len(candidate_validations) == 2, "Secret boundary must retain exactly two validations" + candidate_authorization = " ".join( + candidate_validations[0].get("expression", "").split() + ) + assert candidate_authorization.count(migrator_secret_retirement_allowance) == 1 + assert candidate_validations[0].get("message") == ( + "managed identity and runtime TLS Secrets are writable only by the controller or " + "cert-manager for its owned identity Secret; system:masters may delete only the " + "exact migrator Secret in a runtime namespace" + ) + candidate_cert_manager_guard = " ".join( + candidate_validations[1].get("expression", "").split() + ) + assert candidate_cert_manager_guard.startswith( + "request.userInfo.username != 'system:serviceaccount:cert-manager:cert-manager' ||" + ) + assert "request.operation in ['CREATE', 'UPDATE']" in candidate_cert_manager_guard + assert candidate_spec["matchConstraints"]["resourceRules"] == [ + { + "apiGroups": [""], + "apiVersions": ["v1"], + "operations": ["CREATE", "UPDATE", "DELETE"], + "resources": ["secrets"], + "scope": "Namespaced", + } + ] + conditions = candidate_spec["matchConditions"] + assert len(conditions) == 1 + condition = " ".join(conditions[0].get("expression", "").split()) + generic_scope_start = condition.find( + "((request.namespace in ['dev', 'dev-identity']" + ) + assert generic_scope_start >= 0 + delete_start = condition.find("(request.operation == 'DELETE'", generic_scope_start) + assert delete_start > generic_scope_start + nondelete_start = condition.find("(request.operation != 'DELETE'", delete_start) + assert nondelete_start > delete_start + generic_scope = condition[generic_scope_start:delete_start] + generic_delete = condition[delete_start:nondelete_start] + assert "request.namespace in ['dev', 'dev-identity']" in generic_scope + assert "request.namespace.matches('^pr-[1-9][0-9]{0,50}$')" in generic_scope + assert "request.name == 'firemud-grpc-game-design-baseline-migrator'" in generic_delete + + +assert_migrator_secret_retirement_contract(secret_policy) + + +def master_migrator_secret_delete_is_allowed( + username, groups, namespace, name, operation, subresource +): + # Membership in system:masters is the caller authority; username is not a + # separate authorization predicate in the parsed allowance above. + return ( + "system:masters" in groups + and subresource == "" + and operation == "DELETE" + and re.fullmatch(r"(?:dev|pr-[1-9][0-9]{0,50})", namespace) is not None + and name == "firemud-grpc-game-design-baseline-migrator" + ) + + +assert master_migrator_secret_delete_is_allowed( + "operator@example.test", + ("system:masters",), + "dev", + "firemud-grpc-game-design-baseline-migrator", + "DELETE", + "", +) +assert master_migrator_secret_delete_is_allowed( + "operator@example.test", + ("system:masters",), + "pr-42", + "firemud-grpc-game-design-baseline-migrator", + "DELETE", + "", +) +for denied_retirement in ( + ("system:serviceaccount:firemud-system:firemud-hosted-identity-controller", ("system:serviceaccounts",), "dev", "firemud-grpc-game-design-baseline-migrator", "DELETE", ""), + ("system:masters", ("system:authenticated",), "dev", "firemud-grpc-game-design-baseline-migrator", "DELETE", ""), + ("operator@example.test", ("system:masters",), "dev", "firemud-grpc-game-design-baseline-migrator-copy", "DELETE", ""), + ("operator@example.test", ("system:masters",), "dev-identity", "firemud-grpc-game-design-baseline-migrator", "DELETE", ""), + ("operator@example.test", ("system:masters",), "pr-42-identity", "firemud-grpc-game-design-baseline-migrator", "DELETE", ""), + ("operator@example.test", ("system:masters",), "production", "firemud-grpc-game-design-baseline-migrator", "DELETE", ""), + ("operator@example.test", ("system:masters",), "dev", "firemud-grpc-game-design-baseline-migrator", "UPDATE", ""), + ("operator@example.test", ("system:masters",), "dev", "firemud-grpc-game-design-baseline-migrator", "CREATE", ""), + ("operator@example.test", ("system:masters",), "dev", "firemud-grpc-game-design-baseline-migrator", "DELETE", "status"), +): + assert not master_migrator_secret_delete_is_allowed(*denied_retirement), denied_retirement + + +for retired_predicate in ( + "request.userInfo.groups.exists(group, group == 'system:masters')", + "request.subResource == ''", + "request.operation == 'DELETE'", + "request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$')", + "request.name == 'firemud-grpc-game-design-baseline-migrator'", +): + mutated_secret_policy = copy.deepcopy(secret_policy) + first_expression = mutated_secret_policy["spec"]["validations"][0]["expression"] + assert retired_predicate in first_expression, retired_predicate + mutated_secret_policy["spec"]["validations"][0]["expression"] = first_expression.replace( + retired_predicate, "true", 1 + ) + try: + assert_migrator_secret_retirement_contract(mutated_secret_policy) + except AssertionError: + pass + else: + raise AssertionError( + f"migrator Secret retirement contract accepted a missing {retired_predicate}" + ) + + controller_secret_expression = next( expression for expression in secret_expressions @@ -1559,7 +1684,7 @@ assert "object.metadata.name == 'dev-grpc-game-session-service'" in cert_manager assert "object.metadata.name == 'dev-grpc-social-groups-service'" in cert_manager_expression assert cert_manager_expression.count( "request.name == 'firemud-grpc-game-design-baseline-migrator'" -) == 1, "migrator Secret admission match must be a single exact branch" +) == 2, "migrator Secret must retain only its exact operator-retirement and namespace-controller branches" for migration_secret_gate in ( "request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$')", "object.metadata.name == 'firemud-grpc-game-design-baseline-migrator'", @@ -1593,6 +1718,12 @@ assert certificate_namespace_match.startswith( "request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' ||" ) assert break_glass in certificate_namespace_match +master_certificate_match_scope = ( + "(request.userInfo.groups.exists(group, group == 'system:masters') && " + "(request.namespace == 'dev-identity' || " + "request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')))" +) +assert certificate_namespace_match.count(master_certificate_match_scope) == 1 assert "request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' &&" in certificate_namespace_match assert "request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$')" in certificate_namespace_match assert "request.namespace == 'dev-identity'" in certificate_namespace_match diff --git a/dev-tools/tests/trust-bootstrap-issuance-contract.sh b/dev-tools/tests/trust-bootstrap-issuance-contract.sh index 35604f73b0..9245b90e3c 100755 --- a/dev-tools/tests/trust-bootstrap-issuance-contract.sh +++ b/dev-tools/tests/trust-bootstrap-issuance-contract.sh @@ -150,6 +150,51 @@ def check_contract(items: list[dict]) -> None: certificate_match = actual_policies["firemud-trust-bootstrap-certificate"]["spec"][ "matchConditions" ][0]["expression"] + certificate_match_normalized = " ".join(certificate_match.split()) + certificate_rules = actual_policies["firemud-trust-bootstrap-certificate"]["spec"][ + "matchConstraints" + ]["resourceRules"] + if len(certificate_rules) != 1: + fail("Certificate issuance boundary must have exactly one resource rule") + if certificate_rules[0].get("operations") != ["CREATE", "UPDATE", "DELETE"]: + fail("Certificate issuance boundary must cover create, update, and delete") + if certificate_rules[0].get("resources") != ["certificates"]: + fail("Certificate issuance boundary must match only the certificates resource") + if certificate_rules[0].get("scope") != "Namespaced": + fail("Certificate issuance boundary must be namespaced") + delete_match_branch = certificate_match_normalized.split( + "(request.operation == 'DELETE' &&", 1 + )[1].split("(request.operation == 'CREATE' &&", 1)[0] + for needle in ( + "oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(", + "game-design-baseline-migrator)$')", + "request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$')", + ): + require(delete_match_branch, needle, "runtime migrator Certificate DELETE match condition") + certificate_validations = actual_policies["firemud-trust-bootstrap-certificate"][ + "spec" + ]["validations"] + if len(certificate_validations) != 2: + fail("Certificate boundary must retain both authorization and spec validations") + certificate_validation_normalized = " ".join( + certificate_validations[0]["expression"].split() + ) + if not certificate_validation_normalized.startswith( + "request.userInfo.groups.exists(group, group == 'system:masters') ||" + ): + fail("trusted system:masters must pass the Certificate authorization validation") + spec_validation_normalized = " ".join( + certificate_validations[1]["expression"].split() + ) + for needle in ( + "request.userInfo.groups.exists(group, group == 'system:masters') ||", + "request.operation == 'DELETE' ||", + ): + require( + spec_validation_normalized, + needle, + "Certificate spec validation for an authorized DELETE", + ) certificate_status_policy = actual_policies["firemud-trust-bootstrap-certificate-status"] certificate_status = certificate_status_policy["spec"] for needle in ( diff --git a/k8s/hosted-identity-controller/admission.yaml b/k8s/hosted-identity-controller/admission.yaml index 79cade40e6..efbab43fa4 100644 --- a/k8s/hosted-identity-controller/admission.yaml +++ b/k8s/hosted-identity-controller/admission.yaml @@ -177,11 +177,19 @@ spec: object.metadata.name == 'firemud-grpc-tls-previous' || object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))-previous$'))))) validations: + # Explicitly authorized operators retire the exact ephemeral migrator + # Secret after the audited readback; this does not authorize other names, + # operations, subresources, or namespaces. # Namespace deletion also deletes the exact retained material. Allow # only the built-in kube-system namespace controller, DELETE, managed # namespace, and canonical Secret name; no other namespace-controller # operation or name is exempted. - expression: >- + (request.userInfo.groups.exists(group, group == 'system:masters') && + request.subResource == '' && + request.operation == 'DELETE' && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + request.name == 'firemud-grpc-game-design-baseline-migrator') || (request.userInfo.username == 'system:serviceaccount:kube-system:namespace-controller' && request.operation == 'DELETE' && (((request.namespace in ['dev', 'dev-identity'] || @@ -318,7 +326,7 @@ spec: (object.metadata.labels['firemud.dev/role'] == 'grpc-account-service' && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-account-service') || (object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service' && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-game-session-service') || (object.metadata.labels['firemud.dev/role'] == 'grpc-social-groups-service' && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-social-groups-service'))))))) - message: managed identity and runtime TLS Secrets are writable only by the controller or cert-manager for its owned identity Secret + message: managed identity and runtime TLS Secrets are writable only by the controller or cert-manager for its owned identity Secret; system:masters may delete only the exact migrator Secret in a runtime namespace reason: Forbidden - expression: >- request.userInfo.username != 'system:serviceaccount:cert-manager:cert-manager' || From 9c75c62bbb5aecf4e377023922ffe785dc04853c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 15:51:48 +1300 Subject: [PATCH 23/28] Prove complete baseline migrator network isolation --- ...tity-digest-baseline-migration-contract.sh | 146 +++++++++++++++--- 1 file changed, 125 insertions(+), 21 deletions(-) diff --git a/dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh b/dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh index 827c9ebc2a..3310ef0cdb 100644 --- a/dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh +++ b/dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh @@ -104,6 +104,63 @@ def assert_database_identity(job, expected_secret_name, mode): raise SystemExit(f"{mode} Job must not reference shared firemud-secret") +EXPECTED_MIGRATOR_POLICY_SPEC = { + "podSelector": { + "matchLabels": { + "app": "game-design-baseline-migrator", + "firemud.dev/workload": "game-design-baseline-migrator", + } + }, + "policyTypes": ["Ingress", "Egress"], + "ingress": [], + "egress": [ + { + "to": [ + { + "namespaceSelector": { + "matchLabels": {"kubernetes.io/metadata.name": "kube-system"} + }, + "podSelector": {"matchLabels": {"k8s-app": "kube-dns"}}, + } + ], + "ports": [ + {"protocol": "UDP", "port": 53}, + {"protocol": "TCP", "port": 53}, + ], + }, + { + "to": [{"podSelector": {"matchLabels": {"app": "postgres"}}}], + "ports": [{"protocol": "TCP", "port": 5432}], + }, + { + "to": [ + {"podSelector": {"matchLabels": {"app": "entity-management-service"}}} + ], + "ports": [{"protocol": "TCP", "port": 6565}], + }, + ], +} + + +def validate_migrator_network_policy(policy): + if policy.get("spec") != EXPECTED_MIGRATOR_POLICY_SPEC: + raise ValueError( + "migration NetworkPolicy must exactly select the dedicated pods and allow " + "only kube-dns UDP/TCP 53, same-namespace postgres TCP 5432, and " + "same-namespace Entity Management TCP 6565" + ) + + +def assert_migrator_policy_rejected(case, mutate): + fixture = copy.deepcopy(policy) + mutate(fixture["spec"]) + try: + validate_migrator_network_policy(fixture) + except ValueError: + return + raise SystemExit(f"migration NetworkPolicy validator accepted invalid fixture: {case}") + + disabled = render("migration-disabled") if disabled.returncode != 0: raise SystemExit(f"disabled chart render failed: {disabled.stderr}") @@ -257,27 +314,74 @@ if source.get("items", [{}])[0].get("path") != "expected-source.json": policy = by_kind_name.get(("NetworkPolicy", "game-design-baseline-migrator")) if policy is None: raise SystemExit("enabled configuration did not render the isolated migration policy") -policy_spec = policy.get("spec", {}) -if policy_spec.get("podSelector", {}).get("matchLabels") != { - "app": "game-design-baseline-migrator", - "firemud.dev/workload": "game-design-baseline-migrator", -}: - raise SystemExit("migration NetworkPolicy does not select only the dedicated Job pods") -if policy_spec.get("ingress") != []: - raise SystemExit("migration Job must not accept inbound connections") -allowed = { - ( - rule.get("to", [{}])[0].get("podSelector", {}).get("matchLabels", {}).get("app"), - rule.get("ports", [{}])[0].get("port"), - ) - for rule in policy_spec.get("egress", []) - if rule.get("to") -} -if ("postgres", 5432) not in allowed or ("entity-management-service", 6565) not in allowed: - raise SystemExit("migration Job egress must include only the required DB and Entity ports") -for app, port in allowed: - if (app, port) not in {("postgres", 5432), ("entity-management-service", 6565), (None, 53)}: - raise SystemExit(f"migration Job has unrelated egress permission: {(app, port)}") +try: + validate_migrator_network_policy(policy) +except ValueError as error: + raise SystemExit(str(error)) + +assert_migrator_policy_rejected( + "extra-second-peer", + lambda spec: spec["egress"][1]["to"].append( + {"podSelector": {"matchLabels": {"app": "unrelated"}}} + ), +) +assert_migrator_policy_rejected( + "extra-second-port", + lambda spec: spec["egress"][1]["ports"].append( + {"protocol": "TCP", "port": 5433} + ), +) +assert_migrator_policy_rejected( + "rule-without-peer", + lambda spec: spec["egress"].append({"ports": [{"protocol": "TCP", "port": 1}]}), +) +assert_migrator_policy_rejected( + "empty-policy-selector", lambda spec: spec.update(podSelector={}) +) +assert_migrator_policy_rejected( + "missing-migrator-workload-label", + lambda spec: spec["podSelector"]["matchLabels"].pop("firemud.dev/workload"), +) +assert_migrator_policy_rejected( + "empty-peer-selector", + lambda spec: spec["egress"].append( + {"to": [{"podSelector": {}}], "ports": [{"protocol": "TCP", "port": 1}]} + ), +) +assert_migrator_policy_rejected( + "wildcard-namespace-selector", + lambda spec: spec["egress"][0]["to"][0].update(namespaceSelector={}), +) +assert_migrator_policy_rejected( + "wrong-dns-namespace", + lambda spec: spec["egress"][0]["to"][0]["namespaceSelector"]["matchLabels"].update( + {"kubernetes.io/metadata.name": "default"} + ), +) +assert_migrator_policy_rejected( + "wrong-dns-pod-selector", + lambda spec: spec["egress"][0]["to"][0]["podSelector"]["matchLabels"].update( + {"k8s-app": "not-dns"} + ), +) +assert_migrator_policy_rejected( + "wrong-protocol", + lambda spec: spec["egress"][0]["ports"][0].update(protocol="TCP"), +) +assert_migrator_policy_rejected( + "extra-end-port", + lambda spec: spec["egress"][1]["ports"][0].update(endPort=5434), +) +assert_migrator_policy_rejected( + "ip-block-peer", + lambda spec: spec["egress"][1]["to"].append( + {"ipBlock": {"cidr": "0.0.0.0/0"}} + ), +) +assert_migrator_policy_rejected( + "missing-egress-isolation", + lambda spec: spec.update(policyTypes=["Ingress"]), +) for case, mutation, fragment in ( ( From d3d6b49c69deffbe57262fc0ccbce912e658c7e8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 23:49:04 +1300 Subject: [PATCH 24/28] Clarify canonical Entity v2 definition ordering --- .../api-contracts.md | 5 ++-- ...ntityDraftDesignDigestServiceImplTest.java | 30 ++++++++++++------- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index f52d424261..526996660d 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -81,7 +81,7 @@ Implementation Notes: - The current implementation hashes the version-scoped entity-definition rows for the requested `(tenantId, versionId)` and returns synthetic `appliedCommitId = "version:"` until the later applied-revision ledger lands. - Current version-scoped digest inputs include `items`, `npcs`, `crafting_recipes`, `equipment_slot_definitions`, and `body_layout_slot_definitions`; later entity-template families must join this same `(tenantId, versionId)` digest contract when introduced. -- The current item projection includes optional `equipmentSlot` and `equipmentSlotGroupKey`, normalized like runtime equipment admission (null/blank to empty; otherwise trim and uppercase), and optional `effectPayloadJson`, canonicalized as parsed JSON with recursively stable object-key ordering (null/blank to empty; malformed nonblank JSON fails closed). Equipment-slot definitions contribute normalized slot and group keys plus display name; body-layout membership contributes normalized layout and slot keys. Both projections are sorted by semantic keys and exclude database row IDs and optimistic version counters. It reports `digestSchemaVersion=2`. Focused producer proof covers normalized slot and slot-group equivalents, definition-side slot/group/layout changes, row-order and optimistic-version equivalence, distinct effect payloads, malformed payload rejection, and tenant/version-scoped reads; Game Design's publish gate accepts Entity v2 and rejects v1 or unsupported evidence. Previously recorded v1 evidence still requires affected-scope replay or recomputation, re-recording, and readback before publish; this code change does not perform a live-data migration. +- The current item projection includes optional `equipmentSlot` and `equipmentSlotGroupKey`, normalized like runtime equipment admission (null/blank to empty; otherwise trim and uppercase), and optional `effectPayloadJson`, canonicalized as parsed JSON with recursively stable object-key ordering (null/blank to empty; malformed nonblank JSON fails closed). Equipment-slot definitions contribute normalized slot and group keys plus display name; body-layout membership contributes normalized layout and slot keys. These definition projections follow the relation-specific canonical ordering below and exclude database row IDs and optimistic version counters. It reports `digestSchemaVersion=2`. Focused producer proof covers normalized slot and slot-group equivalents, definition-side slot/group/layout changes, row-order and optimistic-version equivalence, distinct effect payloads, malformed payload rejection, and tenant/version-scoped reads; Game Design's publish gate accepts Entity v2 and rejects v1 or unsupported evidence. Previously recorded v1 evidence still requires affected-scope replay or recomputation, re-recording, and readback before publish; this code change does not perform a live-data migration. - Included objects: - version-scoped entity-template tables such as item, NPC, equipment, loot-table, and balance-curve definitions keyed by `(tenantId, versionId)`; @@ -91,7 +91,8 @@ Implementation Notes: - audit/history/provenance tables and non-semantic timestamps; - applied-revision ledgers when those rows do not affect entity semantics. - Canonicalization rules: - - serialize included relations in stable table order, then primary-key order; + - serialize included relations in lexicographic table-name order; + - order ordinary relation rows by stable cross-service identifiers where applicable, otherwise by primary key; for schema-v2 `equipment_slot_definitions`, order by normalized `slot_key`, then `display_name` (null to empty), then normalized `slot_group_key`; for `body_layout_slot_definitions`, order by normalized `body_layout_key`, then normalized `slot_key`; - include only semantic fields plus stable identifiers referenced cross-service; - normalize encoded structured fields before hashing; for `effectPayloadJson`, parse nonblank JSON and serialize nested objects with stable lexicographic key ordering, failing closed on malformed nonblank JSON. - `digestSchemaVersion` must increment whenever included objects, semantic field selection, or serialization semantics change. For this manifest, once `v2` is deployed, `v1` is unsupported. The schema bump invalidates previously recorded participant evidence for the affected scope: publish/reconciliation must not compare a new-schema digest with a recorded `v1` digest, and Entity must reject a requested or reported unsupported version until the compatible canonicalization is deployed. The migration must explicitly replay or recompute each affected `(tenantId, versionId)` digest, re-record its `appliedCommitId`, digest, and schema version, and provide readback proof before the publish gate accepts the new version; it must not silently reinterpret or migrate old hashes in place. diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java index ff14fdedcd..b1e3e6b592 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java @@ -141,32 +141,40 @@ void bodyLayoutSlotSemanticsChangeTheDigest() { @Test void canonicalizesVocabularyKeysAndIgnoresRowOrderAndOptimisticVersion() { - var firstSlot = slotDefinition(" HEAD ", "Head", " upper "); - firstSlot.setVersion(2); - var secondSlot = slotDefinition("TORSO", "Torso", null); - secondSlot.setVersion(8); - var firstLayoutSlot = bodyLayoutSlot(" Humanoid ", " Head "); - firstLayoutSlot.setVersion(3); - var secondLayoutSlot = bodyLayoutSlot("HUMANOID", "TORSO"); - secondLayoutSlot.setVersion(9); + var firstSlot = slotDefinition("TORSO", "Torso", null); + firstSlot.setId(11L); + firstSlot.setVersion(8); + var secondSlot = slotDefinition(" HEAD ", "Head", " upper "); + secondSlot.setId(22L); + secondSlot.setVersion(2); + var firstLayoutSlot = bodyLayoutSlot("HUMANOID", "TORSO"); + firstLayoutSlot.setId(31L); + firstLayoutSlot.setVersion(9); + var secondLayoutSlot = bodyLayoutSlot(" ALPHA ", " Head "); + secondLayoutSlot.setId(32L); + secondLayoutSlot.setVersion(3); var firstDigest = digestForDefinitions( List.of(firstSlot, secondSlot), List.of(firstLayoutSlot, secondLayoutSlot)); var normalizedSlot = slotDefinition("HEAD", "Head", "UPPER"); + normalizedSlot.setId(3L); normalizedSlot.setVersion(200); var normalizedSecondSlot = slotDefinition("TORSO", "Torso", " "); + normalizedSecondSlot.setId(100L); normalizedSecondSlot.setVersion(800); - var normalizedFirstLayoutSlot = bodyLayoutSlot("HUMANOID", "HEAD"); + var normalizedFirstLayoutSlot = bodyLayoutSlot("ALPHA", "HEAD"); + normalizedFirstLayoutSlot.setId(5L); normalizedFirstLayoutSlot.setVersion(300); var normalizedSecondLayoutSlot = bodyLayoutSlot(" humanoid ", " torso "); + normalizedSecondLayoutSlot.setId(600L); normalizedSecondLayoutSlot.setVersion(900); var equivalentDigest = digestForDefinitions( - List.of(normalizedSecondSlot, normalizedSlot), - List.of(normalizedSecondLayoutSlot, normalizedFirstLayoutSlot)); + List.of(normalizedSlot, normalizedSecondSlot), + List.of(normalizedFirstLayoutSlot, normalizedSecondLayoutSlot)); assertEquals(firstDigest.contentDigest(), equivalentDigest.contentDigest()); } From 24317b256bef5474dc75cce2f560b018a348842f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 07:45:26 +1300 Subject: [PATCH 25/28] Report script-only Entity baseline scopes as blocked --- .../game-design-service/operations.md | 2 ++ .../EntityDigestBaselineMigrationService.java | 9 +++-- ...ityDigestBaselineMigrationServiceTest.java | 36 +++++++++++++++++++ 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 4c7da62c7f..a48b8f3729 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -30,6 +30,8 @@ The target publication boundary treats object-store export as a durable candidat ### Historical Entity digest baseline migration +Enumeration reports retained Entity full-version v1 baselines that resolve to a script-only Version as `BLOCKED_SCRIPT_ONLY`, not as migratable full versions. Exact preflight and migration continue to reject those scopes with `VERSION_SCOPE_MISMATCH`; enumeration neither repairs the anomalous row nor changes its provenance. + **Current implementation status:** The one-shot Game Design maintenance Job and guarded owner-local v1→v2 baseline transition are implemented, but no retained row set or live certificate/consumer/readback outcome has been verified by this document. A retained v1 scope whose authoritative Version is `DRAFT` is reported as `BLOCKED_DRAFT`; migrate rejects it before the Entity digest read and locks/rechecks Version state at the baseline-and-audit write boundary. A no-data scope, existing v2 row, ambiguous scope, or unsupported schema retains its separate preflight classification. This does not freeze live authoring. Publication quiescence drains publication work only and must not be treated as an authoring freeze or proof that DRAFT content cannot change. The Job is disabled in ordinary Helm releases and must be invoked only from a trusted operator context, using a reviewed immutable Game Design image digest. It is not a public API, a general admin role, or a PR-controlled executor. Its dedicated `game-design-baseline-migrator` Kubernetes service account has no Kubernetes API verbs, and its separate client certificate may read only Entity Management's bound `GetDraftDesignDigest` RPC. No Game Design, Account, or Game Session mutation API is delegated to that identity. The Job only writes Game Design's own baseline and audit tables through its guarded service operation; it never accesses Entity's database. Use a controlled pre-v1 publication window for the affected Entity v1 full-version scopes. Drain in-flight publication and prevent new publication on those scopes before comparing rows or deploying the writer. Deploy the migration-capable Game Design reader/reconciler image first so retained stored v1 and v2 baseline shapes can be inspected; its publish gate still requires v2 and never compares v1 content with v2 content. Then deploy Entity's v2 producer image. Because #2872 already has a v2-only gate, deploying it alone may temporarily block affected v1 publication; this is an accepted fail-closed maintenance window, not seamless dual-reader availability. Verify actual service image digests and deployment order before proceeding; if the image topology cannot maintain that sequence, stop instead of relaxing the gate. The current Entity applied-commit token is synthetic `version:` and does not prove durable applied-revision convergence. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java index 8368bee60f..80b39f332f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java @@ -515,9 +515,11 @@ private BaselineSummary toV1Summary(RecordedParticipantDigest row) { ScopeStatus status = version == null ? ScopeStatus.BLOCKED_VERSION_MISSING - : version.getVersionState() == VersionLifecycleState.DRAFT - ? ScopeStatus.BLOCKED_DRAFT - : ScopeStatus.V1_REQUIRES_MIGRATION; + : version.isScriptOnly() + ? ScopeStatus.BLOCKED_SCRIPT_ONLY + : version.getVersionState() == VersionLifecycleState.DRAFT + ? ScopeStatus.BLOCKED_DRAFT + : ScopeStatus.V1_REQUIRES_MIGRATION; return toSummary(row, status); } @@ -606,6 +608,7 @@ public enum ScopeStatus { V1_REQUIRES_MIGRATION, BLOCKED_DRAFT, BLOCKED_VERSION_MISSING, + BLOCKED_SCRIPT_ONLY, V2_ALREADY_RECORDED, NO_RECORDED_BASELINE, AMBIGUOUS_BASELINE, diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java index a1ecf07092..e2d79768c8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java @@ -180,6 +180,42 @@ void enumerationReturnsBoundedCursorPageWithExactScopeIdentities() { assertFalse(page.isEmptyAtCursor()); } + @Test + void enumerationBlocksRetainedFullVersionBaselineForScriptOnlyVersion() { + EntityDigestBaselineMigrationService service = serviceWithMockWriter(); + when(baselineRepository.findEntityV1FullVersionBatchAfterId(10L, 25)) + .thenReturn(List.of(source)); + Version scriptOnly = version(); + scriptOnly.setScriptOnly(true); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(scriptOnly)); + + EntityDigestBaselineMigrationService.EntityV1Batch page = + service.enumerateEntityV1Batch(10L, 25); + + assertEquals(BASELINE_ID, page.nextAfterBaselineId()); + assertEquals(BASELINE_ID, page.baselines().get(0).baselineId()); + assertEquals(TENANT_ID, page.baselines().get(0).tenantId()); + assertEquals(VERSION_ID, page.baselines().get(0).versionId()); + assertEquals( + EntityDigestBaselineMigrationService.ScopeStatus.BLOCKED_SCRIPT_ONLY, + page.baselines().get(0).status()); + assertFalse(page.isEmptyAtCursor()); + + EntityDigestBaselineMigrationService.MigrationRejectedException preflightRejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> service.preflightScope(TENANT_ID, VERSION_ID)); + assertEquals("VERSION_SCOPE_MISMATCH", preflightRejected.failureCode()); + EntityDigestBaselineMigrationService.MigrationRejectedException migrationRejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> service.migrate(command)); + assertEquals("VERSION_SCOPE_MISMATCH", migrationRejected.failureCode()); + verify(entityManagementClient, never()).getDraftDesignDigestForVersion(any()); + verify(auditRepository, never()).insert(any()); + } + @Test void migrateRejectsNewDraftOperationBeforeEntityDigestOrBaselineRead() { Version draft = version(); From 82cd45a4267ef9491927311cea0f925a5878378d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 09:00:44 +1300 Subject: [PATCH 26/28] Reject noncanonical definition keys before Entity digest attestation --- .../api-contracts.md | 1 + .../EntityDraftDesignDigestServiceImpl.java | 28 +++++++++++---- ...ntityDraftDesignDigestServiceImplTest.java | 35 ++++++++++++++++--- 3 files changed, 54 insertions(+), 10 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 526996660d..d254b3cb10 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -80,6 +80,7 @@ Entity Management is a required publish-gate participant and must maintain a sta Implementation Notes: - The current implementation hashes the version-scoped entity-definition rows for the requested `(tenantId, versionId)` and returns synthetic `appliedCommitId = "version:"` until the later applied-revision ledger lands. +- The producer fails closed when persisted required equipment slot or body-layout keys are null, blank, or not already in trim-plus-uppercase canonical form; runtime definition lookups use exact stored keys, so normalizing malformed stored definition keys for the digest could attest different semantics. This producer check does not clean up retained rows, and no retained-row cleanup is implemented or proven. - Current version-scoped digest inputs include `items`, `npcs`, `crafting_recipes`, `equipment_slot_definitions`, and `body_layout_slot_definitions`; later entity-template families must join this same `(tenantId, versionId)` digest contract when introduced. - The current item projection includes optional `equipmentSlot` and `equipmentSlotGroupKey`, normalized like runtime equipment admission (null/blank to empty; otherwise trim and uppercase), and optional `effectPayloadJson`, canonicalized as parsed JSON with recursively stable object-key ordering (null/blank to empty; malformed nonblank JSON fails closed). Equipment-slot definitions contribute normalized slot and group keys plus display name; body-layout membership contributes normalized layout and slot keys. These definition projections follow the relation-specific canonical ordering below and exclude database row IDs and optimistic version counters. It reports `digestSchemaVersion=2`. Focused producer proof covers normalized slot and slot-group equivalents, definition-side slot/group/layout changes, row-order and optimistic-version equivalence, distinct effect payloads, malformed payload rejection, and tenant/version-scoped reads; Game Design's publish gate accepts Entity v2 and rejects v1 or unsupported evidence. Previously recorded v1 evidence still requires affected-scope replay or recomputation, re-recording, and readback before publish; this code change does not perform a live-data migration. diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java index 87900cd1b4..b2e7c652c6 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java @@ -141,7 +141,8 @@ public EntityDraftDesignDigest getDraftDesignDigest(String tenantId, String vers .sorted( Comparator.comparing( (EquipmentSlotDefinition definition) -> - normalizeOptionalKey(definition.getSlotKey())) + canonicalRequiredKey( + definition.getSlotKey(), "equipment slot key")) .thenComparing(definition -> value(definition.getDisplayName())) .thenComparing( definition -> @@ -149,7 +150,9 @@ public EntityDraftDesignDigest getDraftDesignDigest(String tenantId, String vers .map( definition -> Map.of( - "slotKey", normalizeOptionalKey(definition.getSlotKey()), + "slotKey", + canonicalRequiredKey( + definition.getSlotKey(), "equipment slot key"), "displayName", value(definition.getDisplayName()), "slotGroupKey", normalizeOptionalKey(definition.getSlotGroupKey()))) @@ -162,15 +165,21 @@ public EntityDraftDesignDigest getDraftDesignDigest(String tenantId, String vers .sorted( Comparator.comparing( (BodyLayoutSlotDefinition definition) -> - normalizeOptionalKey(definition.getBodyLayoutKey())) + canonicalRequiredKey( + definition.getBodyLayoutKey(), "body layout key")) .thenComparing( - definition -> normalizeOptionalKey(definition.getSlotKey()))) + definition -> + canonicalRequiredKey( + definition.getSlotKey(), "body layout slot key"))) .map( definition -> Map.of( "bodyLayoutKey", - normalizeOptionalKey(definition.getBodyLayoutKey()), - "slotKey", normalizeOptionalKey(definition.getSlotKey()))) + canonicalRequiredKey( + definition.getBodyLayoutKey(), "body layout key"), + "slotKey", + canonicalRequiredKey( + definition.getSlotKey(), "body layout slot key"))) .toList())); return new EntityDraftDesignDigest( tenantId, @@ -191,6 +200,13 @@ private String normalizeOptionalKey(String value) { return value == null || value.isBlank() ? "" : value.trim().toUpperCase(Locale.ROOT); } + private String canonicalRequiredKey(String value, String fieldName) { + if (value == null || value.isBlank() || !value.equals(value.trim().toUpperCase(Locale.ROOT))) { + throw new IllegalArgumentException(fieldName + " must use its canonical stored key"); + } + return value; + } + private String canonicalizeOptionalJson(String value) { if (value == null || value.isBlank()) { return ""; diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java index b1e3e6b592..ff6343af06 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java @@ -140,17 +140,44 @@ void bodyLayoutSlotSemanticsChangeTheDigest() { } @Test - void canonicalizesVocabularyKeysAndIgnoresRowOrderAndOptimisticVersion() { + void rejectsNoncanonicalEquipmentSlotDefinitionKeys() { + for (String slotKey : new String[] {null, "", " \t ", " HEAD ", "head"}) { + assertThrows( + IllegalStateException.class, + () -> digestForDefinitions(List.of(slotDefinition(slotKey, "Head", null)), List.of())); + } + } + + @Test + void rejectsNoncanonicalBodyLayoutDefinitionKeys() { + for (String bodyLayoutKey : new String[] {null, "", " \t ", " HUMANOID ", "humanoid"}) { + assertThrows( + IllegalStateException.class, + () -> digestForDefinitions(List.of(), List.of(bodyLayoutSlot(bodyLayoutKey, "HEAD")))); + } + } + + @Test + void rejectsNoncanonicalBodyLayoutSlotKeys() { + for (String slotKey : new String[] {null, "", " \t ", " HEAD ", "head"}) { + assertThrows( + IllegalStateException.class, + () -> digestForDefinitions(List.of(), List.of(bodyLayoutSlot("HUMANOID", slotKey)))); + } + } + + @Test + void canonicalizesEquivalentGroupKeysAndIgnoresRowOrderAndOptimisticVersion() { var firstSlot = slotDefinition("TORSO", "Torso", null); firstSlot.setId(11L); firstSlot.setVersion(8); - var secondSlot = slotDefinition(" HEAD ", "Head", " upper "); + var secondSlot = slotDefinition("HEAD", "Head", " upper "); secondSlot.setId(22L); secondSlot.setVersion(2); var firstLayoutSlot = bodyLayoutSlot("HUMANOID", "TORSO"); firstLayoutSlot.setId(31L); firstLayoutSlot.setVersion(9); - var secondLayoutSlot = bodyLayoutSlot(" ALPHA ", " Head "); + var secondLayoutSlot = bodyLayoutSlot("ALPHA", "HEAD"); secondLayoutSlot.setId(32L); secondLayoutSlot.setVersion(3); @@ -167,7 +194,7 @@ void canonicalizesVocabularyKeysAndIgnoresRowOrderAndOptimisticVersion() { var normalizedFirstLayoutSlot = bodyLayoutSlot("ALPHA", "HEAD"); normalizedFirstLayoutSlot.setId(5L); normalizedFirstLayoutSlot.setVersion(300); - var normalizedSecondLayoutSlot = bodyLayoutSlot(" humanoid ", " torso "); + var normalizedSecondLayoutSlot = bodyLayoutSlot("HUMANOID", "TORSO"); normalizedSecondLayoutSlot.setId(600L); normalizedSecondLayoutSlot.setVersion(900); From b68e064884a169215df84f611c08fdafc0290f46 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:23:25 +1300 Subject: [PATCH 27/28] 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 ab913ed618..b2300b09a7 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 b38e7dca6ab228941baec49c65fdcce875497369 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:37:08 +1300 Subject: [PATCH 28/28] 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 b2300b09a7..979ffef097 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1012,7 +1012,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) {