From 9e1bf38e595183822a6a44ac1459779e84d85949 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:15:25 +1300 Subject: [PATCH 01/11] feat: retain owner-local runtime family catalog evidence --- .../api-contracts.md | 12 + .../runtime-and-data.md | 32 + .../api-contracts.md | 14 + .../runtime-and-data.md | 27 + .../game-session-service/api-contracts.md | 8 + .../social-groups-service/api-contracts.md | 9 + .../social-groups-service/runtime-and-data.md | 12 + .../world-management-service/api-contracts.md | 14 + .../runtime-and-data.md | 26 + .../automation-and-scheduler-runtime.md | 10 +- .../gameplay-rules-entities-and-effects.md | 10 + ...r-experience-commands-and-communication.md | 1 + .../realm-routing-and-playable-state.md | 8 + ...tomation_runtime_family_catalog_read.proto | 23 + .../entity_runtime_family_catalog_read.proto | 22 + .../social_runtime_family_catalog_read.proto | 23 + .../world_runtime_family_catalog_read.proto | 23 + ...onRuntimeFamilyCatalogReadGrpcService.java | 121 +++ ...omationRuntimeFamilyCatalogRepository.java | 159 ++++ ...utomation_owner_runtime_family_catalog.sql | 339 +++++++++ ...AndRetentionRepositoryIntegrationTest.java | 13 +- ...eFamilyCatalogPostgresIntegrationTest.java | 705 ++++++++++++++++++ ...nRuntimeLifecycleFenceIntegrationTest.java | 7 +- ...ptDefinitionRepositoryIntegrationTest.java | 4 +- ...atchReadinessSingletonIntegrationTest.java | 7 +- ...grationAndRolloutEventIntegrationTest.java | 4 +- ...tionServiceTransactionIntegrationTest.java | 4 +- ...ntimeFamilyCatalogReadGrpcServiceTest.java | 188 +++++ .../AutomationRuntimeFamilyCatalog.java | 400 ++++++++++ .../AutomationRuntimeFamilyCatalogCodec.java | 173 +++++ .../entity/EntityRuntimeFamilyCatalog.java | 360 +++++++++ .../EntityRuntimeFamilyCatalogCodec.java | 168 +++++ .../social/SocialRuntimeFamilyCatalog.java | 398 ++++++++++ .../SocialRuntimeFamilyCatalogCodec.java | 180 +++++ .../world/WorldRuntimeFamilyCatalog.java | 324 ++++++++ .../world/WorldRuntimeFamilyCatalogCodec.java | 175 +++++ .../AutomationRuntimeFamilyCatalogTest.java | 284 +++++++ .../EntityRuntimeFamilyCatalogTest.java | 268 +++++++ .../SocialRuntimeFamilyCatalogTest.java | 266 +++++++ .../world/WorldRuntimeFamilyCatalogTest.java | 222 ++++++ .../EntityRuntimeFamilyCatalogRepository.java | 150 ++++ ...tyRuntimeFamilyCatalogReadGrpcService.java | 119 +++ ...5__entity_owner_runtime_family_catalog.sql | 304 ++++++++ ...eseededActorAssignmentIntegrationTest.java | 5 +- .../RetainedActorIdentityIntegrationTest.java | 14 +- ...haracterCreatePostgresIntegrationTest.java | 6 +- ...ntakeMigrationPostgresIntegrationTest.java | 2 +- ...eFamilyCatalogPostgresIntegrationTest.java | 677 +++++++++++++++++ ...ntimeFamilyCatalogReadGrpcServiceTest.java | 202 +++++ .../AutomationRuntimeFamilyCatalogClient.java | 84 +++ .../EntityRuntimeFamilyCatalogClient.java | 79 ++ .../SocialRuntimeFamilyCatalogClient.java | 85 +++ .../WorldRuntimeFamilyCatalogClient.java | 81 ++ ...ionRuntimeFamilyCatalogClientMtlsTest.java | 329 ++++++++ ...ityRuntimeFamilyCatalogClientMtlsTest.java | 296 ++++++++ ...ialRuntimeFamilyCatalogClientMtlsTest.java | 289 +++++++ ...rldRuntimeFamilyCatalogClientMtlsTest.java | 283 +++++++ ...alRuntimeFamilyCatalogReadGrpcService.java | 124 +++ .../SocialRuntimeFamilyCatalogRepository.java | 160 ++++ ...4__social_owner_runtime_family_catalog.sql | 280 +++++++ ...eFamilyCatalogPostgresIntegrationTest.java | 599 +++++++++++++++ ...ntimeFamilyCatalogReadGrpcServiceTest.java | 226 ++++++ ...ldRuntimeFamilyCatalogReadGrpcService.java | 100 +++ .../WorldRuntimeFamilyCatalogRepository.java | 162 ++++ ...46__world_owner_runtime_family_catalog.sql | 274 +++++++ ...eFamilyCatalogPostgresIntegrationTest.java | 496 ++++++++++++ ...ntimeFamilyCatalogReadGrpcServiceTest.java | 186 +++++ 67 files changed, 10633 insertions(+), 22 deletions(-) create mode 100644 protos/automation-scripting/v1/automation_runtime_family_catalog_read.proto create mode 100644 protos/entity-management/v1/entity_runtime_family_catalog_read.proto create mode 100644 protos/social-groups/v1/social_runtime_family_catalog_read.proto create mode 100644 protos/world-management/v1/world_runtime_family_catalog_read.proto create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogRepository.java create mode 100644 services/automation-scripting-service/src/main/resources/db/migration/V1004__automation_owner_runtime_family_catalog.sql create mode 100644 services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java create mode 100644 services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalog.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogTest.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogTest.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogTest.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogTest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogRepository.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java create mode 100644 services/entity-management-service/src/main/resources/db/migration/V1025__entity_owner_runtime_family_catalog.sql create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcServiceTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialRuntimeFamilyCatalogClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClient.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClientMtlsTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClientMtlsTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/SocialRuntimeFamilyCatalogClientMtlsTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClientMtlsTest.java create mode 100644 services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcService.java create mode 100644 services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogRepository.java create mode 100644 services/social-groups-service/src/main/resources/db/migration/V1004__social_owner_runtime_family_catalog.sql create mode 100644 services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java create mode 100644 services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcServiceTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogRepository.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcServiceTest.java diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index 735bf805dc..0f775e99ac 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -35,6 +35,18 @@ Target formation control-plane behavior eliminates unauthenticated service-local - Durable parent-event identity, canonical request-digest conflict handling, an atomically frozen ordered handler manifest, binding-scoped plugin execution identity, and activation-epoch fencing under ADR 0172 are not implemented. Current retries can still re-resolve mutable handler state. - Registry-classified `REJECT_VISIBLE`, `DURABLE_RETRY`, and `SKIP_RECONCILE` reload handling, transient attempt state, producer-specific expiry/backoff, and policy-specific proof under ADR 0173 are not implemented. Current denial memoization and producer behavior do not establish that target. +## Owner-local runtime-family catalog read + +[`AutomationRuntimeFamilyCatalogReadService.ReadAutomationRuntimeFamilyCatalog`](../../../../protos/automation-scripting/v1/automation_runtime_family_catalog_read.proto) is a standalone, manually composed source prerequisite. Its owner-local schema/classification, durable epoch, immutable snapshot, and retained-family consequences are defined in the [runtime/data catalog contract](./runtime-and-data.md#owner-local-runtime-family-catalog). Implementation and proof status belong to the [Automation tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#owner-local-runtime-family-catalog-source-prerequisite). Neither producer nor Game Session client is registered by default; this read grants no owner enrollment, FRESH completeness/materialization, actor authorization, runtime admission, CLOSED aggregation, or activation authority. + +The receiver authenticates the exact same-workload-namespace `game-session-service` mTLS peer before decoding request bytes or touching SQL. Account/role context, global/scoped role overrides, shared internal-service credentials, absent or foreign peer identity, and ambient SQL transaction/synchronization refuse. A request binds one non-nil `readRequestId` UUID and the configured workload `targetNamespace`; a request namespace must match the authenticated peer and owner configuration. This workload namespace is not a playable-state namespace, tenant selector, actor identity, lifecycle token, or proof of any target's absence. + +Each protobuf message contains exactly one canonical bytes field; duplicate, missing, unknown, malformed, trailing, or oversized input refuses rather than truncating or paginating. The version-1 request frame is `ACR1`, followed by the UUID's 16 bytes and a four-byte big-endian length-prefixed ASCII workload namespace. The `ACE1` evidence frame binds the complete length-prefixed original request, a non-nil snapshot UUID, the length-prefixed catalog SHA-256 digest, and the complete length-prefixed original catalog bytes. UUIDs use big-endian most-significant then least-significant bits. Digests use lowercase `sha256:<64 hex digits>`. The request wire limit is 1,024 bytes; the complete response wire limit is 2 MiB plus 4,096 bytes, without expanding the nested 2 MiB catalog bound. Exact bytes, snapshot identity, request correlation, epoch, and digests must survive complete decoding and retained readback. + +The owner commits capture before performing independent committed readback; an exact retry returns its original retained snapshot, not a new sample under the same request. Changed correlation input, namespace, catalog epoch, schema/classification, original bytes, or digest binding cannot replace that evidence. An absent catalog, unclassified family, drifted epoch, unavailable store, unsupported evidence, or contradictory retained record is a refusal, never an empty owner or initialized target result. Authentication uses `UNAUTHENTICATED`/`PERMISSION_DENIED`, closed decoding uses `INVALID_ARGUMENT`, inconsistent or invalidated owner evidence uses `FAILED_PRECONDITION`, and storage failures retain their bounded transport classification without exposing private SQL details. + +Game Session's manually constructed `AutomationRuntimeFamilyCatalogClient` requires file-backed mTLS, pins the exact same-namespace Automation server URI SAN identity, applies finite inbound/outbound bounds and a five-second deadline, and rejects ambient SQL/synchronization before transport. Complete request/evidence comparison is mandatory; an outage or deadline is not an empty-source fallback. Consuming a successful source read does not resolve any blocking family disposition or non-SQL gap, and must not enroll Automation or enable a FRESH/lifecycle operation. No plugin activation, epoch generation, `onLoad`, schedule firing, work creation, or runtime mutation is performed to produce this read. + ## Script-transition API consequences The service-local control-plane and event-ingress surfaces apply the canonical script-transition authority as follows: diff --git a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md index c4125b0454..abc1b4c815 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -41,6 +41,38 @@ The current queue consumer has an additional bounded-drain limitation that must The selected-source terminal reader and Account settlement composition are standalone and unregistered construction components; they do not establish complete authenticated owner intake or physical proof. The [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) owns their code and validation status. Without the exact committed Account settlement, finalized source participation remains pending. +## Owner-local runtime-family catalog + +Automation's runtime-family catalog is an owner-local source classification, not a runtime-state manifest. Its fixed owner is `automation-scripting-service` and its closed schema is `automation-runtime-family-catalog/v1`. The canonical replacement and retention authorities remain [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md), [ADR 0137](../../decisions/adr-0137-isolated-playtest-state-modes-and-reset.md), [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md), and the [scheduler runtime-replacement classification](../../system-architecture-scripting-scheduler-and-timers.md#runtime-replacement-classification). This prerequisite does not enroll an owner, close a FRESH owner set, prove private lifecycle/namespace/build evidence, create a target, initialize gameplay, authorize an actor, or release runtime admission. Its [separate read API](./api-contracts.md#owner-local-runtime-family-catalog-read) owns authentication, framing, and consumer consequences; detailed source and proof status belong to the [Automation tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#owner-local-runtime-family-catalog-source-prerequisite). + +### Catalog source and retention boundary + +The owner derives a complete ordered census from the installed combined Automation/Saga PostgreSQL schema, not ORM names, observed rows, a zero count, hand-maintained table-name prefixes, or a mutable cache. Every installed table, including empty tables, has an explicit relation-level disposition; material mixed components are named separately and must exist as installed columns. Live table/column, constraint/index, trigger/policy/rule, routine, sequence definition, view, and type facts and actual configured Flyway history bind the schema seal. Gameplay payload rows, sequence positions, volatile statistics, and installation timestamps do not define that seal. Adding, removing, renaming, or changing a covered object or classification invalidates the current epoch; an unclassified table or missing classified component refuses even if it contains no rows. + +The catalog retains exact PostgreSQL-produced UTF-8 bytes with a positive monotonic owner-local epoch and SHA-256 digest. Its closed root fields are `schema`, `owner`, decimal-string `catalogEpoch`, `families`, `schemaFacts`, and `nonSqlGaps`. Ordered, nonduplicate family entries bind exact relation/component, role, state class, FRESH disposition, retention disposition, and a bounded explicit owner consequence. Schema facts bind kind, identity, and definition digest. Limits are 512 families, 16,384 schema facts, 32 known non-SQL gaps, and 2 MiB of complete catalog bytes; exceeding a bound refuses, never returns a partial source. Roles distinguish `RUNTIME_PAYLOAD`, `SOURCE`, `CONTROL`, `AUDIT`, `PROVENANCE`, and `CATALOG`. `UNKNOWN`, `UNRESOLVED`, and `NOT_PAYLOAD` are classification/disposition evidence, not new runtime replacement classes; no S3 classification is inferred from this source. + +The additive V1004 storage consists of explicit classification and known non-SQL-gap declarations, retained catalog epochs, and immutable request-bound snapshots. It preserves prior Automation/Saga rows, source-intake guards, sequences, and migration history; it does not adopt old numeric identities or rewrite prior migrations. Flyway 13.12's built-in `${flyway:table}` binds the actual configured history table, including custom history names. Because the owner migration's successful history row is written after its transaction, the seal uses its exact installed definitions plus a stable installation marker and separately requires the successful exact V1004 script on later reads. It does not fabricate an own-migration checksum or treat a missing successful installation as current. + +Capture uses an independent owner transaction and complete retained readback in a separate read-only repeatable-read transaction. SQL guards bind the complete request/evidence frames to the latest exact sealed epoch; Java additionally compares every retained identity, byte array, and digest. Exact concurrent retries converge on one immutable snapshot. UPDATE, DELETE, and TRUNCATE of catalog declarations, epochs, or snapshots refuse; a later explicit owner revision cannot overwrite the old evidence, and an invalidated old request cannot be silently resampled. Catalog rows have no automatic expiry. These catalog retention guards neither replace existing runtime cleanup/hold rules nor grant new cleanup, clone, reset, resume, or deployment authority. + +### Explicit family consequences + +| Installed family or component | Source disposition and owner consequence | +| --- | --- | +| `npc_memory`, `npc_formations`, `npc_formation_member` | `STATE_CLASS_UNKNOWN_BLOCKING`: live/latent NPC behavior and actor references lack complete stable namespace, typed actor ownership, replacement classification, mapping, and required-initialization proof. Retain dependency closure; do not infer S3 or copy memory/formations. | +| `faction_standing` | `OWNERSHIP_DRIFT_BLOCKING`: the live Automation reputation writer conflicts with canonical Social ownership. Social owner migration requires explicit retained-row disposition, stable tenant/namespace/character/faction identity, and consumer cutover. The catalog must not normalize Automation as the FRESH standing owner or perform that cutover. Local `factions` definitions remain separate source input. | +| `script_schedule_instances` and due-point state | S2 with `NAMESPACE_MAPPING_BLOCKING`: canonical durable schedules are not disposable instance state. Current rows lack stable playable namespace and complete continuity/mapping and required-initialization evidence; do not inherit schedules/due points or fire them to manufacture proof. Authored `script_schedule_definitions` are source outside S1/S2/S3, not initialized runtime state. | +| `script_work_items`, including `read_snapshot_token` and `admission_epoch` | Runtime payload remains `STATE_CLASS_UNKNOWN_BLOCKING`; retained provenance/control components remain `RUNTIME_EVIDENCE_BLOCKING`. A legacy token/local barrier is not the complete sealed input manifest, descriptor/recovery bundle, or durable charge marker. No inherited pending work, replay, synthetic initialization, or cleanup follows from the census. | +| `script_event_ingress_audit`, `script_event_audit`, `script_handoff_events`, replay requests/results | Explicit audit/control/provenance with `RUNTIME_EVIDENCE_BLOCKING`; retain original claims, work/child/replay lineage, holds, and retry evidence. The ingress `script_id` component identifies the mixed pre-instance readiness branch, not namespace absence. Complete namespace, frozen-handler/recovery evidence, and measured retention horizons remain required. | +| `plugin_runtime_states`, request history, lifecycle events, signer-policy observation | Runtime state remains `STATE_CLASS_UNKNOWN_BLOCKING`; histories are retained blocking control/audit evidence, and policy observation is separate control input. Exact `(pluginActivationEpoch, lifecycleRevision)` does not establish private lifecycle/namespace/build identity, replacement classification, initialization, or a retention horizon. Do not enable a plugin or generate a lifecycle epoch to populate evidence. | +| Pin/rollout projections and events, admission state/history | Retained `RUNTIME_EVIDENCE_BLOCKING` control/audit, not authoritative Game Session pin/rollout chronology, actor authorization, or a private lifecycle manifest. No inherited source barrier, receipt, or chronology and no outage-to-UNPINNED fallback. | +| Scripts, event bindings, schedule definitions, readiness and `readiness_generation`, patch-base provenance, selected-source associations/receipts/reservations | Explicit source/control/provenance outside runtime S-classes, retained and non-cloned under their existing owners. Empty authored source is not empty runtime state. Tenant readiness is not durable game initialization; no `onLoad` is run for catalog evidence. Original source custody, signer/publication provenance and source guards remain unchanged. | +| Installed `saga_instance`/`saga_step`, actual Flyway history, catalog declarations/epochs/snapshots | Explicit retained control/catalog-only, not gameplay payload, a second lifecycle authority, owner enrollment, or materialization evidence. | + +### Known non-SQL limitations + +The `nonSqlGaps` declarations name known limitations, not a census of Redis keys. `DURABLE_CHARGE_MARKERS` is `UNSUPPORTED_BLOCKING`: current quota, tenant-budget, and capacity decisions are best-effort Redis counters/leases, with no durable full-Trigger-Identity charge family or exactly-once admission/execution-start markers. `QUEUE_POINTER_RETENTION` is also `UNSUPPORTED_BLOCKING`: the current pointer lists lack a TTL/length bound and owner-reconciled durable re-drive/reset gate. `QUEUE_DISCOVERY_AND_ENCODING`, `CAPACITY_LEASE_ACCOUNTING`, and `CENTRAL_RESET_ACL_REGISTRATION` are `UNRESOLVED_BLOCKING` for the existing raw identity builders/database-wide `KEYS`, non-idempotent retry leases, and incomplete central reset/ACL inventory described above. The SQL source must not invent durable charge rows or imply cluster, reset, accounting, PKI, operational Unit1B, seeded/snapshot, private-first-OPEN, or lifecycle qualification. Those holds remain separate and unchanged. + ## Authored Template Source Inventory Automation owns the source inventory declaration schema carried as authored content by a new versioned Game Design `TEMPLATE_CONFIG` source ([closed schema and reference rules](../game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state)). The Automation value schema is `automation-authored-source-inventory/v1` with exactly three required family arrays: `SCRIPT_DEFINITIONS`, `EVENT_BINDINGS`, and `SCRIPT_PATCH_SOURCES`. The current shared value accepts only explicitly authored empty arrays; omitted, null, unknown, malformed, duplicate, trailing, oversized, or nonempty input is rejected. Its canonical RFC 8785 bytes preserve the authored declaration deterministically. This declaration is content only: it is not an owner receipt, source readback, authorization, provenance, or proof of owner completeness, and cannot qualify a publication on its own. Existing `TEMPLATE_CONFIG` schema-version content is not reinterpreted as this declaration. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 41b7d404ec..5dd85c3b74 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -4,6 +4,20 @@ This document defines the Entity Management REST and gRPC surfaces, design-time The authoritative REST schema source lives in [../../../../services/entity-management-service/src/main/resources/openapi.yaml](../../../../services/entity-management-service/src/main/resources/openapi.yaml). Proto definitions are the authoritative gRPC source. +## Owner-local runtime-family catalog read + +`EntityRuntimeFamilyCatalogReadService.ReadEntityRuntimeFamilyCatalog` is the narrow internal read in [entity_runtime_family_catalog_read.proto](../../../../protos/entity-management/v1/entity_runtime_family_catalog_read.proto). It returns exact as-of Entity-local schema/classification evidence under the [runtime/data catalog contract](./runtime-and-data.md#owner-local-runtime-family-catalog), not a mode-specific manifest, actor-state inventory or initialization success. The handler, repository and Game Session client are manually composed and unregistered. Current source/proof status belongs to the [Entity implementation tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#entity-owner-local-runtime-family-catalog-prerequisite). + +The receiver requires the certificate-derived exact `spiffe://firemud/ns//sa/game-session-service` peer before closed-frame decoding or SQL. The configured namespace is the server-owned workload namespace, not a playable-state namespace or a caller-selected tenant. Missing peer identity refuses with `UNAUTHENTICATED`; another workload/namespace, authenticated caller/role context, internal-service context or mismatching request namespace refuses with `PERMISSION_DENIED`. Ambient SQL transactions or synchronization refuse with `FAILED_PRECONDITION` before decoding. Request data, ambient roles and SQL context supply no authentication. Manual transport composition must retain the existing certificate-derived peer interceptor and bounded gRPC transport; there is no new signing, trust or credential mechanism. + +Schema one carries a non-nil read-request UUID and exact workload namespace in one closed binary frame. Exactly one repeated-bytes occurrence is required in each purpose-specific proto envelope; unknown fields, duplicate occurrences, malformed/trailing data, unsupported schemas and numeric fallback are refused. The request bound is 1 KiB, the complete database-sealed catalog bound is 2 MiB, and the full response envelope bound is 2 MiB plus 4 KiB. Catalog arrays are finite and nonempty, with at most 512 families and 16,384 schema facts. No empty, partial, paginated or generic JSON registry response is accepted. The catalog's internal PostgreSQL JSON has a closed schema and is preserved as original UTF-8 bytes, not normalized or treated as caller-selected authority. + +The immutable response binds the original request/correlation, namespace, fixed owner `entity-management-service`, positive owner-local catalog epoch, exact catalog bytes and SHA-256, and owner-allocated snapshot UUID. Its complete evidence-frame SHA-256 is retained independently in Entity and exposed by the immutable typed value; Game Session recomputes it over the same exact evidence bytes. Digests use `sha256:` followed by 64 lowercase hexadecimal characters. Request and evidence frames use distinct schema-one magic values `0x45435231` and `0x45434531`; integers and lengths are big-endian, UUIDs are their two 64-bit halves, and variable fields are four-byte-length-prefixed. Evidence encodes the request frame, snapshot UUID, ASCII catalog digest and exact catalog bytes, in that order. No clock value, row count or fabricated runtime identity is substituted into the binding. + +Entity captures one immutable response per read-request UUID in its own transaction and independently reads the committed response back. Exact concurrent retries converge on that response; a changed namespace/request, absent snapshot, changed catalog or invalidated epoch refuses rather than resampling under the same identity. The Game Session consumer authenticates the exact same-namespace Entity server using both peer-qualified call credentials and the peer interceptor, applies a five-second RPC deadline and the finite envelope limits, and retains only typed exact evidence/correlation. An outage is not an empty catalog. Calls and client initialization run outside ambient SQL. The read does not protect a later other-owner commit or establish cross-owner currentness. + +Malformed input uses `INVALID_ARGUMENT`; catalog drift, missing or contradictory retained evidence uses bounded `FAILED_PRECONDITION`; transient storage/dependency failure uses `UNAVAILABLE`; serialization/deadlock SQL conflicts use `ABORTED`; unexpected storage/programming failures use `INTERNAL`. Descriptions omit private SQL/upstream details and no failure emits a partial response or response-level error. Conditional and `UNRESOLVED` catalog entries can be reported as exact facts, but remain blocking initialization consequences, never successful row classifications or permission to discard state. + ## Ordinary Account ownership Ordinary character request/response Account identities use canonical lowercase non-nil Account UUIDs under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) and the [Account identity contract](../account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity). Entity persists this owner in the existing `characters.account_uuid` column. Numeric `characters.account_id` is retained source-row evidence only, never a public selector or response identity; numeric wire fallback and inferred UUID mappings are not supported. 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 62618e3675..b1dd3300f7 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -33,6 +33,33 @@ The explicitly enabled local demo owner-authentication client makes at most thre - Standard, production, and test Flyway profiles use PostgreSQL `transactional-lock=false` for V1004's concurrent index builds. Entity V1003–V1010 follows unchanged develop Saga V1000–V1002 under the default combined migration locations. Current storage, fresh packaged legacy player-flow, and actual-parent upgrade qualification and its local infrastructure limits are recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). - Actual authenticated owner provenance and the real Game Session caller/controller/execution replacement remain incomplete. Test-created `OWNER_RESOLVED` rows establish bounded storage isolation only; legacy names, numeric IDs, `shared-live`, `instance:`, and runtime pointers never fill missing canonical owner evidence. Runtime quarantine guards, cleanup holds, and condition-expiry retention belong to the later runtime boundary. +## Owner-local runtime-family catalog + +The Entity-local catalog is a schema/classification source prerequisite, not the ADR 0137 FRESH manifest or a replacement validation result. [V1025](../../../../services/entity-management-service/src/main/resources/db/migration/V1025__entity_owner_runtime_family_catalog.sql) adds explicit owner metadata, durable positive catalog epochs and immutable request snapshots without changing any existing payload, migration, history, retention guard or allocator position. Its closed value, authenticated read and immediate consumer are specified in [API Contracts](./api-contracts.md#owner-local-runtime-family-catalog-read); focused source/proof status stays in the [Entity tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#entity-owner-local-runtime-family-catalog-prerequisite). + +The census comes from actual PostgreSQL `pg_catalog` in the configured Entity schema, not a Java expected-table list, a name-prefix rule or runtime row absence. Every installed ordinary/partitioned/foreign table needs one explicit base disposition, including the shared Saga tables, actual configured Flyway history and all three catalog tables. Mixed components have additional explicit declarations. The current ordered source stream has 56 Entity tables before this additive migration; Saga, history and new infrastructure are additional installed census members. No historical table/column removal or rename is inferred, and logical `character` maps only to physical/wire `characters`; illustrative `entity_tick_state` is not an installed table. + +The seal binds exact family metadata and sorted definition hashes for tables, columns/defaults, constraints/validation, indexes, triggers, policies, rules, routines, sequences, views, types and installed migrations. Definition hashes exclude payload rows, OIDs, statistics, sequence positions and installation timestamps. The first durable epoch is sealed during V1025 against the actual installation; it is not a claim to repair a previously drifted database or certify uninspected pre-installation definitions. Missing declared tables/components or unknown tables refuse even that initial installation. Thereafter any added, removed, renamed, changed or unclassified table/column/routine/migration/classification changes the census or refuses it and invalidates the existing seal. Neither new requests nor retries can resample under an unchanged epoch. A subsequent owner-controlled forward installation must explicitly retain a new monotonic epoch; there is no catalog-mutation RPC. + +Flyway's built-in `${flyway:table}` placeholder binds the actual configured history identifier, including custom fixture/deployment names; there is no hardcoded deployment-history fallback. All other installed migration facts bind actual script, version, type, checksum and success. V1025's own successful history row is written after its migration transaction, so its seal contains an explicit `catalog-installation:1025` script marker instead of pretending to include that future row's checksum/timing. Every read and snapshot insert separately requires the successful exact V1025 script row. This marker/installed-row boundary is not full attestation of V1025's post-transaction checksum; normal Flyway checksum validation remains required. Entity's combined Entity/Saga locations and PostgreSQL `transactional-lock=false` remain unchanged, as does V1004's `executeInTransaction=false` concurrent-index configuration. Only PostgreSQL census/functions/triggers/seed are bracketed out of jOOQ DDL simulation; ordinary catalog table/column DDL remains visible to generation. + +The explicit metadata preserves these distinct consequences: + +| Physical family | Catalog classification and initialization consequence | +| --- | --- | +| `characters`, `character_friend` | Target S1 remains provisional pending complete namespace/isolation proof. `characters.body_layout_key` and template-dependent authored core remain S2. Embedded private numeric association, quarantine and original creation/descriptor carriers are separate retained provenance, not cloneable authority. | +| `inventory`, `character_equipment` | Conservative S2; neither tenant-wide counts nor an echoed mapping identifier proves namespace membership, approved mapping or application. | +| `actor_resource_states`, `actor_active_conditions` | Conditional S1/S2, explicitly `BLOCKING_NAMESPACE_REMAP`: current namespace, frozen-source and owner-applied remap proof is unavailable. Expiry does not make conditions disposable. | +| `container_instances`, `item_instances`, `item_stacks` | Conditional S1/S2/S3 only by complete holder/containment closure and template validity. Current row-level closure proof is unsupported and blocking; no table-wide S3 classification is allowed. | +| `room_ground_inventory` | Explicit ground-only S3. This classification alone provides no cleanup acknowledgement or target materialization. | +| Both initial runtime-projection tables | Explicit S3 projection with retained immutable assignment/creation and nonreuse lineage; existing guards remain in force. No backfill, replacement or private FRESH qualification follows. | +| `npcs` | Mixed and `UNRESOLVED`/blocking. Explicit authored field components are source; `last_defeated_at` is a distinct unresolved runtime-like component without a namespace/instance partition. The whole table is never hidden in source-only. | +| `item_visible_ref_counters` | Allocator/nonreuse evidence with unresolved S-class and a blocking consequence, not disposable runtime payload. The separate shared runtime entity sequence remains nonreuse evidence, captured as a sequence definition without consuming or resetting it. | +| Authored items, recipes/ingredients, slot/body-layout definitions | Versioned source only. Selected-empty authored providers retain their explicit EMPTY-only source role; their ledgers, numeric reservations, associations and receipts are separate control/provenance. None proves empty runtime state or arbitrary nonempty source intake. | +| Identity/enrollment, assignment, creation, discovery/roster, retention, projection lineage, replay, audit, Saga/control, configured history and catalog infrastructure | Explicit purpose-specific non-cloned roles in the migration metadata, not a catch-all S3 family. Retention, retries, holds, original receipt bytes and authority exclusions remain owned by their existing contracts. | + +Snapshot capture and independent committed readback bind the complete exact census/epoch and original request, never actor/resource/condition counts, target emptiness, mapping application or a source snapshot fence. `UNRESOLVED` and conditional entries are valid catalog facts but blocking initialization consequences. No consumer may infer a complete owner set, required-owner enrollment, FRESH readiness, currentness through another owner's later commit, source cloning, cleanup/expiry/retirement, default registration, admission, activation, reset, seeded/snapshot support or a second pointer authority. The catalog's immutable evidence remains retained until a separately qualified ADR 0163 owner-local policy exists; this slice introduces neither disposal permission nor an indefinite-retention policy. + ## Architecture and Design Notes - Uses the service-owned PostgreSQL schema and the platform `jOOQ + Flyway` persistence direction. Flyway owns schema evolution and generated jOOQ types are the default SQL access path; the narrow PostgreSQL-specific plain-SQL escape hatch requires focused proof and does not create a parallel ORM authority. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index d1252c4713..21fd29d23a 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -84,6 +84,14 @@ The Account client uses a 30-second deadline for this composed read; the nested ### Initial `FRESH` playtest lifecycle source preparation +Game Session may manually consume the [Social & Groups owner-local runtime-family catalog](../social-groups-service/api-contracts.md#owner-local-runtime-family-catalog-read) through its exact same-namespace peer-qualified client with finite request/response and deadline bounds. This is source evidence only; it does not establish row-level classification, initialized target state, owner enrollment, FRESH readiness or protection through a later Game Session commit. Social’s blocking dispositions and unimplemented contracts remain outstanding. + +The manually composed, unregistered `WorldRuntimeFamilyCatalogClient` consumes the [World-owned runtime-family catalog read](../world-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). It authenticates the exact same-namespace World server, preserves the complete typed catalog bytes/digest, durable World epoch, snapshot identity and original read correlation, and refuses malformed, incomplete, stale-catalog, oversized or unavailable source evidence. The finite deadline and wire/source bounds are defined at that World contract owner. It runs outside ambient SQL and supplies only an as-of World-local classification input. It does not invent a complete owner set, wire evidence into FRESH preparation, mutate catalog/pointer authority, produce a FRESH manifest or protect a later Game Session commit. The whole-FRESH batch and focused proof status remain in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#world-owner-local-runtime-family-catalog-prerequisite). + +The separate manually composed, unregistered `EntityRuntimeFamilyCatalogClient` consumes the [Entity-owned local catalog read](../entity-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). It authenticates the exact same-namespace Entity server, runs outside ambient SQL, and preserves the original request, immutable owner snapshot, exact catalog bytes/digests and Entity epoch under that owner's finite bounds/deadline. Conditional and unresolved Entity families remain blocking facts, not qualified resources/conditions, holder closure, mapping application, target emptiness or FRESH readiness. This evidence-only client is not wired into preparation, namespace/current-pointer authority, allocation or a later Game Session commit; its unrun source/proof status belongs to the [Entity tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#entity-owner-local-runtime-family-catalog-prerequisite). + +Game Session has a manually composed, unregistered Automation runtime-family catalog client that requires file-backed mTLS, pins the exact same-namespace Automation peer, applies finite size/deadline bounds, and validates complete request/snapshot/catalog evidence. Its [Automation API owner contract](../automation-scripting-service/api-contracts.md#owner-local-runtime-family-catalog-read) and [classification/retention owner contract](../automation-scripting-service/runtime-and-data.md#owner-local-runtime-family-catalog) remain authoritative. A successful source read does not resolve blocking families or non-SQL gaps, enroll Automation, establish FRESH completeness/materialization, authorize an actor, or enable runtime admission, CLOSED aggregation or activation; unavailable evidence is never empty-source or initialized-state proof. + [ADR 0137](../../decisions/adr-0137-isolated-playtest-state-modes-and-reset.md) owns playtest initialization modes and isolated lifecycle identity; [ADR 0138](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) owns explicit expiry and grant consequences. The local, unregistered `GameSessionInitialPlaytestLifecycleRepository.prepare` boundary supports only an initial `FRESH` preparation. Its exact request binds a stable `requestId`, `targetNamespace`, `tenantId`, `worldSlug`, `realmSlug`, and explicit future `forkExpiresAt`, plus `sourceCatalogRealmId`, `sourceCatalogRequestId`, `sourceCatalogRevision` fixed at `1`, `sourceIntakeOperationId`, `canonicalVersionId`, `publishedReleaseBundleRef`, and `publishedReleaseBundleDigest`. Game Session locks and validates the retained canonical public-production catalog and its complete published policy evidence against the same tenant/world, distinct target realm, source-intake operation, canonical version, and published release bundle; fixture-only source records are excluded. The target must also be an exact visible, non-public, `ISOLATED` realm policy in that complete immutable Human-published policy set. The retained preparation binds its policy identity, canonical bytes, digest and source revision; a public build or catalog alone cannot authorize an arbitrary private target. A new request allocates a fresh non-nil `playtestLifecycleId` and `playableStateNamespaceId` internally and fixes the initial `playtestStateGeneration` at `1`; none is supplied by the request. The canonical original-request preimage and digest are retained: an exact `requestId` retry returns that original allocation, while changed request content conflicts rather than reallocating or extending expiry. The explicit `forkExpiresAt` is stored with the preparation and checked against the database clock for a new allocation. The preparation remains `PREPARING`; an exact lifecycle read returns `INCOMPLETE` before expiry or `EXPIRED` at/after expiry, and every returned snapshot has `admissionAllowed=false`. The internal `GameSessionCurrentPrivatePlaytestRepository` selects one preparation by explicit expected head revision and expected current lifecycle. A new selection retains an immutable request receipt and advances the scoped head once; historical exact replay returns the original selection rather than choosing a newer preparation. Both selection and current reads qualify the exact retained preparation/private policy; this head is not a player-visible catalog or admission pointer. diff --git a/design/architecture/microservices/social-groups-service/api-contracts.md b/design/architecture/microservices/social-groups-service/api-contracts.md index d4b5420c85..5df0dab3e0 100644 --- a/design/architecture/microservices/social-groups-service/api-contracts.md +++ b/design/architecture/microservices/social-groups-service/api-contracts.md @@ -81,6 +81,15 @@ curl -X POST http://localhost:8080/voice/token \ - `AddFriend` – adds a friend relationship at the game or account level - `ListFriendPresence` – returns the bounded account-scoped projection defined by the [Friend Presence Privacy Contract](#friend-presence-privacy-contract). Social & Groups retains the local transport consequence: raw presence is obtained from Game Session and profile policy through bounded internal bulk reads; the current endpoint remains non-pageable as noted in implementation status. - `SendMail` – stores a Social-owned mail envelope and delivery/history state; item or currency attachments use Entity-owned transfer/escrow references and are not Social value +- `ReadSocialRuntimeFamilyCatalog` – a separate internal source-read contract for one exact, same-namespace `game-session-service` workload identity. It is manually composed only, carries one bounded complete request/evidence frame, and records immutable request-bound source bytes on first read; it is not a player API, owner registry, row inventory, FRESH manifest, initialized-target assertion, or admission result. The source and its implementation limits are defined in [Social runtime/data](./runtime-and-data.md#owner-local-runtime-family-catalog); the proto is [social_runtime_family_catalog_read.proto](../../../../protos/social-groups/v1/social_runtime_family_catalog_read.proto). + +### Owner-local runtime-family catalog read + +The exact closed values and byte framing are defined by [SocialRuntimeFamilyCatalog](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalog.java) and its [purpose-specific codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogCodec.java). The request binds a non-nil read UUID and the configured workload namespace; the response binds the unchanged request, owner-allocated snapshot UUID, fixed Social owner, positive epoch, exact catalog bytes/digest and complete evidence digest. The request bound is 1 KiB, the catalog bound is 2 MiB and the complete response bound is 2 MiB plus 4 KiB; the client applies a five-second deadline. Missing, duplicate, unknown, malformed, contradictory, changed-correlation, trailing or oversized carriers refuse without partial or empty success. + +The receiver authenticates the exact same-namespace Game Session certificate-derived workload before decoding or SQL and rejects propagated caller/role/internal-service context and ambient SQL or transaction synchronization. The client independently qualifies the exact same-namespace Social server. Missing identity is `UNAUTHENTICATED`, wrong workload/namespace/context is `PERMISSION_DENIED`, malformed input is `INVALID_ARGUMENT`, and invalidated catalog evidence is `FAILED_PRECONDITION`. Storage/deadlock failures retain their bounded `UNAVAILABLE`/`ABORTED`/`INTERNAL` classification without disclosing private SQL. Capture may commit its immutable snapshot before later readback or response failure; retry preserves the original request identity and exact retained evidence. + +The `ReadSocialRuntimeFamilyCatalog` adapter and Game Session client are currently source-only/manual: the Social handler is not registered with the application's gRPC server, and neither side is wired into a player request path. The client-side mTLS fixture and controlled-peer/storage tests do not establish a reachable deployed producer or a completed owner handoff. ### Relationship, Group, and Value Authority diff --git a/design/architecture/microservices/social-groups-service/runtime-and-data.md b/design/architecture/microservices/social-groups-service/runtime-and-data.md index 5fcb2ebb5d..5c41d2e5dc 100644 --- a/design/architecture/microservices/social-groups-service/runtime-and-data.md +++ b/design/architecture/microservices/social-groups-service/runtime-and-data.md @@ -55,6 +55,18 @@ The current live moderation seam is the synchronous `EvaluateModerationPolicy` r - Target `chat_restriction` and `chat_restriction_revision` tables store owner-local `chat_mute`/`chat_ban` state and immutable revisions. - **Target state:** Social owns durable player faction reputation/standing under the stable playable-state namespace. Automation and Game Logic consume that owner-read contract to evaluate NPC behavior; owning behavior evaluation or local faction behavior definitions does not make Automation the authority for player standing truth. +## Owner-Local Runtime-Family Catalog + +The additive V1004 owner-local catalog is schema-derived source evidence. It assigns an explicit Social role, current disposition, and applicable target owner to every installed Social, Saga, and actual configured Flyway-history table. Component entries identify selected Account-identity carriers and the chat effect replay key; the complete catalog also binds current PostgreSQL table, column, constraint, index, trigger, policy, rule, routine, sequence-definition, view, type, and installed-migration facts. Definition digests do not contain row contents, counts, sequence positions, OIDs, statistics, or installation times. The known non-SQL contract gaps remain explicit in the catalog. + +An unclassified table refuses catalog installation even when it has no rows. After installation, changed, removed, renamed, or newly added schema objects, classifications, or prior migration facts invalidate the stored epoch and refuse both retained and new reads. No runtime path resamples drift or accepts an epoch; future schema/classification evolution requires an explicit owning forward migration. The immutable classification, epoch, and snapshot records preserve the installed source and exact request-bound evidence. + +Flyway 13.12's built-in `${flyway:table}` placeholder binds the configured history table, including a custom name; the catalog never assumes a public-schema history name. Flyway writes V1004's successful history row after the migration transaction, so the seal uses a stable `catalog-installation:1004` marker in place of that not-yet-existing row and the separate installed check requires the exact successful V1004 script. The marker does not attest to the post-transaction checksum; normal Flyway validation remains required. + +The separate `ReadSocialRuntimeFamilyCatalog` contract in [API Contracts](./api-contracts.md#owner-local-runtime-family-catalog-read) retains one complete request-bound evidence frame and refuses drift or storage failure. The handler and Game Session mTLS client are manual source only; the Social handler is not registered with the application's gRPC server, and neither side is connected to player/API flows. This catalog is not row-level evidence, owner enrollment, target initialization, a global FRESH manifest, runtime authority, or admission; its explicit blockers—including tenant-bound account friendships, Social guild value storage, unresolved Saga adoption, and missing communication, safety, and standing contracts—do not qualify for readiness. + +The capture stores the canonical request bytes and digest, unique snapshot identity, epoch/digest, exact complete evidence frame, and evidence digest. Capture commits independently from the subsequent exact committed readback. Repeating the same request identity returns that same retained evidence; a new request identity receives a distinct snapshot over the same current catalog. The request namespace must equal the authenticated fixed Game Session workload namespace. This operation changes only immutable source-evidence metadata and does not read, create, seed, or modify gameplay rows. + ## Redis Role and Prefixes - **Coordination Redis** diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 3875b44120..7bc7b4571c 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -203,6 +203,20 @@ These are deliberately abbreviated, non-admissible fragments. The World inventor } ``` +## Owner-local Runtime-family Catalog Read + +`WorldRuntimeFamilyCatalogReadService.ReadWorldRuntimeFamilyCatalog` is a manually composed, unregistered internal source operation defined by [world_runtime_family_catalog_read.proto](../../../../protos/world-management/v1/world_runtime_family_catalog_read.proto), the shared [WorldRuntimeFamilyCatalog](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java) value and its [closed codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java). World authenticates the exact `spiffe://firemud/ns//sa/game-session-service` peer and rejects propagated account/role or internal-service context before decoding the closed request or accessing SQL. Missing identity is `UNAUTHENTICATED`; a wrong service, peer namespace or requested namespace is `PERMISSION_DENIED`. The owner and consumer reject ambient SQL transactions and transaction synchronization. Composition must supply actual workload mTLS and the peer-identity interceptor; binding the Java service does not configure or register a server, bypass bearer middleware, or provision trust. + +The request contains one canonical non-nil `readRequestId` and the exact configured workload `targetNamespace`. This namespace selects the workload environment, not a tenant or a playable-state namespace. There are no numeric identifiers, actor assertions, owner-set selectors, target runtime selectors, credentials or mutation/action fields. Each protobuf carrier has exactly one repeated byte value so missing and duplicate values are observable; unknown protobuf fields refuse. The closed request frame is big-endian `WCR1` (four ASCII bytes), the UUID as two 64-bit words, then a 32-bit length and ASCII namespace. The complete serialized request is limited to 1,024 bytes, with namespace length at most 63 bytes. + +The complete response frame is big-endian `WCE1`, a length-prefixed unchanged request frame, one World-allocated non-nil snapshot UUID, a length-prefixed `sha256:` lowercase hex schema/catalog digest, and the length-prefixed complete catalog bytes. The digest is SHA-256 of the exact catalog bytes, not a digest of parsed or recanonicalized data. The catalog bytes are the installed PostgreSQL JSONB text encoding, strictly decoded as UTF-8 under the closed `world-runtime-family-catalog/v1` schema. They contain the fixed World owner identity, positive decimal-string catalog epoch, complete ordered family classifications and complete ordered schema-fact identities/definition digests. The shared value retains those original bytes unchanged. `Evidence.digest()` covers the complete exact response frame, including original request and snapshot identity. Missing, duplicate, unsupported, inconsistent, noncanonical binary, trailing, truncated or oversized evidence refuses; there is no partial, empty, paginated, compatibility or numeric-fallback success. + +Catalog bytes are limited to 2,097,152 bytes, 512 family entries and 16,384 schema facts. The complete serialized response is limited to 2,101,248 bytes, including its protobuf framing. A manually composed receiver must bound incoming requests; the matching Game Session client applies the exact request/response limits and a five-second deadline and verifies the exact same-namespace World server certificate before accepting evidence. The owner returns `INVALID_ARGUMENT` for malformed input, `FAILED_PRECONDITION` for invalidated or inconsistent catalog source, and a storage refusal rather than empty evidence on dependency failure. A failed response/readback can leave an already committed immutable source snapshot; retry uses the original read identity and never assumes that an error means no record committed. + +The [World catalog persistence and classification contract](./runtime-and-data.md#owner-local-runtime-family-catalog) owns the census, epoch seal, retention and family meanings. The producer first validates the actual installed census against its sealed epoch, retains or exactly replays the request-bound snapshot in a short World transaction, and independently reads back the committed exact result. A changed request or current schema/catalog conflicts; retries cannot silently re-sample under the same epoch or substitute a newer snapshot for an old request. + +This is **as-of World-owner catalog evidence only**. It selects ADR 0137's permitted owner-scoped epoch representation at this one owner boundary, not a complete set of owner epochs. It is not a global registry, enrollment decision, required-owner-set authority, owner FRESH manifest, row-count/empty-state attestation, actor authorization, source-currentness protection through another owner's later commit, runtime materialization, admission-pointer mutation, activation or admission. World remains the future global inventory/coordinator owner; this method cannot infer that global set from its tables, a caller list, an empty registry or service names. Source/proof status and remaining whole-FRESH gaps belong to [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#world-owner-local-runtime-family-catalog-prerequisite). + ## LOOK Snapshot Contract `GetRoomSnapshot` is the canonical endpoint feeding Game Logic's `ResolveLook`. The current and target fence contracts are intentionally separate. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 49d8a48db7..2feeb5c6e5 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -166,6 +166,32 @@ World persists the initial-bind hold separately and includes it in the lifecycle Redis caches hot rooms for active sessions to speed up lookups. Target Class A cached rooms use keys `room:::` and must never be keyed by template identifiers because runtime rows may diverge from template state. +## Owner-local Runtime-family Catalog + +The manually composed World runtime-family catalog persists owner-local source evidence under forward [V1046](../../../../services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql). It adds only `world_runtime_family_classification`, `world_runtime_family_catalog_epoch` and `world_runtime_family_catalog_snapshot` plus their source functions/guards. Existing World data, authority, lifecycle rows and earlier migrations are not rewritten. Its authenticated read and exact value/transport contract are owned by [World API Contracts](./api-contracts.md#owner-local-runtime-family-catalog-read); implementation and focused proof status are tracked in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#world-owner-local-runtime-family-catalog-prerequisite). + +The migration installs explicit owner metadata for every current World/Saga/history/catalog table, plus the distinct `region_instance.weather` component. `world_runtime_family_catalog_bytes` actually reads the installed service schema through PostgreSQL catalogs and the owning Flyway history. Each table must have a declared table-level disposition, each declared table must exist, and each declared component must resolve to an installed non-dropped column. It also enumerates columns with type/default/nullability/identity/generated/collation facts, constraints, indexes, triggers, routines, sequences, views/rules, types and policies with definition digests. Routine and trigger facts include the installed owner guards, including this catalog's own functions. Migration evidence binds installed rank, version, script, checksum and success, excluding installation user/time. Sequence positions, OIDs, statistics and gameplay row contents are not schema facts. The resulting ordered census and classifications are sealed together as exact bytes with a positive durable epoch, initially `1`, and an actual-byte SHA-256 digest; no Java constructor or empty payload query declares the installed inventory complete. + +Flyway records V1046's own history row after its migration transaction. The initial seal therefore includes a stable `catalog-installation:1046` marker and the actual installed object definitions, rather than the not-yet-existing self-history checksum. Flyway's built-in `flyway:table` placeholder binds the actual configured history relation into the census, its explicit classification and the installed-row check; the service's default `public` schema and explicitly configured history names do not require a separate hardcoded table. The read owner separately requires V1046's successful exact script row through that installed owner function. Every other installed migration row participates in the seal; adding a later migration, changing a prior migration fact, or adding/removing/renaming/changing a schema object or classification invalidates this epoch. A new table with zero rows is still an unclassified family and refuses. Subsequent catalog/schema evolution needs an explicit owning forward migration to install its supported classifications and next exact epoch, including updating the installation-marker/history boundary for that migration. There is no runtime resampling, epoch-advance endpoint or automatic acceptance of a changed census. This seal is owner-local installed-schema evidence, not an external deployment attestation or a substitute for Flyway validation. + +Epoch rows, classification rows and request snapshots reject UPDATE, DELETE and TRUNCATE. A new epoch insertion must be the next positive epoch and bind the exact current census bytes; a source snapshot insertion must bind the current epoch/digest and unchanged installed census. The request UUID is unique across namespaces. A retained snapshot binds exact request bytes/digest, workload namespace, World snapshot UUID, epoch/catalog digest and complete response bytes/digest. Exact retry and independent committed readback compare all of them; changed requests, missing snapshots and old snapshots under a changed catalog refuse rather than returning absence or updated evidence. Evidence is retained without a new deletion/expiry policy or cleanup job. A caller-visible refusal after capture commit does not erase retained evidence. These source records do not mutate a realm, runtime, canonical pointer or player state. + +Current catalog dispositions are intentionally not FRESH outcomes: + +| Current family | Role/class | Local FRESH consequence | +| --- | --- | --- | +| `world_instance` | Lifecycle, `S3`, not copied payload | Requires actual owner lifecycle creation/proof; catalog presence creates no instance. | +| `region_instance`, `zone_instance`, `room_instance`, `room_instance_exit` | Runtime payload, `S3` | Require the actual selected-build minimum topology and its owner materialization/readback. | +| `world_event` | Runtime payload, `S3` | Requires explicit owner event applicability/initialization evidence; no schedules or empty-state proof are inferred. | +| `region_instance.weather` | Runtime payload component, `S3` | Explicitly unsupported while the Weather selector/effect contract is unresolved; no initialized weather is invented. | +| `character_location` | Runtime payload, `S3` | Guarded placement is not initialized by a catalog read; actor, placement and current-location prerequisites remain separate. | +| `instance` | Explicit legacy `S3` exclusion | `LEGACY_EXCLUDED` means the existing zone-scoped legacy family, not private runtime materialization or parent lifecycle cleanup authority. | +| `world_canonical_instance_association`, `world_canonical_instance_preparation`, `world_canonical_instance_topology_identity`, `world_canonical_preparation_start_location`, `world_canonical_instance_execution`, `world_canonical_initial_player_location_operation` | Provenance, `NOT_PAYLOAD` | Canonical owner materialization/replay/initial-placement evidence is retained; it is neither copied gameplay payload nor a FRESH manifest. | + +The remaining current tables are explicitly classified individually by the owning migration as authored/source evidence, control/guard records, audit/replay evidence or catalog infrastructure, with `NOT_PAYLOAD` and the corresponding closed `SOURCE_ONLY`, `CONTROL_ONLY`, `AUDIT_ONLY` or `CATALOG_ONLY` disposition. This is not a blanket prefix exclusion: the live census must still match every exact declared table. Classification never authorizes cloning source/control/audit/provenance records or dropping retained replay evidence. Absent `npc_location`, generalized occupancy, population schedules, generation-run provenance and future ambient persistence are not invented as installed rows or declared empty. A selected build requiring unsupported/unimplemented state still cannot qualify FRESH; a catalog contains no per-build materialization or applicability result. + +The existing canonical World materializer remains public-production `SHARED`, generation-free and original-`StartSession`-specific. This source addition does not convert it to private FRESH. The owner-local schema epoch supplies neither global enrollment/required-owner-set completeness nor the later complete owner-manifest aggregate, protected private operation, private materialization, canonical CLOSED result or admission authority. + ## Replacement-Instance State Classification The exhaustive S1/S2/S3 rules, unknown-state fail-closed behavior, namespace modes, owner mapping/application evidence, and freshness-bound preflight are owned by [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). World Management publishes only this local family inventory and current implementation caveat; it must not infer a class for an unregistered family. diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index de9d637484..f38e04e627 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -8,12 +8,20 @@ This is a non-normative implementation tracker for automation and scheduler runt Adjudicated retention identity gap: `npc_memory` is live but latent and remains unclassified for replacement. Its replacement admission is blocked pending owner classification, mapping, and proof; see the [Automation runtime/data owner contract](../../architecture/microservices/automation-scripting-service/runtime-and-data.md#runtime-data-model). -The bounded implementation slices recorded here are complete at their stated boundaries. This tracker is the permanent reader-facing implementation record for the live automation ingress, scheduling, execution, handoff, readiness, and runtime/operator projection contracts. +The bounded runtime implementation slices recorded here retain their stated boundaries; source-only prerequisites below are not qualified or complete runtime capabilities. This tracker is the permanent reader-facing implementation record for the live automation ingress, scheduling, execution, handoff, readiness, and runtime/operator projection contracts. The bounded Automation handoff path has focused unit-level transaction/RPC-boundary proof, including producer-shaped handoff classifications and post-evaluation diagnostic behavior in [ScriptWorkItemExecutionServiceImplTest](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java) and [ScriptGameplayCommandHandoffServiceImplTest](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java). This does not establish live PostgreSQL crash/concurrency behavior, real Spring proxy rollback-only behavior, or cross-service authenticated receiver-gate behavior. The durable evaluated descriptor, complete child ledger, and reconciliation owner required for stage-aware recovery remain unimplemented; normative mechanics and diagnostic-marker behavior are owned by the [Automation runtime/data contract](../../architecture/microservices/automation-scripting-service/runtime-and-data.md#implementation-status). The exact-base publication-provenance candidates in this stack are not yet live. V3.1 adds nullable provenance columns to retained Automation owner records and a positive patch-to-base binding table without synthesizing bases for legacy rows. The Automation candidate retains and reads back the admitted positive `baseVersionId` across digests, readiness/work-item projections, timer audits, and the local command handoff; its tenant-wide full-version digest still includes all tenant scripts rather than release-specific content. Focused proof covers exact stored-base validation, fail-closed scheduling, and unavailable publication links when the base is missing. PostgreSQL retained-data behavior for V3.1 remains unexecuted absent targeted completed CI proof; unknown-base enrichment remains fail-closed. +### Owner-local runtime-family catalog source prerequisite + +The unregistered Automation catalog source comprises [V1004](../../../services/automation-scripting-service/src/main/resources/db/migration/V1004__automation_owner_runtime_family_catalog.sql), the [capture/readback repository](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogRepository.java), [authenticated read handler](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java), [Common value](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java), [closed codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogCodec.java), [proto](../../../protos/automation-scripting/v1/automation_runtime_family_catalog_read.proto) and [Game Session client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClient.java). The database-derived catalog, durable epoch and immutable request snapshot retain actual combined Automation/Saga schema and configured Flyway-history facts. Normative classification/retention belongs to [Automation runtime/data](../../architecture/microservices/automation-scripting-service/runtime-and-data.md#owner-local-runtime-family-catalog); wire and consumer constraints belong to [Automation API contracts](../../architecture/microservices/automation-scripting-service/api-contracts.md#owner-local-runtime-family-catalog-read). + +Receiving proof243/244 passes six Common value/codec cases, four workload-guard cases, thirteen actual PostgreSQL cases and five physical client mTLS cases, with zero failures, errors or skips. Proof242 passes owning generation/formatting after correcting H2 simulation of PostgreSQL-only consequence constraints without weakening their physical guards. Proof245 passes 76 cases across all six affected existing Automation migration-fixture suites, affected main/unit/integration static analysis, formatting and documentation checks. Latest-frontier fixtures use the actual combined Saga/service migrations and explicit service schema; historical migration targets and positive assertions remain. The [catalog SQL suite](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java) and [mTLS suite](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClientMtlsTest.java) execute separately with controlled upstream identities, source bytes and local PKI. They do not prove a coupled deployed SQL-to-mTLS boundary, genuine issuer/custody, fresh images or private initialization. Game Session main SpotBugs remains unqualified under the separate JVM investigation. + +NPC memory/formations, admitted work/plugin state, stable schedule namespace/mapping, the Automation/Social faction-standing ownership conflict, and non-SQL Redis/charge/accounting/reset sources remain explicit blockers at the owning contract. This source does not enroll Automation, establish a complete owner set or FRESH manifest, copy runtime state, run initialization, authorize an actor, or aggregate CLOSED. Capability ratings are unchanged. Private first admission, default registration, activation, Unit1B, reset, seeded/snapshot, issuer/custody and PKI holds remain. + ### Game Session receiver candidate The Game Session receiver candidate retains lower-level helper behavior for admitting the exact local patch/base/pin tuple, persisting the admitted base on commands through an additive migration, comparing it on retries, and using it for command-status publication links. Its authenticated `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` receiving RPCs are currently gated before live mutation because the separate Automation admission-epoch receiver fence is absent; both fail closed with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable`. The gate and its successor activation requirement are recorded in the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). Focused lower-level owner tests cover exact tuple and missing/mismatched-base rejection, but do not prove successful end-to-end receiver admission. Historical command rows and pre-upgrade pins without a proven base remain fail-closed; live database migration, cross-service deployment, and the distinct-instance remote target tuple remain open as recorded below. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 50441ff57c..331c7403f6 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -6,6 +6,16 @@ This is a non-normative implementation tracker for gameplay rules, entities, and ## Current Status +### Entity owner-local runtime-family catalog prerequisite + +Working source adds the bounded Entity-local catalog prerequisite within the existing private FRESH batch: forward [V1025](../../../services/entity-management-service/src/main/resources/db/migration/V1025__entity_owner_runtime_family_catalog.sql), [capture and independent readback repository](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogRepository.java), [authenticated read handler](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java), [immutable Common value](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java), [closed codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogCodec.java), [purpose-specific proto](../../../protos/entity-management/v1/entity_runtime_family_catalog_read.proto) and [Game Session consumer](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClient.java). Normative semantics belong only to [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md#owner-local-runtime-family-catalog) and [Entity API Contracts](../../architecture/microservices/entity-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). These components remain manually composed/unregistered, with no FRESH coordinator or pointer integration and no capability-rating upgrade. + +Focused executable sources are added for [Common value/codec/digest/bounds](../../../services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogTest.java), [workload-before-decode/SQL and positive handler behavior](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcServiceTest.java), [actual combined-migration PostgreSQL census, conditional/unresolved facts, populated retained source, epoch/readback/reconstruction, concurrent exact replay, history names and drift](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java), and [peer-qualified Game Session mTLS identity, correlation, refusals and actual deadline](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClientMtlsTest.java). Existing Entity migration-frontier fixture assertions advance to V1025 without removing their positive cases or changing old migrations. The new PostgreSQL fixture retains the real Entity Testcontainers/Flyway pattern, combined Saga locations, custom history and V1004's nontransactional concurrent-index behavior; it has no unavailable-Docker skip or substitute database. + +Receiving proof243/244 passes seven Common value/codec cases, four workload-guard cases, twelve actual PostgreSQL cases and five physical client mTLS cases, with zero failures, errors or skips. Proof242 passes owning generation/formatting. Proof245 passes all 53 cases across the four affected existing Entity migration-fixture suites, affected main/unit/integration static analysis, formatting and documentation checks. Game Session main SpotBugs remains unqualified under the separate JVM investigation. SQL/RPC peer contexts and retained upstream identities are controlled; separate physical mTLS source uses controlled local PKI and catalog bytes, not a coupled SQL-to-mTLS owner chain or genuine issuer/custody evidence. Reconstruction is not process-death proof. The V1025 installed-row marker has the explicit post-transaction checksum limit documented at its owner. + +Remaining semantic obligations include namespace qualification for provisional character/friend and S2 inventory/equipment; resource/condition namespace, frozen-definition and remap proof; complete row-level holder closure; unresolved NPC mixed state and visible-ref allocator S-class; owner manifests/materialization and complete owner-set aggregation into the existing canonical CLOSED owner. No catalog proves empty target state, approved/applied remaps, complete FRESH, other-owner commit currentness, registration, actor promotion/backfill, cleanup/retirement, admission/activation, seeded/snapshot/reset, production PKI or Unit1B. Main Gameplay owns integration, consolidated validation, aggregated realm-routing status and any publication. + ### Protected preseeded assignment ingress Entity's [protected preseeded assignment](../../architecture/microservices/entity-management-service/api-contracts.md#protected-preseeded-actor-assignment) now has a manually composed, certificate-guarded handler and an immediate Game Session client. They reuse the existing assignment owner and immutable receipt writer. Neither component registers itself or changes the ordinary `PLAY` path. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index cb755924e4..273d463990 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -79,6 +79,7 @@ Focused source proof covers complete Common Security and Social unit suites, nat - Previously recorded focused unit, native application and WebSocket composition evidence covers bounded presence-owner correlation, the earlier tenant-scoped classification, profile-policy projection and player-facing output corrections; its exact run attribution remains in the review records. The current receiving source changes make Game Session presence PLAYER-only while no independent gameplay-grant carrier is available, and add cached-role projection plus ordinary-update demotion. R1423’s receiving preparation, committed as `d12c0ab2e7a7d1d40f62991e3d097bd9090cc2ef`, executed 137 selected Common/Game Session units, including Redis presence, WHO and reconnect cases, plus six actual-Redis cases using the production serializer. Its retained `qualification.log` and `recovery.log` distinguish the original aggregate failure from fixture recovery; these are preparation-time results, not a rerun on the current review head. Its physical cache cases compare retained bytes and TTL through session, game and account reads before field-preserving activity demotion. The initial aggregate fails only new integration-fixture mutable-long analysis; immutable per-case IDs recover all six physical cases and enabled integration static analysis, formatting and documentation. Earlier unit/main-analysis results keep their source attribution; these scoped results do not establish full native-service, production gameplay-grant or admission proof. Snapshot-bound continuation, current relationship/block revalidation and broader authorization/disclosure remain incomplete. [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md), the [authentication owner](../../architecture/system-architecture-authentication.md), and the [Game Session runtime/data owner](../../architecture/microservices/game-session-service/runtime-and-data.md) own the target behavior. - Guild creation/member lifecycle callbacks emit best-effort operational logs after commit, with no committed lifecycle event on rollback. This logging supplies no durable audit or delivery guarantee. Consolidated receiving R1137 passes all 109 Social unit cases and all 15 selected native application cases, including the 12 `GuildServiceImplTest` cases covering all four actions, commit-versus-rollback context and a scoped throwing-appender regression. Enabled affected main/test/integration analysis, formatting and documentation checks pass. This proves the local dispatch boundary and supported service seams, not durable audit, delivery guarantees or current published-head/fresh-image qualification. - Current behavior/proof: `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, mail APIs, friends, guild APIs, presence reads, privacy settings, recipient delivery, and speech normalization are live at bounded service/API seams; focused communication, social, presence, privacy, moderation, and cross-service tests cover those seams. +- The Social owner-local runtime-family source prerequisite adds V1004 schema/history classification and an exact request-bound snapshot repository, a separately defined bounded `ReadSocialRuntimeFamilyCatalog` contract, and a manual Game Session mTLS client. It classifies installed Social/Saga/Flyway-history schema facts and explicit blockers only; it does not inspect row values, enroll an owner, establish target initialization, or produce FRESH readiness. The Social handler is not registered with the application gRPC server, and neither side is wired to a player path. Receiving proof243/244 passes six Common value/codec, four workload-guard, ten actual combined Social/Saga PostgreSQL and four physical Game Session mTLS cases, with zero failures, errors or skips; proof245 passes affected Social/Common static analysis, formatting and documentation checks. SQL and transport execute separately with controlled upstream data and local PKI, without deployed owner-chain, fresh-image or private-initialization proof. Game Session main SpotBugs remains unqualified under the separate JVM investigation. Current behavior and proof limits remain with [Social API Contracts](../../architecture/microservices/social-groups-service/api-contracts.md#grpc-apis) and [Social runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md#owner-local-runtime-family-catalog). - Local gaps linked to [ADR 0147](../../architecture/decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md), [ADR 0148](../../architecture/decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md), [ADR 0149](../../architecture/decisions/adr-0149-communication-type-specific-history-and-retention.md), and [ADR 0150](../../architecture/decisions/adr-0150-closed-observer-views-and-profile-scoped-shout.md) include offline `TELL`, profile-scoped `SHOUT`, richer topology/interception, type-specific history/acknowledgement, entity-owned social value/attachments, closed observer views, cross-pod delivery, first-party recipient presentation, and the canonical gameplay `WHISPER` recipient-scope migration. These ADR links identify gaps; they do not restate target policy. - Presence/privacy drift remains tracked against [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md) and [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). Current `gameplaypresence:*` and `accountrecentpresence:*` Redis shapes, partial-write behavior, reset/readback behavior, storage role, and proof of private-by-failure enforcement for missing, stale, partial, or ambiguous evidence remain implementation/proof gaps. The canonical raw-presence/friend-projection ownership and disclosure rules are in the [Social & Groups Friend Presence Privacy Contract](../../architecture/microservices/social-groups-service/api-contracts.md#friend-presence-privacy-contract); canonical owner/reset details also live in the [Redis reset catalog](../../architecture/system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Current Game Session has no independent gameplay-grant carrier, so the received source defaults presence to `PLAYER`; the focused R1423 receiving proof does not establish production grant qualification. This correction does not complete snapshot-bound continuation, broad activity consumers, private-by-failure enforcement, or broader authorization/disclosure proof. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 11ce916664..6c923c2480 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -23,6 +23,14 @@ These links add decision provenance only; they do not upgrade routing or playabl Current-selection CAS is implemented by [`GameSessionCurrentPrivatePlaytestRepository`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestRepository.java) and forward [V1055](../../../services/game-session-service/src/main/resources/db/migration/V1055__current_private_playtest_preparation.sql), with focused executable proof in [`GameSessionCurrentPrivatePlaytestPostgresIntegrationTest`](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestPostgresIntegrationTest.java). The Account-only read is owned by [`CurrentPrivatePlaytestLifecycleReadGrpcService`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CurrentPrivatePlaytestLifecycleReadGrpcService.java) and its [workload guard](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/CurrentPrivatePlaytestLifecycleReadWorkloadGuard.java), with the bounded transport cases in [`CurrentPrivatePlaytestLifecycleReadGrpcServiceIntegrationTest`](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/CurrentPrivatePlaytestLifecycleReadGrpcServiceIntegrationTest.java). These anchors identify the preceding qualified source boundaries and do not extend their proof limits. +### World owner-local runtime-family catalog prerequisite + +The private FRESH prerequisite batch now has a concrete World-local catalog producer and Game Session consumer in working source: forward [V1046](../../../services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql), [World persistence/readback owner](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogRepository.java), [authenticated World read](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java), [shared exact value](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java), [closed codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java) and [Game Session client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClient.java). The normative census/classification/retention detail stays with [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#owner-local-runtime-family-catalog), and wire/authentication/bounds with [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). This is an actual database-derived World schema/family source and durable epoch/snapshot prerequisite, not a static expected-table list, global runtime registry, complete owner-epoch set or FRESH manifest. + +Receiving proof243/244 passes six World [value/codec cases](../../../services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogTest.java), four [workload-guard cases](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcServiceTest.java), thirteen [actual PostgreSQL cases](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java) and four [physical client mTLS cases](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClientMtlsTest.java), with zero failures, errors or skips. The four-owner receiving batch totals 107 focused cases; proof245 separately passes 129 affected existing Entity/Automation migration-fixture cases and selected owner/Common main-unit-integration static analysis, formatting and documentation checks. Owning generation passes242/243. Earlier retained proof238 reproduces the configured-history refusal corrected before239; it is not a passing aggregate. Proof243 retains its missing Social client-import compilation failure;244 runs the corrected eighteen client cases and reuses unchanged passing codec/guard/SQL results. Exact XML and logs retain those scopes. Game Session main SpotBugs remains unqualified under the separate JVM investigation. PostgreSQL identity/legacy inputs and guard peer contexts are controlled; mTLS uses local test PKI and catalog responses rather than a live database producer. No coupled database-plus-mTLS owner chain, fresh-image/runtime or whole-FRESH proof is claimed. + +Remaining batch obligations are the genuine World-owned global enrollment/required-owner-set source, remaining actual owner catalogs/epochs, complete build/lifecycle/namespace/generation-bound FRESH manifest production and immutable authenticated readback, genuine protected private authorization/runtime/materialization, and complete-set aggregation into the existing canonical CLOSED pointer/audit/outcome owner. Current World canonical materialization is still public `SHARED` and original-`StartSession`-only; no private FRESH relabelling is valid. The existing unregistered [canonical CLOSED owner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java) supplies public initial CLOSED persistence, not the missing private aggregate; the registered legacy routing model described elsewhere remains narrower. No second private pointer authority is added. CLOSED-to-OPEN, private first admission, issuer/custody/PKI qualification, runtime/default registration, operational activation, reset and Unit1B remain held. Capability ratings are unchanged; this source batch does not complete FRESH capability. + ## Capability Status | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | diff --git a/protos/automation-scripting/v1/automation_runtime_family_catalog_read.proto b/protos/automation-scripting/v1/automation_runtime_family_catalog_read.proto new file mode 100644 index 0000000000..48a87f2e5f --- /dev/null +++ b/protos/automation-scripting/v1/automation_runtime_family_catalog_read.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; + +package automation_scripting.v1; + +option java_package = "net.firedevops.firemud.automationscripting.v1"; +option java_multiple_files = true; + +// Manual unregistered source read only. Not owner enrollment, FRESH materialization, +// actor authorization, runtime admission or activation. +service AutomationRuntimeFamilyCatalogReadService { + rpc ReadAutomationRuntimeFamilyCatalog(ReadAutomationRuntimeFamilyCatalogRequest) + returns (ReadAutomationRuntimeFamilyCatalogResponse); +} + +message ReadAutomationRuntimeFamilyCatalogRequest { + // Exactly one closed bounded frame; repeated preserves duplicate-wire refusal. + repeated bytes canonical_request_bytes = 1; +} + +message ReadAutomationRuntimeFamilyCatalogResponse { + // Exactly one complete immutable correlated snapshot; never partial or paginated. + repeated bytes canonical_response_bytes = 1; +} diff --git a/protos/entity-management/v1/entity_runtime_family_catalog_read.proto b/protos/entity-management/v1/entity_runtime_family_catalog_read.proto new file mode 100644 index 0000000000..d633dca38e --- /dev/null +++ b/protos/entity-management/v1/entity_runtime_family_catalog_read.proto @@ -0,0 +1,22 @@ +syntax = "proto3"; + +package entity_management.v1; + +option java_package = "net.firedevops.firemud.entitymanagement.v1"; +option java_multiple_files = true; + +// Manual, unregistered Entity-local schema evidence, not a runtime manifest or admission. +service EntityRuntimeFamilyCatalogReadService { + rpc ReadEntityRuntimeFamilyCatalog(ReadEntityRuntimeFamilyCatalogRequest) + returns (ReadEntityRuntimeFamilyCatalogResponse); +} + +message ReadEntityRuntimeFamilyCatalogRequest { + // Exactly one closed frame; repeated preserves duplicate wire occurrences for refusal. + repeated bytes canonical_request_bytes = 1; +} + +message ReadEntityRuntimeFamilyCatalogResponse { + // Exactly one complete bounded frame. No empty, partial or paginated success. + repeated bytes canonical_response_bytes = 1; +} diff --git a/protos/social-groups/v1/social_runtime_family_catalog_read.proto b/protos/social-groups/v1/social_runtime_family_catalog_read.proto new file mode 100644 index 0000000000..ec21ff2f38 --- /dev/null +++ b/protos/social-groups/v1/social_runtime_family_catalog_read.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; + +package social_groups.v1; + +option java_package = "net.firedevops.firemud.socialgroups.v1"; +option java_multiple_files = true; + +// Manually composed only. As-of Social-local schema/classification evidence, never a FRESH +// manifest, owner registry, row inventory, materialization or admission result. +service SocialRuntimeFamilyCatalogReadService { + rpc ReadSocialRuntimeFamilyCatalog(ReadSocialRuntimeFamilyCatalogRequest) + returns (ReadSocialRuntimeFamilyCatalogResponse); +} + +message ReadSocialRuntimeFamilyCatalogRequest { + // Exactly one value; repeated so duplicate wire values remain observable. + repeated bytes canonical_request_bytes = 1; +} + +message ReadSocialRuntimeFamilyCatalogResponse { + // Exactly one complete closed frame. No partial, empty or paginated success. + repeated bytes canonical_response_bytes = 1; +} diff --git a/protos/world-management/v1/world_runtime_family_catalog_read.proto b/protos/world-management/v1/world_runtime_family_catalog_read.proto new file mode 100644 index 0000000000..878bdaf3fa --- /dev/null +++ b/protos/world-management/v1/world_runtime_family_catalog_read.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Manually composed only. As-of World-local catalog evidence, never a FRESH manifest, +// global owner registry, materialization, actor authorization or admission result. +service WorldRuntimeFamilyCatalogReadService { + rpc ReadWorldRuntimeFamilyCatalog(ReadWorldRuntimeFamilyCatalogRequest) + returns (ReadWorldRuntimeFamilyCatalogResponse); +} + +message ReadWorldRuntimeFamilyCatalogRequest { + // Exactly one value; repeated so duplicate wire values remain observable. + repeated bytes canonical_request_bytes = 1; +} + +message ReadWorldRuntimeFamilyCatalogResponse { + // Exactly one complete closed frame. No partial, empty or paginated success. + repeated bytes canonical_response_bytes = 1; +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java new file mode 100644 index 0000000000..7d900451e3 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java @@ -0,0 +1,121 @@ +package net.firedevops.firemud.automationscripting.runtimecatalog; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Objects; +import net.firedevops.firemud.automationscripting.v1.AutomationRuntimeFamilyCatalogReadServiceGrpc; +import net.firedevops.firemud.automationscripting.v1.ReadAutomationRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.automationscripting.v1.ReadAutomationRuntimeFamilyCatalogResponse; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Manual unregistered producer. Exact Game Session workload authentication precedes decode/SQL. */ +public final class AutomationRuntimeFamilyCatalogReadGrpcService + extends AutomationRuntimeFamilyCatalogReadServiceGrpc + .AutomationRuntimeFamilyCatalogReadServiceImplBase { + private final AutomationRuntimeFamilyCatalogRepository repository; + private final String namespace; + + public AutomationRuntimeFamilyCatalogReadGrpcService( + AutomationRuntimeFamilyCatalogRepository repository, String namespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Fixed workload namespace required"); + this.namespace = namespace; + } + + @Override + public void readAutomationRuntimeFamilyCatalog( + ReadAutomationRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + refuse(observer, Status.UNAUTHENTICATED, "Authenticated workload required"); + return; + } + if (!peer.isService("game-session-service") + || !peer.isInNamespace(namespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + refuse( + observer, + Status.PERMISSION_DENIED, + "Exact same-namespace Game Session workload required without caller context"); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + refuse( + observer, Status.FAILED_PRECONDITION, "Independent Automation owner operation required"); + return; + } + Request request; + try { + request = AutomationRuntimeFamilyCatalogCodec.fromRequest(wire); + } catch (IllegalArgumentException invalid) { + refuse(observer, Status.INVALID_ARGUMENT, "Complete bounded catalog request required"); + return; + } + if (!namespace.equals(request.targetNamespace())) { + refuse( + observer, + Status.PERMISSION_DENIED, + "Request namespace differs from authenticated workload"); + return; + } + ReadAutomationRuntimeFamilyCatalogResponse response; + try { + response = AutomationRuntimeFamilyCatalogCodec.toResponse(request, repository.read(request)); + } catch (AutomationRuntimeFamilyCatalogRepository.CatalogConflictException + | IllegalArgumentException invalid) { + refuse( + observer, + Status.FAILED_PRECONDITION, + "Automation catalog is changed, unsupported or inconsistent"); + return; + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException failure) { + refuse(observer, storageStatus(failure), "Automation catalog storage read failed"); + return; + } catch (org.springframework.transaction.CannotCreateTransactionException unavailable) { + refuse(observer, Status.UNAVAILABLE, "Automation catalog storage unavailable"); + return; + } catch (RuntimeException failure) { + refuse(observer, Status.INTERNAL, "Automation catalog read failed"); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static Status storageStatus(RuntimeException failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql) { + String state = sql.getSQLState(); + if (state == null) continue; + if (state.startsWith("23") || state.startsWith("P0") || state.equals("55000")) + return Status.FAILED_PRECONDITION; + if (state.equals("40001") || state.equals("40P01")) return Status.ABORTED; + if (state.startsWith("08") || state.startsWith("57") || state.equals("55P03")) + return Status.UNAVAILABLE; + if (state.startsWith("22") || state.startsWith("42") || state.startsWith("XX")) + return Status.INTERNAL; + } + } + if (failure instanceof org.springframework.dao.DataIntegrityViolationException) + return Status.FAILED_PRECONDITION; + if (failure instanceof org.jooq.exception.DataAccessException + || failure instanceof org.springframework.dao.TransientDataAccessException + || failure instanceof org.springframework.dao.DataAccessResourceFailureException) + return Status.UNAVAILABLE; + return Status.INTERNAL; + } + + private static void refuse(StreamObserver observer, Status status, String message) { + observer.onError(status.withDescription(message).asRuntimeException()); + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogRepository.java new file mode 100644 index 0000000000..d0617e40a7 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogRepository.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.automationscripting.runtimecatalog; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Manual PostgreSQL census capture and independent committed readback; never runtime state. */ +public final class AutomationRuntimeFamilyCatalogRepository { + private final DSLContext dsl; + private final String schema; + private final String namespace; + private final TransactionTemplate capture; + private final TransactionTemplate readback; + + public AutomationRuntimeFamilyCatalogRepository( + DSLContext dsl, PlatformTransactionManager transactions, String schema, String namespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (schema == null + || !schema.matches("[a-z][a-z0-9_]{0,62}") + || !GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixed owner schema and workload namespace required"); + } + this.schema = schema; + this.namespace = namespace; + capture = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + capture.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + capture.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + readback = new TransactionTemplate(transactions); + readback.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readback.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readback.setReadOnly(true); + } + + /** Exact retries converge through SQL uniqueness; changed requests cannot replace a snapshot. */ + public Evidence read(Request request) { + requireIndependent(request); + byte[] committed = + capture.execute( + status -> { + AutomationRuntimeFamilyCatalog catalog = currentCatalog(); + byte[] requestBytes = AutomationRuntimeFamilyCatalogCodec.requestBytes(request); + var proposed = new Evidence(request, UUID.randomUUID(), catalog); + byte[] evidenceBytes = AutomationRuntimeFamilyCatalogCodec.evidenceBytes(proposed); + dsl.execute( + "INSERT INTO " + + table("automation_runtime_family_catalog_snapshot") + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," + + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" + + " ON CONFLICT (read_request_id) DO NOTHING", + request.readRequestId(), + request.targetNamespace(), + requestBytes, + AutomationRuntimeFamilyCatalog.sha256(requestBytes), + proposed.snapshotId(), + catalog.catalogEpoch(), + catalog.digest(), + evidenceBytes, + proposed.digest()); + return retained(request, catalog); + }); + Evidence result = readExact(request); + if (!Arrays.equals(committed, AutomationRuntimeFamilyCatalogCodec.evidenceBytes(result))) { + throw new CatalogConflictException("Committed Automation catalog readback changed"); + } + return result; + } + + /** Missing, stale, contradictory or corrupt evidence refuses; none is an empty-owner result. */ + public Evidence readExact(Request request) { + requireIndependent(request); + return readback.execute( + status -> + AutomationRuntimeFamilyCatalogCodec.evidenceFromStored( + retained(request, currentCatalog()))); + } + + private AutomationRuntimeFamilyCatalog currentCatalog() { + Record row = + dsl.fetchOne( + "SELECT catalog_epoch,catalog_bytes,catalog_digest," + + schema + + ".automation_runtime_family_catalog_bytes(catalog_epoch) AS current_bytes FROM " + + table("automation_runtime_family_catalog_epoch") + + " WHERE " + + schema + + ".automation_runtime_family_catalog_installed() ORDER BY catalog_epoch DESC LIMIT 1"); + if (row == null) throw new CatalogConflictException("No durable Automation catalog epoch"); + byte[] sealed = row.get("catalog_bytes", byte[].class); + if (!Arrays.equals(sealed, row.get("current_bytes", byte[].class))) { + throw new CatalogConflictException( + "Automation schema/classification drift invalidates its epoch"); + } + AutomationRuntimeFamilyCatalog catalog = AutomationRuntimeFamilyCatalog.fromStored(sealed); + if (catalog.catalogEpoch() != row.get("catalog_epoch", Long.class) + || !catalog.digest().equals(row.get("catalog_digest", String.class))) { + throw new CatalogConflictException("Automation catalog epoch/digest binding is inconsistent"); + } + return catalog; + } + + private byte[] retained(Request request, AutomationRuntimeFamilyCatalog current) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + table("automation_runtime_family_catalog_snapshot") + + " WHERE read_request_id=?", + request.readRequestId()); + if (row == null) + throw new CatalogConflictException("Exact Automation catalog snapshot is absent"); + byte[] bytes = row.get("evidence_bytes", byte[].class); + Evidence result = AutomationRuntimeFamilyCatalogCodec.evidenceFromStored(bytes); + byte[] requestBytes = AutomationRuntimeFamilyCatalogCodec.requestBytes(request); + if (!request.equals(result.request()) + || !request.targetNamespace().equals(row.get("target_namespace", String.class)) + || !Arrays.equals(requestBytes, row.get("request_bytes", byte[].class)) + || !AutomationRuntimeFamilyCatalog.sha256(requestBytes) + .equals(row.get("request_digest", String.class)) + || !result.snapshotId().equals(row.get("snapshot_id", UUID.class)) + || result.catalog().catalogEpoch() != row.get("catalog_epoch", Long.class) + || !result.catalog().digest().equals(row.get("catalog_digest", String.class)) + || !result.digest().equals(row.get("evidence_digest", String.class)) + || !Arrays.equals(current.exactBytes(), result.catalog().exactBytes())) { + throw new CatalogConflictException( + "Changed request or invalidated Automation catalog snapshot"); + } + return bytes; + } + + private String table(String name) { + return schema + "." + name; + } + + private void requireIndependent(Request request) { + Objects.requireNonNull(request, "request"); + if (!namespace.equals(request.targetNamespace())) + throw new CatalogConflictException("Wrong workload namespace"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Catalog evidence requires independent owner transactions"); + } + } + + public static final class CatalogConflictException extends IllegalStateException { + public CatalogConflictException(String message) { + super(message); + } + } +} diff --git a/services/automation-scripting-service/src/main/resources/db/migration/V1004__automation_owner_runtime_family_catalog.sql b/services/automation-scripting-service/src/main/resources/db/migration/V1004__automation_owner_runtime_family_catalog.sql new file mode 100644 index 0000000000..b773a5ef93 --- /dev/null +++ b/services/automation-scripting-service/src/main/resources/db/migration/V1004__automation_owner_runtime_family_catalog.sql @@ -0,0 +1,339 @@ +-- Additive source prerequisite only. No gameplay/source rows, sequences or prior history change. +CREATE TABLE automation_runtime_family_classification ( + family_id VARCHAR(127) PRIMARY KEY, + relation_name VARCHAR(63) NOT NULL, + component_name VARCHAR(63) NOT NULL DEFAULT '', + family_role VARCHAR(32) NOT NULL CHECK (family_role IN + ('RUNTIME_PAYLOAD','SOURCE','CONTROL','AUDIT','PROVENANCE','CATALOG')), + state_class VARCHAR(16) NOT NULL CHECK (state_class IN ('S2','UNKNOWN','UNRESOLVED','NOT_PAYLOAD')), + fresh_disposition VARCHAR(48) NOT NULL CHECK (fresh_disposition IN + ('STATE_CLASS_UNKNOWN_BLOCKING','NAMESPACE_MAPPING_BLOCKING','OWNERSHIP_DRIFT_BLOCKING', + 'RUNTIME_EVIDENCE_BLOCKING','SOURCE_ONLY','CONTROL_ONLY','AUDIT_ONLY','PROVENANCE_ONLY','CATALOG_ONLY')), + retention_disposition VARCHAR(32) NOT NULL CHECK (retention_disposition IN + ('OWNER_POLICY_RETAINED','UNRESOLVED_RETAINED','IMMUTABLE_RETAINED')), + owner_consequence VARCHAR(1024) NOT NULL, + UNIQUE (relation_name, component_name), + CHECK (relation_name ~ '^[a-z][a-z0-9_]{0,62}$'), + CHECK (component_name = '' OR component_name ~ '^[a-z][a-z0-9_]{0,62}$'), + CHECK (family_id = relation_name || CASE WHEN component_name = '' THEN '' ELSE '.' || component_name END), + CHECK ( + (fresh_disposition='STATE_CLASS_UNKNOWN_BLOCKING' AND family_role='RUNTIME_PAYLOAD' AND state_class='UNKNOWN') + OR (fresh_disposition='NAMESPACE_MAPPING_BLOCKING' AND family_role='RUNTIME_PAYLOAD' AND state_class='S2') + OR (fresh_disposition='OWNERSHIP_DRIFT_BLOCKING' AND family_role='RUNTIME_PAYLOAD' AND state_class='UNRESOLVED') + OR (fresh_disposition='RUNTIME_EVIDENCE_BLOCKING' AND family_role IN ('CONTROL','AUDIT','PROVENANCE') AND state_class='NOT_PAYLOAD') + OR (fresh_disposition='SOURCE_ONLY' AND family_role='SOURCE' AND state_class='NOT_PAYLOAD') + OR (fresh_disposition='CONTROL_ONLY' AND family_role='CONTROL' AND state_class='NOT_PAYLOAD') + OR (fresh_disposition='AUDIT_ONLY' AND family_role='AUDIT' AND state_class='NOT_PAYLOAD') + OR (fresh_disposition='PROVENANCE_ONLY' AND family_role='PROVENANCE' AND state_class='NOT_PAYLOAD') + OR (fresh_disposition='CATALOG_ONLY' AND family_role='CATALOG' AND state_class='NOT_PAYLOAD') + ), + CHECK (family_role <> 'CATALOG' OR retention_disposition='IMMUTABLE_RETAINED') +); + +-- Known non-SQL limitations, not a Redis census or invented durable charge family. +CREATE TABLE automation_runtime_catalog_non_sql_gap ( + gap_id VARCHAR(48) PRIMARY KEY CHECK (gap_id IN + ('CAPACITY_LEASE_ACCOUNTING','CENTRAL_RESET_ACL_REGISTRATION','DURABLE_CHARGE_MARKERS', + 'QUEUE_DISCOVERY_AND_ENCODING','QUEUE_POINTER_RETENTION')), + disposition VARCHAR(32) NOT NULL CHECK (disposition IN ('UNRESOLVED_BLOCKING','UNSUPPORTED_BLOCKING')), + owner_consequence VARCHAR(1024) NOT NULL +); + +CREATE TABLE automation_runtime_family_catalog_epoch ( + catalog_epoch BIGINT PRIMARY KEY CHECK (catalog_epoch > 0), + catalog_bytes BYTEA NOT NULL CHECK (octet_length(catalog_bytes) BETWEEN 1 AND 2097152), + catalog_digest VARCHAR(71) NOT NULL CHECK (catalog_digest = 'sha256:' || encode(sha256(catalog_bytes), 'hex')), + installed_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE automation_runtime_family_catalog_snapshot ( + read_request_id UUID PRIMARY KEY CHECK (read_request_id <> '00000000-0000-0000-0000-000000000000'), + target_namespace VARCHAR(63) NOT NULL CHECK (target_namespace ~ '^[a-z0-9]([-a-z0-9]*[a-z0-9])?$'), + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) BETWEEN 1 AND 1024), + request_digest VARCHAR(71) NOT NULL CHECK (request_digest = 'sha256:' || encode(sha256(request_bytes), 'hex')), + snapshot_id UUID NOT NULL UNIQUE CHECK (snapshot_id <> '00000000-0000-0000-0000-000000000000'), + catalog_epoch BIGINT NOT NULL REFERENCES automation_runtime_family_catalog_epoch(catalog_epoch), + catalog_digest VARCHAR(71) NOT NULL, + evidence_bytes BYTEA NOT NULL CHECK (octet_length(evidence_bytes) BETWEEN 1 AND 2101248), + evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest = 'sha256:' || encode(sha256(evidence_bytes), 'hex')), + retained_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +-- PostgreSQL POSIX character classes are not simulated equivalently by DDLDatabase/H2. +-- Preserve the exact owner-consequence guards in PostgreSQL while exposing all table types. +-- [jooq ignore start] +ALTER TABLE automation_runtime_family_classification + ADD CONSTRAINT ck_automation_runtime_family_consequence + CHECK (length(btrim(owner_consequence)) > 0 AND owner_consequence !~ '[[:cntrl:]]'); +ALTER TABLE automation_runtime_catalog_non_sql_gap + ADD CONSTRAINT ck_automation_runtime_gap_consequence + CHECK (length(btrim(owner_consequence)) > 0 AND owner_consequence !~ '[[:cntrl:]]'); +-- [jooq ignore stop] + +-- Exhaustive exact current table dispositions. UNKNOWN/UNRESOLVED are refusal facts, not S3. +-- The classifications describe source facts, not target-namespace absence or initialization proof. +INSERT INTO automation_runtime_family_classification + (family_id,relation_name,component_name,family_role,state_class,fresh_disposition,retention_disposition,owner_consequence) +VALUES + ('npc_memory','npc_memory','','RUNTIME_PAYLOAD','UNKNOWN','STATE_CLASS_UNKNOWN_BLOCKING','UNRESOLVED_RETAINED', + 'Live latent behavior memory keyed by tenant/npc/key; stable namespace, typed actor scope, replacement class and required initialization are unresolved. Retain; never inherit or assume disposable.'), + ('npc_formations','npc_formations','','RUNTIME_PAYLOAD','UNKNOWN','STATE_CLASS_UNKNOWN_BLOCKING','UNRESOLVED_RETAINED', + 'Formation leader references lack Entity-owned tenant/namespace actor proof; classification and fresh initialization remain unsupported. Do not clone formations.'), + ('npc_formation_member','npc_formation_member','','RUNTIME_PAYLOAD','UNKNOWN','STATE_CLASS_UNKNOWN_BLOCKING','UNRESOLVED_RETAINED', + 'Membership follows a formation but lacks namespace and member NPC owner proof; preserve dependency closure and do not infer S3.'), + ('faction_standing','faction_standing','','RUNTIME_PAYLOAD','UNRESOLVED','OWNERSHIP_DRIFT_BLOCKING','UNRESOLVED_RETAINED', + 'Live Automation player-reputation writer conflicts with canonical Social ownership. Social must own tenant/namespace/character/faction identity after retained-row disposition and consumer cutover; not Automation FRESH ownership.'), + ('script_work_items','script_work_items','','RUNTIME_PAYLOAD','UNKNOWN','STATE_CLASS_UNKNOWN_BLOCKING','UNRESOLVED_RETAINED', + 'Admitted work and uncertain handoff share one row; namespace, sealed input/descriptor recovery and family classification are incomplete. No inherited pending work, receipts or synthetic initialization.'), + ('script_schedule_instances','script_schedule_instances','','RUNTIME_PAYLOAD','S2','NAMESPACE_MAPPING_BLOCKING','UNRESOLVED_RETAINED', + 'Canonical durable schedules/due state are S2; live rows lack stable namespace and complete owner continuity/mapping proof. Never inherit due points, fire schedules or fabricate target initialization.'), + ('plugin_runtime_states','plugin_runtime_states','','RUNTIME_PAYLOAD','UNKNOWN','STATE_CLASS_UNKNOWN_BLOCKING','UNRESOLVED_RETAINED', + 'Exact plugin activation/lifecycle tuples are narrower than private lifecycle/namespace/build proof. Required initialization and replacement classification are unresolved; do not activate or generate an epoch to populate evidence.'), + ('script_event_ingress_audit','script_event_ingress_audit','','AUDIT','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED', + 'Event-scope claim/admission audit mixes runtime and pre-instance readiness branches; runtime namespace and frozen handler manifest are absent. Retain original claims and never clone source audit authority.'), + ('script_event_audit','script_event_audit','','AUDIT','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED', + 'Handler, timer-candidate and readiness evidence is not a fresh manifest; namespace and complete recovery-bundle proof are missing. Existing holds and references remain authoritative for retention.'), + ('script_handoff_events','script_handoff_events','','AUDIT','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED', + 'Retain per-child handoff/remote lineage under existing work, replay and hold guards; complete source/target namespace and descriptor recovery evidence is unsupported. No inherited handoff receipts.'), + ('script_dead_letter_replay_requests','script_dead_letter_replay_requests','','CONTROL','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED', + 'Retained replay request identity/result is retry authority, not initialized gameplay. Minimum measured horizons, aggregate recovery claims and target namespace proof are unresolved; no clone or new cleanup.'), + ('script_dead_letter_replay_results','script_dead_letter_replay_results','','PROVENANCE','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED', + 'Generation-bound results hold their referenced work and retain rejection/failure lineage; horizon and complete recovery ledger are unresolved. Never copy or delete receipts by omission.'), + ('plugin_runtime_request_history','plugin_runtime_request_history','','CONTROL','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED', + 'Immutable exact lifecycle retry receipts survive no-op and later transitions; namespace binding and measured retry/recovery/restore horizons remain unresolved. Retain without cloning.'), + ('plugin_runtime_events','plugin_runtime_events','','AUDIT','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED', + 'Plugin lifecycle history is retained reconciliation/audit evidence, not pin or rollout authority. Holds, safe watermark and measured retention horizons are unresolved; no inherited chronology.'), + ('script_patch_pin_projections','script_patch_pin_projections','','CONTROL','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED', + 'Non-authoritative Game Session exact-pin observation; never mint a pin or infer UNPINNED from outage/absence. Stable private namespace/lifecycle evidence is missing.'), + ('script_patch_instance_rollout_projections','script_patch_instance_rollout_projections','','CONTROL','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED', + 'Automation convergence projection only; Game Session owns pin and rollout history. No private lifecycle/namespace manifest or inherited source timeline.'), + ('script_patch_instance_rollout_events','script_patch_instance_rollout_events','','AUDIT','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED', + 'Legacy observed rollout diagnostics remain retained non-authoritative history, not Game Session committed rollout events or a new target timeline.'), + ('automation_admission_states','automation_admission_states','','CONTROL','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED', + 'Local scoped Automation barrier/epoch is not actor authorization, global admission or private lifecycle proof; no source barrier is inherited.'), + ('automation_admission_request_history','automation_admission_request_history','','CONTROL','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED', + 'Exact barrier acknowledgements are retained retry evidence; horizon/tombstone and private namespace/lifecycle contracts remain missing. Do not copy source requests.'), + ('scripts','scripts','','SOURCE','NOT_PAYLOAD','SOURCE_ONLY','OWNER_POLICY_RETAINED', + 'Versioned compiled definition source; production authoring/publication authority stays Game Design. Exact base/provenance and supported-version retention remain required; never clone mutable runtime state.'), + ('script_event_bindings','script_event_bindings','','SOURCE','NOT_PAYLOAD','SOURCE_ONLY','OWNER_POLICY_RETAINED', + 'Versioned resolved event/binding source, not a frozen handler manifest or proof of a complete selected runtime owner set.'), + ('script_schedule_definitions','script_schedule_definitions','','SOURCE','NOT_PAYLOAD','SOURCE_ONLY','OWNER_POLICY_RETAINED', + 'Authored patch-derived cadence definitions are outside S1/S2/S3; retain with supported source/version lifecycle, never equate definitions with initialized due state.'), + ('factions','factions','','SOURCE','NOT_PAYLOAD','SOURCE_ONLY','OWNER_POLICY_RETAINED', + 'Local faction behavior definitions may remain Automation input; this does not authorize the separate player-standing writer or establish namespace-scoped Social standing.'), + ('script_patch_readiness_projections','script_patch_readiness_projections','','CONTROL','NOT_PAYLOAD','CONTROL_ONLY','UNRESOLVED_RETAINED', + 'Tenant readiness/generation and onLoad bookkeeping, not durable game initialization. Complete expected-handler/source-publication proof is missing; do not run onLoad to fabricate FRESH evidence.'), + ('script_patch_base_bindings','script_patch_base_bindings','','PROVENANCE','NOT_PAYLOAD','PROVENANCE_ONLY','OWNER_POLICY_RETAINED', + 'Exact patch-to-base source provenance; no historical missing base is synthesized and this is not runtime pin/activation authority.'), + ('automation_empty_source_numeric_key_reservation','automation_empty_source_numeric_key_reservation','','CONTROL','NOT_PAYLOAD','CONTROL_ONLY','OWNER_POLICY_RETAINED', + 'Retain immutable legacy/canonical numeric source custody and its writer guards; private numeric source keys are not playable namespace identity.'), + ('automation_empty_selected_source_association','automation_empty_selected_source_association','','SOURCE','NOT_PAYLOAD','SOURCE_ONLY','OWNER_POLICY_RETAINED', + 'Selected-empty authored source association with original Account/World provenance; empty authored inventory is not empty runtime families or FRESH completeness.'), + ('automation_empty_selected_source_receipt','automation_empty_selected_source_receipt','','PROVENANCE','NOT_PAYLOAD','PROVENANCE_ONLY','OWNER_POLICY_RETAINED', + 'Retain original immutable selected-source receipt and authorization/readback digests; never reuse it as a runtime manifest or release authority.'), + ('saga_instance','saga_instance','','CONTROL','NOT_PAYLOAD','CONTROL_ONLY','OWNER_POLICY_RETAINED', + 'Installed adopter-local Saga workflow state under existing retention; not runtime payload, FRESH membership or a second lifecycle authority.'), + ('saga_step','saga_step','','CONTROL','NOT_PAYLOAD','CONTROL_ONLY','OWNER_POLICY_RETAINED', + 'Installed adopter-local Saga step/recovery lineage remains retained with its parent; no cloning or cleanup permission.'), + ('script_event_ingress_audit.script_id','script_event_ingress_audit','script_id','CONTROL','NOT_PAYLOAD','CONTROL_ONLY','UNRESOLVED_RETAINED', + 'Pre-instance onLoad branch is tenant-readiness only and omits runtime identity; this mixed-table component cannot establish namespace absence.'), + ('script_work_items.read_snapshot_token','script_work_items','read_snapshot_token','PROVENANCE','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED', + 'One legacy owner token is narrower than the sealed handler input manifest; no owner versions, causal floor, artifact and seed completeness is implied.'), + ('script_work_items.admission_epoch','script_work_items','admission_epoch','CONTROL','NOT_PAYLOAD','RUNTIME_EVIDENCE_BLOCKING','UNRESOLVED_RETAINED', + 'Local barrier evidence is not the missing durable full-Trigger-Identity admission/execution charge marker or private lifecycle generation.'), + ('plugin_runtime_states.last_policy_checked_at','plugin_runtime_states','last_policy_checked_at','CONTROL','NOT_PAYLOAD','CONTROL_ONLY','UNRESOLVED_RETAINED', + 'Signer/component-policy observation is runtime enforcement input only; accepted Game Design provenance, fresh policy and lifecycle/final-effect fences remain distinct.'), + ('script_patch_readiness_projections.readiness_generation','script_patch_readiness_projections','readiness_generation','CONTROL','NOT_PAYLOAD','CONTROL_ONLY','UNRESOLVED_RETAINED', + 'Tenant readiness generation is not private playtestStateGeneration, source publication ordering or durable handler-created initialization.'), + ('automation_runtime_family_classification','automation_runtime_family_classification','','CATALOG','NOT_PAYLOAD','CATALOG_ONLY','IMMUTABLE_RETAINED', + 'Exact explicit installed family dispositions; changed classification invalidates the prior epoch, never enrollment or materialization authority.'), + ('automation_runtime_catalog_non_sql_gap','automation_runtime_catalog_non_sql_gap','','CATALOG','NOT_PAYLOAD','CATALOG_ONLY','IMMUTABLE_RETAINED', + 'Retained known non-SQL limitation declarations only; no Redis census, key inventory or durable charge table is invented.'), + ('automation_runtime_family_catalog_epoch','automation_runtime_family_catalog_epoch','','CATALOG','NOT_PAYLOAD','CATALOG_ONLY','IMMUTABLE_RETAINED', + 'Retained monotonic schema/classification seal; owner-local epoch only, not common registry revision or target state currentness.'), + ('automation_runtime_family_catalog_snapshot','automation_runtime_family_catalog_snapshot','','CATALOG','NOT_PAYLOAD','CATALOG_ONLY','IMMUTABLE_RETAINED', + 'Retained exact request/snapshot/catalog bytes and digests; no TTL, FRESH completeness or actor permission.'); + +INSERT INTO automation_runtime_catalog_non_sql_gap VALUES + ('CAPACITY_LEASE_ACCOUNTING','UNRESOLVED_BLOCKING', + 'Readiness/dry-run Redis reservations are not work-item-idempotent; retry can overwrite the prior lease and leak counts until expiry. Fenced/reclaimable accounting remains unproved.'), + ('CENTRAL_RESET_ACL_REGISTRATION','UNRESOLVED_BLOCKING', + 'Live test quota/capacity and readiness capacity families are not all in the central reset/ACL inventory; no reset, resume or environment registration is authorized here.'), + ('DURABLE_CHARGE_MARKERS','UNSUPPORTED_BLOCKING', + 'Quota/tenant-budget/capacity decisions are best-effort Redis counters/leases. Durable full-Trigger-Identity charge rows and exactly-once admission/execution-start markers do not exist.'), + ('QUEUE_DISCOVERY_AND_ENCODING','UNRESOLVED_BLOCKING', + 'Live queue discovery uses database-wide KEYS and raw nonblank identity builders; cluster-safe owner index, canonical tuple encoding and collision/brace proof are missing.'), + ('QUEUE_POINTER_RETENTION','UNSUPPORTED_BLOCKING', + 'Live RPUSH/LPOP queue pointer lists have no pointer TTL or maximum-length bound; owner-reconciled durable re-drive/reset gate is unavailable. SQL census does not enumerate these Redis keys.'); + +-- Flyway 13.12 built-in placeholder selects the ACTUAL configured history table. +-- Narrow PostgreSQL-only block: all ordinary table DDL above stays visible to jOOQ. +-- [jooq ignore start] +INSERT INTO automation_runtime_family_classification + (family_id,relation_name,family_role,state_class,fresh_disposition,retention_disposition,owner_consequence) +VALUES ('${flyway:table}','${flyway:table}','CONTROL','NOT_PAYLOAD','CONTROL_ONLY','OWNER_POLICY_RETAINED', + 'Actual configured owner Flyway history is retained installation evidence, not gameplay state or enrollment.'); + +CREATE FUNCTION automation_runtime_family_catalog_installed() RETURNS BOOLEAN +LANGUAGE SQL STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ + SELECT EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1004' AND script='V1004__automation_owner_runtime_family_catalog.sql' AND success); +$$; + +CREATE FUNCTION automation_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE v_families JSONB; v_facts JSONB; v_gaps JSONB; +BEGIN + IF p_epoch IS NULL OR p_epoch<=0 THEN + RAISE EXCEPTION 'Positive Automation catalog epoch required' USING ERRCODE='23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM automation_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM automation_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed Automation schema family' USING ERRCODE='23514'; + END IF; + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name,'component',component_name, + 'role',family_role,'stateClass',state_class,'freshDisposition',fresh_disposition, + 'retentionDisposition',retention_disposition,'ownerConsequence',owner_consequence) + ORDER BY family_id COLLATE "C") INTO v_families FROM automation_runtime_family_classification; + SELECT jsonb_agg(jsonb_build_object('id',gap_id,'disposition',disposition,'ownerConsequence',owner_consequence) + ORDER BY gap_id COLLATE "C") INTO v_gaps FROM automation_runtime_catalog_non_sql_gap; + + -- Live definitions, never payload rows, OIDs, sequence positions, statistics or installation times. + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname,jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,pg_get_viewdef(c.oid,true) FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1004' + UNION ALL + -- Own row is post-transaction. Exact installed definitions plus this stable marker bind + -- installation; the separate installed() check requires the later successful exact script. + -- This is deliberately NOT a fabricated checksum for the not-yet-written Flyway row. + SELECT 'MIGRATION','catalog-installation:1004','V1004__automation_owner_runtime_family_catalog.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + IF v_families IS NULL OR v_facts IS NULL OR v_gaps IS NULL + OR jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 + OR jsonb_array_length(v_gaps)>32 THEN + RAISE EXCEPTION 'Complete Automation catalog exceeds source bounds' USING ERRCODE='23514'; + END IF; + RETURN convert_to(jsonb_build_object('schema','automation-runtime-family-catalog/v1', + 'owner','automation-scripting-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts,'nonSqlGaps',v_gaps)::TEXT,'UTF8'); +END; +$$; + +CREATE FUNCTION automation_runtime_catalog_immutable() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Automation runtime catalog evidence is immutable' USING ERRCODE='23514'; +END; +$$; +CREATE TRIGGER automation_runtime_classification_retained BEFORE UPDATE OR DELETE OR TRUNCATE +ON automation_runtime_family_classification FOR EACH STATEMENT EXECUTE FUNCTION automation_runtime_catalog_immutable(); +CREATE TRIGGER automation_runtime_non_sql_gap_retained BEFORE UPDATE OR DELETE OR TRUNCATE +ON automation_runtime_catalog_non_sql_gap FOR EACH STATEMENT EXECUTE FUNCTION automation_runtime_catalog_immutable(); +CREATE TRIGGER automation_runtime_epoch_retained BEFORE UPDATE OR DELETE OR TRUNCATE +ON automation_runtime_family_catalog_epoch FOR EACH STATEMENT EXECUTE FUNCTION automation_runtime_catalog_immutable(); +CREATE TRIGGER automation_runtime_snapshot_retained BEFORE UPDATE OR DELETE OR TRUNCATE +ON automation_runtime_family_catalog_snapshot FOR EACH STATEMENT EXECUTE FUNCTION automation_runtime_catalog_immutable(); + +CREATE FUNCTION automation_runtime_catalog_epoch_guard() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = "${serviceSchema}", pg_catalog AS $$ +BEGIN + IF NEW.catalog_epoch<>coalesce((SELECT max(catalog_epoch) FROM automation_runtime_family_catalog_epoch),0)+1 + OR NEW.catalog_bytes<>automation_runtime_family_catalog_bytes(NEW.catalog_epoch) THEN + RAISE EXCEPTION 'Automation epoch must bind the exact classified installed schema' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER automation_runtime_epoch_exact BEFORE INSERT ON automation_runtime_family_catalog_epoch +FOR EACH ROW EXECUTE FUNCTION automation_runtime_catalog_epoch_guard(); + +CREATE FUNCTION automation_runtime_catalog_snapshot_guard() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE v_epoch automation_runtime_family_catalog_epoch%ROWTYPE; v_request BYTEA; v_evidence BYTEA; +BEGIN + SELECT * INTO STRICT v_epoch FROM automation_runtime_family_catalog_epoch ORDER BY catalog_epoch DESC LIMIT 1; + IF NOT automation_runtime_family_catalog_installed() + OR NEW.catalog_epoch<>v_epoch.catalog_epoch OR NEW.catalog_digest<>v_epoch.catalog_digest + OR automation_runtime_family_catalog_bytes(v_epoch.catalog_epoch)<>v_epoch.catalog_bytes THEN + RAISE EXCEPTION 'Automation runtime catalog changed; new owner epoch required' USING ERRCODE='23514'; + END IF; + -- Exact ACR1/ACE1 binary frames match the closed Java codec, including the original request. + v_request := decode('41435231','hex') || uuid_send(NEW.read_request_id) + || int4send(octet_length(convert_to(NEW.target_namespace,'UTF8'))) || convert_to(NEW.target_namespace,'UTF8'); + v_evidence := decode('41434531','hex') || int4send(octet_length(v_request)) || v_request + || uuid_send(NEW.snapshot_id) || int4send(octet_length(convert_to(v_epoch.catalog_digest,'UTF8'))) + || convert_to(v_epoch.catalog_digest,'UTF8') || int4send(octet_length(v_epoch.catalog_bytes)) || v_epoch.catalog_bytes; + IF NEW.request_bytes<>v_request OR NEW.evidence_bytes<>v_evidence THEN + RAISE EXCEPTION 'Automation snapshot must bind complete exact request and evidence' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER automation_runtime_snapshot_current BEFORE INSERT ON automation_runtime_family_catalog_snapshot +FOR EACH ROW EXECUTE FUNCTION automation_runtime_catalog_snapshot_guard(); +-- [jooq ignore stop] + +-- PostgreSQL-only bootstrap, not an H2/embedded simulation of pg_catalog completeness. +-- [jooq ignore start] +INSERT INTO automation_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT 1,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM (SELECT automation_runtime_family_catalog_bytes(1) AS bytes) seal; +-- [jooq ignore stop] diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java index 6bfbed9acc..0ede369ba3 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java @@ -17,6 +17,7 @@ import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -87,7 +88,14 @@ void setUpRepositories() { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); - Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") + .schemas("public") + .defaultSchema("public") + .placeholders(Map.of("serviceSchema", "public")) + .load() + .migrate(); dsl = DSL.using(dataSource, SQLDialect.POSTGRES); ingressRepository = new ScriptEventIngressAuditRepository(dsl); @@ -173,9 +181,10 @@ void flywayV4PreservesV3WorkItemsAndPersistsReplayEvidence() { Flyway.configure() .dataSource(upgradeDataSource) - .locations(MIGRATION_LOCATION) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") .schemas(upgradeSchema) .defaultSchema(upgradeSchema) + .placeholders(Map.of("serviceSchema", upgradeSchema)) .load() .migrate(); diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java new file mode 100644 index 0000000000..d9142e9fa9 --- /dev/null +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -0,0 +1,705 @@ +package net.firedevops.firemud.automationscripting.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.automationscripting.runtimecatalog.AutomationRuntimeFamilyCatalogReadGrpcService; +import net.firedevops.firemud.automationscripting.runtimecatalog.AutomationRuntimeFamilyCatalogRepository; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.automationscripting.v1.ReadAutomationRuntimeFamilyCatalogResponse; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.FactKind; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.FreshDisposition; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.GapId; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.StateClass; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual combined Automation/Saga migration proof, using the existing Automation filesystem Flyway + * and Testcontainers pattern. Legacy rows and RPC peer context are controlled. No SQL fixture is a + * live private authority producer or mTLS/PKI proof. Positive cases are not disabled without + * Docker. + */ +@Testcontainers +@SuppressWarnings("resource") +class AutomationRuntimeFamilyCatalogPostgresIntegrationTest { + private static final String MIGRATIONS = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String HISTORY = "flyway_schema_history_automation_scripting_service"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void actualConfiguredHistoryNotHardcodedHistoryBindsInstallation() throws Exception { + for (String history : + List.of("flyway_schema_history_public", "flyway_schema_history_custom_auto")) { + try (Fixture f = fixture(null, history)) { + var evidence = f.owner().read(request()); + assertThat(evidence.catalog().families()) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo(history); + assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.CONTROL_ONLY); + }); + assertThat(f.owner().readExact(evidence.request())).isEqualTo(evidence); + assertThat( + f.dsl + .fetchSingle("SELECT to_regclass(?) IS NULL", f.schema + "." + HISTORY) + .get(0, Boolean.class)) + .isTrue(); + } + } + } + + @Test + void completeLiveCensusIncludesEveryEmptyTableAndExplicitBlockingFamiliesAndNonSqlGaps() + throws Exception { + try (Fixture f = fixture(null)) { + var catalog = f.owner().read(request()).catalog(); + assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat( + catalog.schemaFacts().stream() + .filter(fact -> fact.kind() == FactKind.TABLE) + .map(AutomationRuntimeFamilyCatalog.SchemaFact::identity) + .toList()) + .containsExactlyInAnyOrderElementsOf(f.tables()); + assertThat(catalog.families().stream().filter(family -> family.component().isEmpty()).count()) + .isEqualTo(f.tables().size()); + for (String name : + List.of( + "npc_memory", + "npc_formations", + "npc_formation_member", + "script_work_items", + "plugin_runtime_states")) { + assertThat(catalog.families()) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo(name); + assertThat(family.stateClass()).isEqualTo(StateClass.UNKNOWN); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.STATE_CLASS_UNKNOWN_BLOCKING); + }); + } + assertThat(catalog.families()) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo("faction_standing"); + assertThat(family.stateClass()).isEqualTo(StateClass.UNRESOLVED); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.OWNERSHIP_DRIFT_BLOCKING); + assertThat(family.ownerConsequence()) + .contains( + "Social", "retained-row disposition", "not Automation FRESH ownership"); + }) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo("script_schedule_instances"); + assertThat(family.stateClass()).isEqualTo(StateClass.S2); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.NAMESPACE_MAPPING_BLOCKING); + }); + assertThat(catalog.families()) + .anyMatch(family -> family.familyId().equals("saga_instance")) + .anyMatch(family -> family.familyId().equals("saga_step")) + .anyMatch(family -> family.familyId().equals("automation_empty_selected_source_receipt")) + .anyMatch(family -> family.familyId().equals("script_work_items.read_snapshot_token")) + .allSatisfy(family -> assertThat(family.ownerConsequence()).isNotBlank()); + assertThat(catalog.nonSqlGaps()) + .extracting(AutomationRuntimeFamilyCatalog.NonSqlGap::id) + .containsExactly( + GapId.CAPACITY_LEASE_ACCOUNTING, + GapId.CENTRAL_RESET_ACL_REGISTRATION, + GapId.DURABLE_CHARGE_MARKERS, + GapId.QUEUE_DISCOVERY_AND_ENCODING, + GapId.QUEUE_POINTER_RETENTION); + assertThat(catalog.families()) + .noneMatch( + family -> + family.familyId().contains("charge_record") + || family.familyId().equals("redis_queue") + || family.familyId().equals("script_firing_claims")); + assertThat(catalog.schemaFacts()) + .anyMatch(fact -> fact.kind() == FactKind.ROUTINE) + .anyMatch(fact -> fact.kind() == FactKind.MIGRATION) + .anyMatch(fact -> fact.kind() == FactKind.SEQUENCE); + assertThat( + f.dsl + .fetchSingle( + "SELECT catalog_bytes=automation_runtime_family_catalog_bytes(catalog_epoch)" + + " FROM automation_runtime_family_catalog_epoch") + .get(0, Boolean.class)) + .isTrue(); + assertThat(f.count("script_work_items")).isZero(); + assertThat(f.count("script_schedule_instances")).isZero(); + assertThat(f.count("plugin_runtime_states")).isZero(); + assertThat(f.count("faction_standing")).isZero(); + } + } + + @Test + void exactRetryRestartAndIndependentReadbackRetainBytesDigestsAndSnapshotIdentity() + throws Exception { + try (Fixture f = fixture(null)) { + Request read = request(); + var original = f.owner().read(read); + assertThat(f.owner().read(read)).isEqualTo(original); + assertThat(f.owner().readExact(read)).isEqualTo(original); + assertThat(f.count("automation_runtime_family_catalog_snapshot")).isEqualTo(1); + var other = f.owner().read(request()); + assertThat(other.snapshotId()).isNotEqualTo(original.snapshotId()); + assertThat(other.catalog().exactBytes()).isEqualTo(original.catalog().exactBytes()); + assertThat(other.catalog().digest()).isEqualTo(original.catalog().digest()); + var foreignOwner = + new AutomationRuntimeFamilyCatalogRepository(f.dsl, f.manager, f.schema, "other"); + assertThatThrownBy(() -> foreignOwner.read(new Request(read.readRequestId(), "other"))) + .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().readExact(request())) + .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.count("automation_runtime_family_catalog_snapshot")).isEqualTo(2); + } + } + + @Test + void concurrentExactRetriesConvergeOnOneImmutableSnapshot() throws Exception { + try (Fixture f = fixture(null); + var workers = Executors.newFixedThreadPool(2)) { + Request read = request(); + var first = workers.submit(() -> f.owner().read(read)); + var second = workers.submit(() -> f.owner().read(read)); + assertThat(first.get(30, TimeUnit.SECONDS)).isEqualTo(second.get(30, TimeUnit.SECONDS)); + assertThat(f.count("automation_runtime_family_catalog_snapshot")).isEqualTo(1); + } + } + + @Test + void forwardUpgradePreservesPopulatedPredecessorRowsHistorySequencesAndSourceGuards() + throws Exception { + try (Fixture f = fixture("1003")) { + f.populatePredecessor(); + Map rows = f.rows(); + assertThat(rows.values()).allSatisfy(value -> assertThat(value).isNotEqualTo("[]")); + List history = f.historyRows(false); + List sequences = f.sequencePositions(); + List guards = f.guards(); + migration(f.source, f.schema, f.history, null).migrate(); + for (var retained : rows.entrySet()) + assertThat(f.jsonRows(retained.getKey())).isEqualTo(retained.getValue()); + assertThat(f.historyRows(true)).isEqualTo(history); + assertThat(f.sequencePositions()).isEqualTo(sequences); + assertThat(f.guards()).containsAll(guards); + var evidence = f.owner().read(request()); + assertThat(f.owner().readExact(evidence.request())).isEqualTo(evidence); + for (var retained : rows.entrySet()) + assertThat(f.jsonRows(retained.getKey())).isEqualTo(retained.getValue()); + assertThat(f.sequencePositions()).isEqualTo(sequences); + // Existing source custody trigger must still reject its protected immutable reservation. + assertThatThrownBy( + () -> f.dsl.execute("DELETE FROM automation_empty_source_numeric_key_reservation")) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO scripts(tenant_id,name,version,definition) VALUES(1,'forbidden','patch','{}')")) + .hasMessageContaining("reserved by an immutable empty-source receipt"); + migration(f.source, f.schema, f.history, null).validate(); + } + } + + @Test + void emptyUnknownTableInvalidatesOldReadAndRefusesNewCapture() throws Exception { + try (Fixture f = fixture(null)) { + Request read = request(); + f.owner().read(read); + f.dsl.execute("CREATE TABLE unknown_runtime_family (id BIGINT PRIMARY KEY)"); + assertThat(f.count("unknown_runtime_family")).isZero(); + assertThatThrownBy(() -> f.owner().readExact(read)).hasMessageContaining("Unclassified"); + assertThatThrownBy(() -> f.owner().read(request())).hasMessageContaining("Unclassified"); + assertThat(f.count("automation_runtime_family_catalog_snapshot")).isEqualTo(1); + } + } + + @Test + void installationOnUnknownPredecessorFamilyFailsAtomicallyWithoutHistoryRewrite() + throws Exception { + try (Fixture f = fixture("1003")) { + f.dsl.execute("CREATE TABLE unknown_runtime_family (id BIGINT PRIMARY KEY)"); + List history = f.historyRows(false); + assertThatThrownBy(() -> migration(f.source, f.schema, f.history, null).migrate()) + .hasMessageContaining("Unclassified or changed"); + assertThat( + f.dsl + .fetchSingle( + "SELECT to_regclass(?) IS NULL", + f.schema + ".automation_runtime_family_catalog_epoch") + .get(0, Boolean.class)) + .isTrue(); + assertThat(f.historyRows(false)).isEqualTo(history); + assertThat(f.count("unknown_runtime_family")).isZero(); + } + } + + @Test + void columnAddRemoveRenameConstraintsAndRoutineDriftCannotResampleSameEpoch() throws Exception { + for (String change : + List.of( + "ALTER TABLE npc_memory ADD COLUMN future_state TEXT", + "ALTER TABLE npc_memory RENAME COLUMN value TO later_value", + "ALTER TABLE npc_memory DROP COLUMN value", + "ALTER TABLE npc_memory ADD CONSTRAINT catalog_probe CHECK (id>0)", + "ALTER TABLE npc_memory RENAME TO renamed_memory", + "CREATE FUNCTION future_runtime_writer() RETURNS INTEGER LANGUAGE SQL AS 'SELECT 1'", + "ALTER FUNCTION automation_source_positive_numeric_key(TEXT) RENAME TO renamed_numeric_parser")) { + try (Fixture f = fixture(null)) { + Request read = request(); + f.owner().read(read); + f.dsl.execute(change); + assertThatThrownBy(() -> f.owner().readExact(read)).isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> f.owner().read(request())).isInstanceOf(RuntimeException.class); + assertThat(f.count("automation_runtime_family_catalog_snapshot")).isEqualTo(1); + } + } + } + + @Test + void removalClassificationAndNonSqlGapChangesInvalidateWithoutOverwritingEvidence() + throws Exception { + try (Fixture f = fixture(null)) { + Request read = request(); + f.owner().read(read); + f.dsl.execute("DROP TABLE npc_memory"); + assertThatThrownBy(() -> f.owner().readExact(read)) + .hasMessageContaining("Unclassified or changed"); + } + try (Fixture f = fixture(null)) { + Request read = request(); + var original = f.owner().read(read); + f.addComponent(); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(request())) + .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat( + f.dsl + .fetchSingle( + "SELECT evidence_bytes FROM automation_runtime_family_catalog_snapshot WHERE read_request_id=?", + read.readRequestId()) + .get(0, byte[].class)) + .isEqualTo(AutomationRuntimeFamilyCatalogCodec.evidenceBytes(original)); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE automation_runtime_catalog_non_sql_gap SET disposition='UNRESOLVED_BLOCKING'")) + .hasMessageContaining("immutable"); + } + } + + @Test + void priorMigrationFactsAndOwnSuccessfulScriptAreRequiredNotFabricatedOwnChecksum() + throws Exception { + try (Fixture f = fixture(null)) { + Request read = request(); + f.owner().read(read); + f.dsl.execute("UPDATE " + f.history + " SET checksum=checksum+1 WHERE version='1'"); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); + } + for (String change : List.of("success=false", "script='wrong_catalog_installation.sql'")) { + try (Fixture f = fixture(null)) { + f.dsl.execute("UPDATE " + f.history + " SET " + change + " WHERE version='1004'"); + assertThatThrownBy(() -> f.owner().read(request())) + .hasMessageContaining("No durable Automation catalog epoch"); + assertThat(f.count("automation_runtime_family_catalog_snapshot")).isZero(); + } + } + try (Fixture f = fixture(null)) { + f.owner().read(request()); + f.dsl.execute( + "INSERT INTO " + + f.history + + " (installed_rank,version,description,type,script,checksum,installed_by,execution_time,success)" + + " VALUES (10000,'1005','controlled later migration','SQL','V1005__probe.sql',1,current_user,0,true)"); + assertThatThrownBy(() -> f.owner().read(request())) + .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); + } + } + + @Test + void explicitOwnerEpochAdvanceInvalidatesOldRequestButRetainsOriginalSnapshot() throws Exception { + try (Fixture f = fixture(null)) { + Request read = request(); + var original = f.owner().read(read); + f.addComponent(); + // Controlled owner revision installation only; no runtime mutation/registration API exists. + f.dsl.execute( + "INSERT INTO automation_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" + + " SELECT 2,bytes,'sha256:'||encode(sha256(bytes),'hex')" + + " FROM (SELECT automation_runtime_family_catalog_bytes(2) AS bytes) revised"); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(read)) + .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat( + f.dsl + .fetchSingle( + "SELECT evidence_bytes FROM automation_runtime_family_catalog_snapshot WHERE read_request_id=?", + read.readRequestId()) + .get(0, byte[].class)) + .isEqualTo(AutomationRuntimeFamilyCatalogCodec.evidenceBytes(original)); + var revised = f.owner().read(request()); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(2); + assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); + assertThat(f.count("automation_runtime_family_catalog_epoch")).isEqualTo(2); + } + } + + @Test + void metadataEpochSnapshotRetentionAndCompleteSqlFrameBindingCannotBeBypassed() throws Exception { + try (Fixture f = fixture(null)) { + var original = f.owner().read(request()); + for (String consequence : List.of(" ", "\t")) { + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO automation_runtime_family_classification VALUES" + + " ('npc_memory.value','npc_memory','value','RUNTIME_PAYLOAD','UNKNOWN'," + + "'STATE_CLASS_UNKNOWN_BLOCKING','UNRESOLVED_RETAINED',?)", + consequence)) + .hasMessageContaining("ck_automation_runtime_family_consequence"); + } + for (String table : + List.of( + "automation_runtime_family_classification", + "automation_runtime_catalog_non_sql_gap", + "automation_runtime_family_catalog_epoch", + "automation_runtime_family_catalog_snapshot")) { + assertThatThrownBy(() -> f.dsl.execute("DELETE FROM " + table)) + .hasMessageContaining("immutable"); + assertThatThrownBy(() -> f.dsl.execute("TRUNCATE " + table + " CASCADE")) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE " + + table + + " SET " + + (table.equals("automation_runtime_family_classification") + ? "family_id=family_id" + : table.equals("automation_runtime_catalog_non_sql_gap") + ? "gap_id=gap_id" + : "catalog_epoch=catalog_epoch"))) + .hasMessageContaining("immutable"); + } + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO automation_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" + + " SELECT 2,catalog_bytes,catalog_digest FROM automation_runtime_family_catalog_epoch WHERE catalog_epoch=1")) + .hasMessageContaining("exact classified installed schema"); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO automation_runtime_family_catalog_snapshot" + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest)" + + " SELECT ?,target_namespace,request_bytes,request_digest,?,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest" + + " FROM automation_runtime_family_catalog_snapshot WHERE read_request_id=?", + UUID.randomUUID(), + UUID.randomUUID(), + original.request().readRequestId())) + .hasMessageContaining("complete exact request and evidence"); + assertThat(f.count("automation_runtime_family_catalog_snapshot")).isEqualTo(1); + } + } + + @Test + void realProducerReturnsCompleteCorrelatedEvidenceWithoutRuntimeWritesAndRejectsAmbientSql() + throws Exception { + try (Fixture f = fixture(null)) { + Request read = request(); + var service = new AutomationRuntimeFamilyCatalogReadGrpcService(f.owner(), "test"); + var collector = new Collector(); + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") + .orElseThrow(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> + service.readAutomationRuntimeFamilyCatalog( + AutomationRuntimeFamilyCatalogCodec.toRequest(read), collector)); + assertThat(collector.error).isNull(); + assertThat(collector.completed).isTrue(); + var evidence = AutomationRuntimeFamilyCatalogCodec.fromResponse(read, collector.value); + assertThat(f.owner().readExact(read)).isEqualTo(evidence); + for (String table : + List.of( + "script_work_items", + "script_schedule_instances", + "plugin_runtime_states", + "npc_memory", + "faction_standing")) { + assertThat(f.count(table)).isZero(); + } + var transaction = new TransactionTemplate(f.manager); + assertThatThrownBy(() -> transaction.execute(status -> f.owner().read(request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent"); + } + } + + private static Request request() { + return new Request(UUID.randomUUID(), "test"); + } + + private static Fixture fixture(String target) { + return fixture(target, HISTORY); + } + + private static Flyway migration( + DriverManagerDataSource source, String schema, String history, String target) { + var configuration = + Flyway.configure() + .dataSource(source) + .locations(MIGRATIONS, "classpath:db/migration/saga") + .schemas(schema) + .defaultSchema(schema) + .table(history) + .placeholders(Map.of("serviceSchema", schema)); + if (target != null) configuration.target(target); + return configuration.load(); + } + + private static Fixture fixture(String target, String history) { + String schema = "auto_catalog_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + try { + migration(source, schema, history, target).migrate(); + return new Fixture(schema, history, source, dsl, new DataSourceTransactionManager(source)); + } catch (RuntimeException failed) { + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + throw failed; + } + } + + private record Fixture( + String schema, + String history, + DriverManagerDataSource source, + DSLContext dsl, + DataSourceTransactionManager manager) + implements AutoCloseable { + AutomationRuntimeFamilyCatalogRepository owner() { + return new AutomationRuntimeFamilyCatalogRepository(dsl, manager, schema, "test"); + } + + long count(String table) { + return dsl.fetchSingle("SELECT count(*) FROM " + table).get(0, Long.class); + } + + List tables() { + return dsl.fetch( + "SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace" + + " WHERE n.nspname=? AND c.relkind IN ('r','p','f') ORDER BY c.relname", + schema) + .getValues(0, String.class); + } + + String jsonRows(String table) { + return dsl.fetchSingle( + "SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb)::text FROM " + + table + + " t") + .get(0, String.class); + } + + Map rows() { + Map result = new LinkedHashMap<>(); + for (String table : tables()) if (!table.equals(history)) result.put(table, jsonRows(table)); + return result; + } + + List historyRows(boolean excludeNew) { + return dsl.fetch( + "SELECT to_jsonb(h)::text FROM " + + history + + " h" + + (excludeNew ? " WHERE version IS DISTINCT FROM '1004'" : "") + + " ORDER BY installed_rank") + .getValues(0, String.class); + } + + List sequencePositions() { + return dsl.fetch( + "SELECT sequencename||':'||coalesce(last_value::text,'unused') FROM pg_sequences" + + " WHERE schemaname=? ORDER BY sequencename", + schema) + .getValues(0, String.class); + } + + List guards() { + return dsl.fetch( + "SELECT pg_get_triggerdef(t.oid,true) FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid" + + " JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=? AND NOT t.tgisinternal ORDER BY t.tgname", + schema) + .getValues(0, String.class); + } + + void addComponent() { + dsl.execute( + "INSERT INTO automation_runtime_family_classification VALUES" + + " ('npc_memory.key','npc_memory','key','RUNTIME_PAYLOAD','UNKNOWN','STATE_CLASS_UNKNOWN_BLOCKING'," + + "'UNRESOLVED_RETAINED','Controlled added component; still blocking, not S3.')"); + } + + void populatePredecessor() { + // Reuse the existing selected-source fixture and owner to retain a real predecessor receipt. + // Its Account/World inputs are controlled; this is preservation, not genuine intake proof. + var selected = AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + new AutomationEmptySelectedSourceIntakeRepository(dsl) + .retainFresh( + selected.inputs(), + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + "test", selected.authorization(), selected.freezeEvidence())); + dsl.execute( + "INSERT INTO scripts(tenant_id,name,version,definition,base_version_id) VALUES(7001,'retained','patch','{}',1)"); + dsl.execute( + "INSERT INTO script_event_bindings(tenant_id,script_patch_version,event_type,event_schema_version,script_id,target_scope_type,target_scope_id)" + + " VALUES(7001,'patch','onCommand','1','script','ENTITY','7')"); + dsl.execute( + "INSERT INTO script_patch_base_bindings(tenant_id,script_patch_version,base_version_id) VALUES('7001','patch',1)"); + dsl.execute("INSERT INTO factions(tenant_id,name) VALUES(7001,'retained')"); + dsl.execute( + "INSERT INTO faction_standing(tenant_id,character_id,faction_id,reputation,playable_state_key)" + + " VALUES(7001,9,1,42,'instance:legacy')"); + dsl.execute( + "INSERT INTO npc_memory(tenant_id,npc_id,key,value) VALUES(7001,7,'memory','retain')"); + dsl.execute( + "INSERT INTO npc_formations(tenant_id,name,leader_npc_id,formation_type) VALUES(7001,'retained',7,'LINE')"); + dsl.execute("INSERT INTO npc_formation_member(formation_id,npc_id) VALUES(1,8)"); + dsl.execute( + "INSERT INTO plugin_runtime_states(tenant_id,game_instance_id,plugin_id,active_plugin_version_id,plugin_state,status_reason," + + "plugin_activation_epoch,lifecycle_revision) VALUES('7001','legacy','plugin','v1','PLUGIN_STATE_ENABLED','retained',1,1)"); + dsl.execute( + "INSERT INTO script_work_items(tenant_id,game_instance_id,region_id,region_epoch,entity_id,script_id,event_type," + + "event_schema_version,script_patch_version,script_pin_epoch,script_pin_control_plane_request_id,script_event_id,source_service,trigger_mode,status,failure_generation)" + + " VALUES('7001','legacy','region',1,'7','script','onCommand','1','patch',1,'pin','event','game-session-service','NORMAL','DEAD_LETTERED',1)"); + dsl.execute( + "INSERT INTO script_event_audit(tenant_id,game_instance_id,region_id,region_epoch,entity_id,script_id,event_type," + + "event_schema_version,script_patch_version,script_event_id,source_service,trigger_mode,work_item_id,final_stage,final_outcome,final_reason)" + + " VALUES('7001','legacy','region',1,'7','script','onCommand','1','patch','event','game-session-service','NORMAL',1,'DSL_EVAL','failed','retain')"); + dsl.execute( + "INSERT INTO script_event_ingress_audit(tenant_id,event_type,event_schema_version,script_patch_version,script_event_id," + + "source_service,trigger_mode,admitted,admission_outcome,admission_reason)" + + " VALUES('7001','onLoad','1','patch','readiness','automation-scripting-service','NORMAL',false,'failed','retain')"); + dsl.execute( + "INSERT INTO script_handoff_events(event_id,tenant_id,game_instance_id,script_patch_version,script_id,work_item_id,command_ordinal," + + "automation_dispatch_id,target_entity_id,handoff_outcome,handoff_reason)" + + " VALUES('handoff','7001','legacy','patch','script',1,0,'dispatch','7','failed','retain')"); + dsl.execute( + "INSERT INTO script_dead_letter_replay_requests(tenant_id,control_plane_request_id,request_fingerprint,status)" + + " VALUES('7001','replay',?,'COMPLETED')", + "a".repeat(64)); + dsl.execute( + "INSERT INTO script_dead_letter_replay_results(tenant_id,replay_request_id,requested_work_item_id,work_item_id,outcome)" + + " VALUES('7001',1,1,1,'rejected')"); + dsl.execute( + "INSERT INTO script_schedule_instances(tenant_id,game_instance_id,script_patch_version,script_id,event_type,schedule_definition_id," + + "schedule_kind,cadence_value,cadence_unit,materialization_status,schedule_metadata_json,schedule_semantics_hash)" + + " VALUES('7001','legacy','patch','script','onInterval','schedule','INTERVAL',10,'TICK','PENDING_RUNTIME_PROGRESS','{}',?)", + "b".repeat(64)); + dsl.execute( + "INSERT INTO plugin_runtime_request_history(tenant_id,game_instance_id,plugin_id,operation,control_plane_request_id,request_fingerprint," + + "plugin_state,plugin_activation_epoch,lifecycle_revision) VALUES('7001','legacy','plugin','ENABLE','request',?,'PLUGIN_STATE_ENABLED',1,1)", + "c".repeat(64)); + dsl.execute( + "INSERT INTO plugin_runtime_events(event_id,tenant_id,game_instance_id,plugin_id,plugin_state,status_reason)" + + " VALUES('plugin-event','7001','legacy','plugin','PLUGIN_STATE_DISABLED','retain')"); + dsl.execute( + "INSERT INTO automation_admission_request_history(tenant_id,game_instance_id,region_id,mode,control_plane_request_id,request_fingerprint," + + "admission_epoch,outcome,actor_principal,reason) VALUES('7001','legacy','region','NORMAL','barrier',?,1,'APPLIED','controlled','retain')", + "d".repeat(64)); + dsl.execute( + "INSERT INTO automation_admission_states(tenant_id,game_instance_id,region_id) VALUES('7001','legacy','region')"); + dsl.execute( + "INSERT INTO script_patch_pin_projections(tenant_id,game_instance_id,observed_pinned_script_patch_version,script_pin_epoch,last_observed_control_plane_request_id)" + + " VALUES('7001','legacy','patch',1,'pin')"); + dsl.execute( + "INSERT INTO script_patch_instance_rollout_projections(tenant_id,game_instance_id,script_patch_version,rollout_status,status_reason)" + + " VALUES('7001','legacy','patch','OBSERVED','retain')"); + dsl.execute( + "INSERT INTO script_patch_instance_rollout_events(event_id,tenant_id,game_instance_id,script_patch_version,rollout_status,status_reason)" + + " VALUES('rollout','7001','legacy','patch','OBSERVED','retain')"); + dsl.execute( + "INSERT INTO script_schedule_definitions(tenant_id,script_patch_version,script_id,event_type,schedule_definition_id,schedule_kind,cadence_value,cadence_unit," + + "schedule_metadata_json,schedule_semantics_hash) VALUES(7001,'patch','script','onInterval','schedule','INTERVAL',10,'TICK','{}',?)", + "b".repeat(64)); + dsl.execute( + "INSERT INTO script_patch_readiness_projections(tenant_id,script_patch_version,readiness_status,status_reason)" + + " VALUES('7001','patch','FAILED','retain')"); + dsl.execute( + "INSERT INTO automation_empty_source_numeric_key_reservation VALUES('TENANT',7001,'LEGACY_NUMERIC')"); + dsl.execute("INSERT INTO saga_instance(saga_name,state) VALUES('retained','PENDING')"); + dsl.execute( + "INSERT INTO saga_step(instance_id,name,status) VALUES(1,'retained-step','PENDING')"); + } + + @Override + public void close() { + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + private static final class Collector + implements StreamObserver { + private ReadAutomationRuntimeFamilyCatalogResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadAutomationRuntimeFamilyCatalogResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/PluginRuntimeLifecycleFenceIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/PluginRuntimeLifecycleFenceIntegrationTest.java index b6b1a00f88..6c89c99e18 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/PluginRuntimeLifecycleFenceIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/PluginRuntimeLifecycleFenceIntegrationTest.java @@ -10,6 +10,7 @@ import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -62,9 +63,10 @@ void migrateSchema() { DriverManagerDataSource dataSource = dataSource(schema); Flyway.configure() .dataSource(dataSource) - .locations(MIGRATION_LOCATION) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") .schemas(schema) .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) .load() .migrate(); dsl = DSL.using(dataSource, SQLDialect.POSTGRES); @@ -606,9 +608,10 @@ private DSLContext migrateToVersionTwo(String targetSchema) { private void migrateExistingSchemaToLatest(String targetSchema) { Flyway.configure() .dataSource(dataSource(targetSchema)) - .locations(MIGRATION_LOCATION) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") .schemas(targetSchema) .defaultSchema(targetSchema) + .placeholders(Map.of("serviceSchema", targetSchema)) .load() .migrate(); } diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptDefinitionRepositoryIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptDefinitionRepositoryIntegrationTest.java index 2b17da9b3a..3e5bbc663f 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptDefinitionRepositoryIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptDefinitionRepositoryIntegrationTest.java @@ -7,6 +7,7 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; @@ -58,9 +59,10 @@ void migrateSchema() { DriverManagerDataSource dataSource = dataSource(schema); Flyway.configure() .dataSource(dataSource) - .locations(MIGRATION_LOCATION) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") .schemas(schema) .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) .load() .migrate(); dsl = DSL.using(dataSource, SQLDialect.POSTGRES); diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPatchReadinessSingletonIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPatchReadinessSingletonIntegrationTest.java index 15bae5d321..27d3ff7440 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPatchReadinessSingletonIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPatchReadinessSingletonIntegrationTest.java @@ -5,6 +5,7 @@ import java.nio.file.Path; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -429,9 +430,10 @@ private DSLContext migrateToLatest() { schema = newSchemaName(); Flyway.configure() .dataSource(dataSource(schema)) - .locations(MIGRATION_LOCATION) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") .schemas(schema) .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) .load() .migrate(); return schemaDsl(); @@ -453,9 +455,10 @@ private DSLContext migrateToVersionOne() { private void migrateExistingSchemaToLatest() { Flyway.configure() .dataSource(dataSource(schema)) - .locations(MIGRATION_LOCATION) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") .schemas(schema) .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) .load() .migrate(); } diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPinEpochMigrationAndRolloutEventIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPinEpochMigrationAndRolloutEventIntegrationTest.java index ea8caa481b..ae0f36dede 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPinEpochMigrationAndRolloutEventIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPinEpochMigrationAndRolloutEventIntegrationTest.java @@ -10,6 +10,7 @@ import java.nio.file.Path; import java.time.Instant; +import java.util.Map; import java.util.UUID; import net.firedevops.firemud.automationscripting.entity.ScriptEventAudit; import net.firedevops.firemud.automationscripting.entity.ScriptEventIngressAudit; @@ -246,9 +247,10 @@ private DSLContext migrateToLatest() { schema = newSchemaName(); Flyway.configure() .dataSource(dataSource(schema)) - .locations(MIGRATION_LOCATION) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") .schemas(schema) .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) .load() .migrate(); return schemaDsl(); diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/service/impl/ScriptDefinitionServiceTransactionIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/service/impl/ScriptDefinitionServiceTransactionIntegrationTest.java index 421c12d55e..cb0cf7a0e5 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/service/impl/ScriptDefinitionServiceTransactionIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/service/impl/ScriptDefinitionServiceTransactionIntegrationTest.java @@ -10,6 +10,7 @@ import java.nio.file.Path; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -68,9 +69,10 @@ void setUp() { DriverManagerDataSource rawDataSource = dataSource(schema); Flyway.configure() .dataSource(rawDataSource) - .locations(MIGRATION_LOCATION) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") .schemas(schema) .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) .load() .migrate(); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcServiceTest.java new file mode 100644 index 0000000000..eb94ccb81c --- /dev/null +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcServiceTest.java @@ -0,0 +1,188 @@ +package unit.net.firedevops.firemud.automationscripting.runtimecatalog; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.automationscripting.runtimecatalog.AutomationRuntimeFamilyCatalogReadGrpcService; +import net.firedevops.firemud.automationscripting.runtimecatalog.AutomationRuntimeFamilyCatalogRepository; +import net.firedevops.firemud.automationscripting.v1.ReadAutomationRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.automationscripting.v1.ReadAutomationRuntimeFamilyCatalogResponse; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Controlled identity context proves guard order; physical mTLS is separate client proof. */ +class AutomationRuntimeFamilyCatalogReadGrpcServiceTest { + @Test + void exactWorkloadGuardPrecedesMalformedDecodeAndAllSqlIncludingAmbientRoles() { + var repository = mock(AutomationRuntimeFamilyCatalogRepository.class); + var service = new AutomationRuntimeFamilyCatalogReadGrpcService(repository, "test"); + var malformed = + ReadAutomationRuntimeFamilyCatalogRequest.newBuilder() + .addCanonicalRequestBytes(ByteString.copyFromUtf8("bad frame")) + .build(); + assertThat(call(service, malformed, null).error).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(call(service, malformed, peer("account-service", "test")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(call(service, malformed, peer("game-session-service", "other")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + for (int context = 0; context < 4; context++) { + switch (context) { + case 0 -> SessionContext.setContext(UUID.randomUUID().toString(), List.of(), Map.of()); + case 1 -> SessionContext.setContext(null, List.of("platformAdmin"), Map.of()); + case 2 -> SessionContext.setContext(null, List.of(), Map.of("42", List.of("tenantAdmin"))); + default -> + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-session-service", "controlled"); + } + try { + assertThat(call(service, malformed, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + } + verifyNoInteractions(repository); + } + + @Test + void ambientSqlAndSynchronizationRefuseBeforeDecode() { + var repository = mock(AutomationRuntimeFamilyCatalogRepository.class); + var service = new AutomationRuntimeFamilyCatalogReadGrpcService(repository, "test"); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThat( + call( + service, + ReadAutomationRuntimeFamilyCatalogRequest.getDefaultInstance(), + peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThat( + call( + service, + ReadAutomationRuntimeFamilyCatalogRequest.getDefaultInstance(), + peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(repository); + } + + @Test + void authenticatedWrongNamespaceMalformedAndOversizedRequestsRefuseBeforeSql() { + var repository = mock(AutomationRuntimeFamilyCatalogRepository.class); + var service = new AutomationRuntimeFamilyCatalogReadGrpcService(repository, "test"); + var peer = peer("game-session-service", "test"); + assertThat( + call(service, ReadAutomationRuntimeFamilyCatalogRequest.getDefaultInstance(), peer) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + call( + service, + AutomationRuntimeFamilyCatalogCodec.toRequest( + new Request(UUID.randomUUID(), "other")), + peer) + .error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + call( + service, + ReadAutomationRuntimeFamilyCatalogRequest.newBuilder() + .addCanonicalRequestBytes(ByteString.copyFrom(new byte[1025])) + .build(), + peer) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void authenticatedRequestReachesOwnerButDriftAndStorageOutageNeverBecomeEmptyEvidence() { + var repository = mock(AutomationRuntimeFamilyCatalogRepository.class); + var service = new AutomationRuntimeFamilyCatalogReadGrpcService(repository, "test"); + var read = new Request(UUID.randomUUID(), "test"); + var wire = AutomationRuntimeFamilyCatalogCodec.toRequest(read); + when(repository.read(read)) + .thenThrow( + new AutomationRuntimeFamilyCatalogRepository.CatalogConflictException( + "private details")); + Collector drift = call(service, wire, peer("game-session-service", "test")); + assertThat(drift.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(drift.value).isNull(); + assertThat(drift.description).doesNotContain("private details"); + verify(repository).read(read); + doThrow( + new org.jooq.exception.DataAccessException( + "private SQL", new SQLException("private SQL", "08006"))) + .when(repository) + .read(read); + Collector outage = call(service, wire, peer("game-session-service", "test")); + assertThat(outage.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(outage.value).isNull(); + assertThat(outage.description).doesNotContain("private SQL"); + } + + private static Collector call( + AutomationRuntimeFamilyCatalogReadGrpcService service, + ReadAutomationRuntimeFamilyCatalogRequest request, + GrpcPeerIdentity peer) { + var collector = new Collector(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run(() -> service.readAutomationRuntimeFamilyCatalog(request, collector)); + return collector; + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static final class Collector + implements StreamObserver { + private Status.Code error; + private String description; + private ReadAutomationRuntimeFamilyCatalogResponse value; + + @Override + public void onNext(ReadAutomationRuntimeFamilyCatalogResponse next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + assertThat(value).isNull(); + error = Status.fromThrowable(failure).getCode(); + description = Status.fromThrowable(failure).getDescription(); + } + + @Override + public void onCompleted() { + assertThat(value).isNotNull(); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java new file mode 100644 index 0000000000..fbfae87a80 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java @@ -0,0 +1,400 @@ +package net.firedevops.firemud.common.automation; + +import com.google.protobuf.ByteString; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Exact Automation SQL source classification; neither enrollment nor a FRESH state manifest. */ +public final class AutomationRuntimeFamilyCatalog { + public static final String OWNER = "automation-scripting-service"; + public static final String SCHEMA = "automation-runtime-family-catalog/v1"; + public static final int MAX_CATALOG_BYTES = 2 * 1024 * 1024; + public static final int MAX_FAMILIES = 512; + public static final int MAX_FACTS = 16384; + public static final int MAX_NON_SQL_GAPS = 32; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public enum Role { + RUNTIME_PAYLOAD, + SOURCE, + CONTROL, + AUDIT, + PROVENANCE, + CATALOG + } + + /** UNKNOWN/UNRESOLVED are blocking facts, never implicit S3 or a new replacement class. */ + public enum StateClass { + S2, + UNKNOWN, + UNRESOLVED, + NOT_PAYLOAD + } + + public enum FreshDisposition { + STATE_CLASS_UNKNOWN_BLOCKING, + NAMESPACE_MAPPING_BLOCKING, + OWNERSHIP_DRIFT_BLOCKING, + RUNTIME_EVIDENCE_BLOCKING, + SOURCE_ONLY, + CONTROL_ONLY, + AUDIT_ONLY, + PROVENANCE_ONLY, + CATALOG_ONLY + } + + public enum RetentionDisposition { + OWNER_POLICY_RETAINED, + UNRESOLVED_RETAINED, + IMMUTABLE_RETAINED + } + + public enum GapId { + CAPACITY_LEASE_ACCOUNTING, + CENTRAL_RESET_ACL_REGISTRATION, + DURABLE_CHARGE_MARKERS, + QUEUE_DISCOVERY_AND_ENCODING, + QUEUE_POINTER_RETENTION + } + + public enum GapDisposition { + UNRESOLVED_BLOCKING, + UNSUPPORTED_BLOCKING + } + + public enum FactKind { + TABLE, + COLUMN, + CONSTRAINT, + INDEX, + TRIGGER, + ROUTINE, + SEQUENCE, + VIEW, + TYPE, + POLICY, + RULE, + MIGRATION + } + + public record Family( + String familyId, + String relation, + String component, + Role role, + StateClass stateClass, + FreshDisposition freshDisposition, + RetentionDisposition retentionDisposition, + String ownerConsequence) { + public Family { + identifier(relation); + Objects.requireNonNull(component, "component"); + if (!component.isEmpty()) identifier(component); + if (!Objects.equals(familyId, relation + (component.isEmpty() ? "" : "." + component))) { + throw new IllegalArgumentException("Family must name its exact installed component"); + } + Objects.requireNonNull(role, "role"); + Objects.requireNonNull(stateClass, "stateClass"); + Objects.requireNonNull(freshDisposition, "freshDisposition"); + Objects.requireNonNull(retentionDisposition, "retentionDisposition"); + consequence(ownerConsequence); + boolean coherent = + switch (freshDisposition) { + case STATE_CLASS_UNKNOWN_BLOCKING -> + role == Role.RUNTIME_PAYLOAD && stateClass == StateClass.UNKNOWN; + case NAMESPACE_MAPPING_BLOCKING -> + role == Role.RUNTIME_PAYLOAD && stateClass == StateClass.S2; + case OWNERSHIP_DRIFT_BLOCKING -> + role == Role.RUNTIME_PAYLOAD && stateClass == StateClass.UNRESOLVED; + case RUNTIME_EVIDENCE_BLOCKING -> + (role == Role.CONTROL || role == Role.AUDIT || role == Role.PROVENANCE) + && stateClass == StateClass.NOT_PAYLOAD; + case SOURCE_ONLY -> role == Role.SOURCE && stateClass == StateClass.NOT_PAYLOAD; + case CONTROL_ONLY -> role == Role.CONTROL && stateClass == StateClass.NOT_PAYLOAD; + case AUDIT_ONLY -> role == Role.AUDIT && stateClass == StateClass.NOT_PAYLOAD; + case PROVENANCE_ONLY -> role == Role.PROVENANCE && stateClass == StateClass.NOT_PAYLOAD; + case CATALOG_ONLY -> role == Role.CATALOG && stateClass == StateClass.NOT_PAYLOAD; + }; + if (!coherent) throw new IllegalArgumentException("Contradictory Automation disposition"); + if (role == Role.CATALOG && retentionDisposition != RetentionDisposition.IMMUTABLE_RETAINED) { + throw new IllegalArgumentException("Catalog evidence must remain retained and immutable"); + } + } + } + + /** Explicit known limitations, not an enumeration or census of Redis keys. */ + public record NonSqlGap(GapId id, GapDisposition disposition, String ownerConsequence) { + public NonSqlGap { + Objects.requireNonNull(id, "id"); + Objects.requireNonNull(disposition, "disposition"); + consequence(ownerConsequence); + } + } + + public record SchemaFact(FactKind kind, String identity, String definitionDigest) { + public SchemaFact { + Objects.requireNonNull(kind, "kind"); + if (identity == null + || identity.isBlank() + || identity.length() > 8192 + || identity.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Invalid schema fact identity"); + } + requireDigest(definitionDigest); + } + } + + public record Request(UUID readRequestId, String targetNamespace) { + public Request { + requireUuid(readRequestId); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Exact workload namespace required"); + } + } + } + + public record Evidence(Request request, UUID snapshotId, AutomationRuntimeFamilyCatalog catalog) { + public Evidence { + Objects.requireNonNull(request, "request"); + requireUuid(snapshotId); + Objects.requireNonNull(catalog, "catalog"); + } + + public String digest() { + return sha256(AutomationRuntimeFamilyCatalogCodec.evidenceBytes(this)); + } + } + + private final long catalogEpoch; + private final List families; + private final List schemaFacts; + private final List nonSqlGaps; + private final ByteString exactBytes; + + private AutomationRuntimeFamilyCatalog( + long epoch, + List families, + List facts, + List gaps, + byte[] bytes) { + catalogEpoch = epoch; + this.families = List.copyOf(families); + schemaFacts = List.copyOf(facts); + nonSqlGaps = List.copyOf(gaps); + exactBytes = ByteString.copyFrom(bytes); + } + + public long catalogEpoch() { + return catalogEpoch; + } + + public List families() { + return families; + } + + public List schemaFacts() { + return schemaFacts; + } + + public List nonSqlGaps() { + return nonSqlGaps; + } + + public byte[] exactBytes() { + return exactBytes.toByteArray(); + } + + public String digest() { + return sha256(exactBytes.toByteArray()); + } + + @Override + public boolean equals(Object other) { + return other instanceof AutomationRuntimeFamilyCatalog catalog + && exactBytes.equals(catalog.exactBytes); + } + + @Override + public int hashCode() { + return exactBytes.hashCode(); + } + + /** Retains original PostgreSQL-sealed bytes; no constructor can assert schema completeness. */ + public static AutomationRuntimeFamilyCatalog fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CATALOG_BYTES) { + throw new IllegalArgumentException("Automation catalog exceeds complete-source bound"); + } + try { + String decoded = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + JsonNode root = JSON.readTree(decoded); + fields( + root, Set.of("schema", "owner", "catalogEpoch", "families", "schemaFacts", "nonSqlGaps")); + if (!SCHEMA.equals(text(root, "schema")) || !OWNER.equals(text(root, "owner"))) { + throw new IllegalArgumentException("Unsupported Automation schema/owner"); + } + String epochText = text(root, "catalogEpoch"); + if (!epochText.matches("[1-9][0-9]{0,18}")) + throw new IllegalArgumentException("Invalid epoch"); + long epoch = Long.parseLong(epochText); + var families = new ArrayList(); + var facts = new ArrayList(); + var gaps = new ArrayList(); + array(root.get("families"), MAX_FAMILIES); + String previous = ""; + for (JsonNode node : root.get("families")) { + fields( + node, + Set.of( + "familyId", + "relation", + "component", + "role", + "stateClass", + "freshDisposition", + "retentionDisposition", + "ownerConsequence")); + Family family = + new Family( + text(node, "familyId"), + text(node, "relation"), + text(node, "component"), + Role.valueOf(text(node, "role")), + StateClass.valueOf(text(node, "stateClass")), + FreshDisposition.valueOf(text(node, "freshDisposition")), + RetentionDisposition.valueOf(text(node, "retentionDisposition")), + text(node, "ownerConsequence")); + if (previous.compareTo(family.familyId()) >= 0) + throw new IllegalArgumentException("Unordered/duplicate family"); + previous = family.familyId(); + families.add(family); + } + array(root.get("schemaFacts"), MAX_FACTS); + previous = ""; + Set tables = new HashSet<>(); + Set columns = new HashSet<>(); + for (JsonNode node : root.get("schemaFacts")) { + fields(node, Set.of("kind", "identity", "definitionDigest")); + SchemaFact fact = + new SchemaFact( + FactKind.valueOf(text(node, "kind")), + text(node, "identity"), + text(node, "definitionDigest")); + String key = fact.kind().name() + "/" + fact.identity(); + if (previous.compareTo(key) >= 0) + throw new IllegalArgumentException("Unordered/duplicate schema fact"); + previous = key; + if (fact.kind() == FactKind.TABLE) tables.add(fact.identity()); + if (fact.kind() == FactKind.COLUMN) columns.add(fact.identity()); + facts.add(fact); + } + Set declared = new HashSet<>(); + for (Family family : families) { + if (!tables.contains(family.relation())) + throw new IllegalArgumentException("Missing family table"); + if (family.component().isEmpty()) declared.add(family.relation()); + else if (!columns.contains(family.familyId())) + throw new IllegalArgumentException("Missing family component"); + } + if (!tables.equals(declared) || tables.isEmpty()) { + throw new IllegalArgumentException("Every installed table needs an explicit disposition"); + } + array(root.get("nonSqlGaps"), MAX_NON_SQL_GAPS); + previous = ""; + for (JsonNode node : root.get("nonSqlGaps")) { + fields(node, Set.of("id", "disposition", "ownerConsequence")); + NonSqlGap gap = + new NonSqlGap( + GapId.valueOf(text(node, "id")), + GapDisposition.valueOf(text(node, "disposition")), + text(node, "ownerConsequence")); + if (previous.compareTo(gap.id().name()) >= 0) + throw new IllegalArgumentException("Unordered/duplicate non-SQL gap"); + previous = gap.id().name(); + gaps.add(gap); + } + return new AutomationRuntimeFamilyCatalog(epoch, families, facts, gaps, bytes); + } catch (java.io.IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Invalid closed Automation catalog", invalid); + } + } + + static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) + throw new IllegalArgumentException("Non-nil UUID required"); + } + + static void requireDigest(String value) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException("SHA-256 required"); + } + + public static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 required by Java", impossible); + } + } + + private static void consequence(String value) { + if (value == null + || value.isBlank() + || value.length() > 1024 + || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Bounded explicit owner consequence required"); + } + } + + private static void identifier(String value) { + if (value == null || !value.matches("[a-z][a-z0-9_]{0,62}")) + throw new IllegalArgumentException("Schema identifier required"); + } + + private static void fields(JsonNode node, Set expected) { + if (node == null || !node.isObject()) + throw new IllegalArgumentException("Closed object required"); + Set actual = new HashSet<>(); + node.propertyNames().forEach(actual::add); + if (!actual.equals(expected)) + throw new IllegalArgumentException("Unknown or missing catalog field"); + } + + private static String text(JsonNode node, String key) { + JsonNode value = node.get(key); + if (value == null || !value.isTextual()) + throw new IllegalArgumentException("Text field required"); + return value.asText(); + } + + private static void array(JsonNode node, int maximum) { + if (node == null || !node.isArray() || node.isEmpty() || node.size() > maximum) { + throw new IllegalArgumentException("Complete bounded catalog array required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogCodec.java new file mode 100644 index 0000000000..a371cab369 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogCodec.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.common.automation; + +import com.google.protobuf.ByteString; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.automationscripting.v1.ReadAutomationRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.automationscripting.v1.ReadAutomationRuntimeFamilyCatalogResponse; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Request; + +/** Purpose-specific closed framing; no compatibility, generic parser or numeric fallback. */ +public final class AutomationRuntimeFamilyCatalogCodec { + public static final int MAX_REQUEST_BYTES = 1024; + public static final int MAX_RESPONSE_BYTES = + AutomationRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 4096; + private static final int REQUEST_V1 = 0x41435231; + private static final int EVIDENCE_V1 = 0x41434531; + + private AutomationRuntimeFamilyCatalogCodec() {} + + public static byte[] requestBytes(Request request) { + return encode( + out -> { + out.writeInt(REQUEST_V1); + uuid(out, request.readRequestId()); + bytes(out, request.targetNamespace().getBytes(StandardCharsets.US_ASCII)); + }); + } + + public static Request requestFromStored(byte[] bytes) { + try (var in = input(bytes, MAX_REQUEST_BYTES)) { + if (in.readInt() != REQUEST_V1) throw new IllegalArgumentException("Unsupported read schema"); + Request result = new Request(uuid(in), new String(bytes(in, 63), StandardCharsets.US_ASCII)); + if (in.available() != 0 || !Arrays.equals(bytes, requestBytes(result))) { + throw new IllegalArgumentException("Noncanonical Automation catalog request"); + } + return result; + } catch (IOException invalid) { + throw new IllegalArgumentException("Incomplete Automation catalog request", invalid); + } + } + + public static byte[] evidenceBytes(Evidence evidence) { + byte[] result = + encode( + out -> { + out.writeInt(EVIDENCE_V1); + bytes(out, requestBytes(evidence.request())); + uuid(out, evidence.snapshotId()); + bytes(out, evidence.catalog().digest().getBytes(StandardCharsets.US_ASCII)); + bytes(out, evidence.catalog().exactBytes()); + }); + if (result.length > MAX_RESPONSE_BYTES) + throw new IllegalArgumentException("Oversized complete catalog evidence"); + return result; + } + + public static Evidence evidenceFromStored(byte[] bytes) { + try (var in = input(bytes, MAX_RESPONSE_BYTES)) { + if (in.readInt() != EVIDENCE_V1) + throw new IllegalArgumentException("Unsupported evidence schema"); + Request request = requestFromStored(bytes(in, MAX_REQUEST_BYTES)); + UUID snapshotId = uuid(in); + String digest = new String(bytes(in, 71), StandardCharsets.US_ASCII); + AutomationRuntimeFamilyCatalog catalog = + AutomationRuntimeFamilyCatalog.fromStored( + bytes(in, AutomationRuntimeFamilyCatalog.MAX_CATALOG_BYTES)); + Evidence result = new Evidence(request, snapshotId, catalog); + if (in.available() != 0 + || !digest.equals(catalog.digest()) + || !Arrays.equals(bytes, evidenceBytes(result))) { + throw new IllegalArgumentException("Changed/noncanonical catalog evidence"); + } + return result; + } catch (IOException invalid) { + throw new IllegalArgumentException("Incomplete Automation catalog evidence", invalid); + } + } + + public static ReadAutomationRuntimeFamilyCatalogRequest toRequest(Request request) { + return ReadAutomationRuntimeFamilyCatalogRequest.newBuilder() + .addCanonicalRequestBytes(ByteString.copyFrom(requestBytes(request))) + .build(); + } + + /** Authenticate the exact workload before invoking this decoder. */ + public static Request fromRequest(ReadAutomationRuntimeFamilyCatalogRequest request) { + if (request == null + || request.getSerializedSize() > MAX_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty() + || request.getCanonicalRequestBytesCount() != 1) { + throw new IllegalArgumentException("One bounded closed catalog request required"); + } + return requestFromStored(request.getCanonicalRequestBytes(0).toByteArray()); + } + + public static ReadAutomationRuntimeFamilyCatalogResponse toResponse( + Request request, Evidence evidence) { + if (!request.equals(evidence.request())) + throw new IllegalArgumentException("Changed catalog read correlation"); + var response = + ReadAutomationRuntimeFamilyCatalogResponse.newBuilder() + .addCanonicalResponseBytes(ByteString.copyFrom(evidenceBytes(evidence))) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) + throw new IllegalArgumentException("Oversized response"); + return response; + } + + public static Evidence fromResponse( + Request request, ReadAutomationRuntimeFamilyCatalogResponse response) { + if (response == null + || response.getSerializedSize() > MAX_RESPONSE_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || response.getCanonicalResponseBytesCount() != 1) { + throw new IllegalArgumentException("One complete bounded catalog response required"); + } + Evidence result = evidenceFromStored(response.getCanonicalResponseBytes(0).toByteArray()); + if (!request.equals(result.request())) + throw new IllegalArgumentException("Changed catalog read correlation"); + return result; + } + + private static DataInputStream input(byte[] value, int maximum) { + if (value == null || value.length == 0 || value.length > maximum) + throw new IllegalArgumentException("Frame bound exceeded"); + return new DataInputStream(new ByteArrayInputStream(value)); + } + + private static byte[] bytes(DataInputStream in, int maximum) throws IOException { + int length = in.readInt(); + if (length < 0 || length > maximum || length > in.available()) + throw new IllegalArgumentException("Invalid field bound"); + return in.readNBytes(length); + } + + private static void bytes(DataOutputStream out, byte[] value) throws IOException { + out.writeInt(value.length); + out.write(value); + } + + private static UUID uuid(DataInputStream in) throws IOException { + UUID result = new UUID(in.readLong(), in.readLong()); + AutomationRuntimeFamilyCatalog.requireUuid(result); + return result; + } + + private static void uuid(DataOutputStream out, UUID value) throws IOException { + out.writeLong(value.getMostSignificantBits()); + out.writeLong(value.getLeastSignificantBits()); + } + + private interface Encoder { + void write(DataOutputStream out) throws IOException; + } + + private static byte[] encode(Encoder encoder) { + try (var buffer = new ByteArrayOutputStream(); + var out = new DataOutputStream(buffer)) { + encoder.write(out); + out.flush(); + return buffer.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException("Memory frame encoding failed", impossible); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java new file mode 100644 index 0000000000..5d0c113707 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java @@ -0,0 +1,360 @@ +package net.firedevops.firemud.common.entity; + +import com.google.protobuf.ByteString; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Exact Entity-local schema facts. Conditional/unresolved entries never qualify runtime state. */ +public final class EntityRuntimeFamilyCatalog { + public static final String OWNER = "entity-management-service"; + public static final String SCHEMA = "entity-runtime-family-catalog/v1"; + public static final int MAX_CATALOG_BYTES = 2 * 1024 * 1024; + public static final int MAX_FAMILIES = 512; + public static final int MAX_FACTS = 16384; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public enum Role { + RUNTIME_PAYLOAD, + MIXED, + SOURCE, + IDENTITY, + ASSIGNMENT, + CREATION, + DISCOVERY, + RETENTION, + PROJECTION, + REPLAY, + AUDIT, + CONTROL, + PROVENANCE, + ALLOCATOR, + HISTORY, + CATALOG + } + + public enum StateClass { + S1, + S2, + S3, + CONDITIONAL_S1_S2, + CONDITIONAL_HOLDER, + UNRESOLVED, + NOT_PAYLOAD + } + + /** These are catalog facts, not runtime initialization outcomes. */ + public enum FreshDisposition { + PROVISIONAL_NAMESPACE, + TEMPLATE_MAPPING_REQUIRED, + BLOCKING_NAMESPACE_REMAP, + BLOCKING_HOLDER_CLOSURE, + BLOCKING_MIXED_NPC, + BLOCKING_ALLOCATOR_CLASS, + GROUND_ONLY_S3, + PROJECTION_S3_RETAIN_LINEAGE, + AUTHORED_SOURCE_ONLY, + SELECTED_EMPTY_SOURCE_ONLY, + IDENTITY_ONLY, + ASSIGNMENT_ONLY, + CREATE_ONLY, + DISCOVERY_ONLY, + RETENTION_ONLY, + REPLAY_ONLY, + AUDIT_ONLY, + CONTROL_ONLY, + PROVENANCE_ONLY, + HISTORY_ONLY, + CATALOG_ONLY + } + + public enum FactKind { + TABLE, + COLUMN, + CONSTRAINT, + INDEX, + TRIGGER, + ROUTINE, + SEQUENCE, + VIEW, + TYPE, + POLICY, + RULE, + MIGRATION + } + + public record Family( + String familyId, + String relation, + String component, + Role role, + StateClass stateClass, + FreshDisposition freshDisposition) { + public Family { + identifier(relation); + Objects.requireNonNull(component, "component"); + if (!component.isEmpty()) identifier(component); + if (!Objects.equals(familyId, relation + (component.isEmpty() ? "" : "." + component))) + throw new IllegalArgumentException("Family must name its exact physical component"); + Objects.requireNonNull(role, "role"); + Objects.requireNonNull(stateClass, "stateClass"); + Objects.requireNonNull(freshDisposition, "freshDisposition"); + Role expectedRole = + switch (freshDisposition) { + case PROVISIONAL_NAMESPACE, + TEMPLATE_MAPPING_REQUIRED, + BLOCKING_NAMESPACE_REMAP, + BLOCKING_HOLDER_CLOSURE, + GROUND_ONLY_S3 -> + Role.RUNTIME_PAYLOAD; + case BLOCKING_MIXED_NPC -> Role.MIXED; + case BLOCKING_ALLOCATOR_CLASS -> Role.ALLOCATOR; + case PROJECTION_S3_RETAIN_LINEAGE -> Role.PROJECTION; + case AUTHORED_SOURCE_ONLY, SELECTED_EMPTY_SOURCE_ONLY -> Role.SOURCE; + case IDENTITY_ONLY -> Role.IDENTITY; + case ASSIGNMENT_ONLY -> Role.ASSIGNMENT; + case CREATE_ONLY -> Role.CREATION; + case DISCOVERY_ONLY -> Role.DISCOVERY; + case RETENTION_ONLY -> Role.RETENTION; + case REPLAY_ONLY -> Role.REPLAY; + case AUDIT_ONLY -> Role.AUDIT; + case CONTROL_ONLY -> Role.CONTROL; + case PROVENANCE_ONLY -> Role.PROVENANCE; + case HISTORY_ONLY -> Role.HISTORY; + case CATALOG_ONLY -> Role.CATALOG; + }; + StateClass expectedClass = + switch (freshDisposition) { + case PROVISIONAL_NAMESPACE -> StateClass.S1; + case TEMPLATE_MAPPING_REQUIRED -> StateClass.S2; + case BLOCKING_NAMESPACE_REMAP -> StateClass.CONDITIONAL_S1_S2; + case BLOCKING_HOLDER_CLOSURE -> StateClass.CONDITIONAL_HOLDER; + case BLOCKING_MIXED_NPC, BLOCKING_ALLOCATOR_CLASS -> StateClass.UNRESOLVED; + case GROUND_ONLY_S3, PROJECTION_S3_RETAIN_LINEAGE -> StateClass.S3; + default -> StateClass.NOT_PAYLOAD; + }; + if (role != expectedRole || stateClass != expectedClass) + throw new IllegalArgumentException("Contradictory Entity family classification"); + } + + /** The owning contract's singular character family has one physical/wire spelling. */ + public String logicalFamily() { + return relation.equals("characters") ? "character" : relation; + } + } + + public record SchemaFact(FactKind kind, String identity, String definitionDigest) { + public SchemaFact { + Objects.requireNonNull(kind, "kind"); + if (identity == null + || identity.isBlank() + || identity.length() > 8192 + || identity.codePoints().anyMatch(Character::isISOControl)) + throw new IllegalArgumentException("Invalid schema fact identity"); + requireDigest(definitionDigest); + } + } + + public record Request(UUID readRequestId, String targetNamespace) { + public Request { + requireUuid(readRequestId); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException("Exact workload namespace required"); + } + } + + public record Evidence(Request request, UUID snapshotId, EntityRuntimeFamilyCatalog catalog) { + public Evidence { + Objects.requireNonNull(request, "request"); + requireUuid(snapshotId); + Objects.requireNonNull(catalog, "catalog"); + } + + public String digest() { + return sha256(EntityRuntimeFamilyCatalogCodec.evidenceBytes(this)); + } + } + + private final long catalogEpoch; + private final List families; + private final List schemaFacts; + private final ByteString exactBytes; + + private EntityRuntimeFamilyCatalog( + long epoch, List families, List facts, byte[] bytes) { + catalogEpoch = epoch; + this.families = List.copyOf(families); + schemaFacts = List.copyOf(facts); + exactBytes = ByteString.copyFrom(bytes); + } + + public long catalogEpoch() { + return catalogEpoch; + } + + public List families() { + return families; + } + + public List schemaFacts() { + return schemaFacts; + } + + public byte[] exactBytes() { + return exactBytes.toByteArray(); + } + + public String digest() { + return sha256(exactBytes.toByteArray()); + } + + @Override + public boolean equals(Object other) { + return other instanceof EntityRuntimeFamilyCatalog catalog + && exactBytes.equals(catalog.exactBytes); + } + + @Override + public int hashCode() { + return exactBytes.hashCode(); + } + + /** Closed bounded parsing retains original PostgreSQL bytes rather than recanonicalizing. */ + public static EntityRuntimeFamilyCatalog fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CATALOG_BYTES) + throw new IllegalArgumentException("Entity catalog exceeds complete-source bound"); + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + JsonNode root = JSON.readTree(json); + fields(root, Set.of("schema", "owner", "catalogEpoch", "families", "schemaFacts")); + if (!SCHEMA.equals(text(root, "schema")) || !OWNER.equals(text(root, "owner"))) + throw new IllegalArgumentException("Unsupported Entity catalog schema/owner"); + String epochText = text(root, "catalogEpoch"); + if (!epochText.matches("[1-9][0-9]{0,18}")) + throw new IllegalArgumentException("Invalid epoch"); + long epoch = Long.parseLong(epochText); + var families = new ArrayList(); + var facts = new ArrayList(); + array(root.get("families"), MAX_FAMILIES); + String previous = ""; + for (JsonNode node : root.get("families")) { + fields( + node, + Set.of("familyId", "relation", "component", "role", "stateClass", "freshDisposition")); + Family family = + new Family( + text(node, "familyId"), + text(node, "relation"), + text(node, "component"), + Role.valueOf(text(node, "role")), + StateClass.valueOf(text(node, "stateClass")), + FreshDisposition.valueOf(text(node, "freshDisposition"))); + if (previous.compareTo(family.familyId()) >= 0) + throw new IllegalArgumentException("Unordered/duplicate family"); + previous = family.familyId(); + families.add(family); + } + array(root.get("schemaFacts"), MAX_FACTS); + previous = ""; + Set tables = new HashSet<>(); + Set columns = new HashSet<>(); + for (JsonNode node : root.get("schemaFacts")) { + fields(node, Set.of("kind", "identity", "definitionDigest")); + SchemaFact fact = + new SchemaFact( + FactKind.valueOf(text(node, "kind")), + text(node, "identity"), + text(node, "definitionDigest")); + String key = fact.kind().name() + "/" + fact.identity(); + if (previous.compareTo(key) >= 0) + throw new IllegalArgumentException("Unordered/duplicate schema fact"); + previous = key; + if (fact.kind() == FactKind.TABLE) tables.add(fact.identity()); + if (fact.kind() == FactKind.COLUMN) columns.add(fact.identity()); + facts.add(fact); + } + Set declaredTables = new HashSet<>(); + for (Family family : families) { + if (!tables.contains(family.relation())) + throw new IllegalArgumentException("Missing family table"); + if (family.component().isEmpty()) declaredTables.add(family.relation()); + else if (!columns.contains(family.familyId())) + throw new IllegalArgumentException("Missing family component"); + } + if (!tables.equals(declaredTables) || tables.isEmpty()) + throw new IllegalArgumentException("Every installed table needs an explicit disposition"); + return new EntityRuntimeFamilyCatalog(epoch, families, facts, bytes); + } catch (java.io.IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Invalid closed Entity catalog", invalid); + } + } + + static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) + throw new IllegalArgumentException("Non-nil UUID required"); + } + + static void requireDigest(String value) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException("SHA-256 required"); + } + + public static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 required by Java", impossible); + } + } + + private static void identifier(String value) { + if (value == null || !value.matches("[a-z][a-z0-9_]{0,62}")) + throw new IllegalArgumentException("Schema identifier required"); + } + + private static void fields(JsonNode node, Set expected) { + if (node == null || !node.isObject()) + throw new IllegalArgumentException("Closed object required"); + Set actual = new HashSet<>(); + node.propertyNames().forEach(actual::add); + if (!actual.equals(expected)) + throw new IllegalArgumentException("Unknown or missing catalog field"); + } + + private static String text(JsonNode node, String key) { + JsonNode value = node.get(key); + if (value == null || !value.isTextual()) + throw new IllegalArgumentException("Text field required"); + return value.asText(); + } + + private static void array(JsonNode node, int maximum) { + if (node == null || !node.isArray() || node.isEmpty() || node.size() > maximum) + throw new IllegalArgumentException("Complete bounded catalog array required"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogCodec.java new file mode 100644 index 0000000000..e5468ec88f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogCodec.java @@ -0,0 +1,168 @@ +package net.firedevops.firemud.common.entity; + +import com.google.protobuf.ByteString; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.entitymanagement.v1.ReadEntityRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadEntityRuntimeFamilyCatalogResponse; + +/** Purpose-specific closed framing; never a generic registry or compatibility decoder. */ +public final class EntityRuntimeFamilyCatalogCodec { + public static final int MAX_REQUEST_BYTES = 1024; + public static final int MAX_RESPONSE_BYTES = EntityRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 4096; + private static final int REQUEST_V1 = 0x45435231; + private static final int EVIDENCE_V1 = 0x45434531; + + private EntityRuntimeFamilyCatalogCodec() {} + + public static byte[] requestBytes(Request request) { + return encode( + out -> { + out.writeInt(REQUEST_V1); + uuid(out, request.readRequestId()); + bytes(out, request.targetNamespace().getBytes(StandardCharsets.US_ASCII)); + }); + } + + public static Request requestFromStored(byte[] bytes) { + try (var in = input(bytes, MAX_REQUEST_BYTES)) { + if (in.readInt() != REQUEST_V1) throw new IllegalArgumentException("Unsupported read schema"); + Request result = new Request(uuid(in), new String(bytes(in, 63), StandardCharsets.US_ASCII)); + if (in.available() != 0 || !Arrays.equals(bytes, requestBytes(result))) + throw new IllegalArgumentException("Noncanonical Entity catalog request"); + return result; + } catch (IOException invalid) { + throw new IllegalArgumentException("Incomplete Entity catalog request", invalid); + } + } + + public static byte[] evidenceBytes(Evidence evidence) { + byte[] result = + encode( + out -> { + out.writeInt(EVIDENCE_V1); + bytes(out, requestBytes(evidence.request())); + uuid(out, evidence.snapshotId()); + bytes(out, evidence.catalog().digest().getBytes(StandardCharsets.US_ASCII)); + bytes(out, evidence.catalog().exactBytes()); + }); + if (result.length > MAX_RESPONSE_BYTES) + throw new IllegalArgumentException("Oversized complete catalog evidence"); + return result; + } + + public static Evidence evidenceFromStored(byte[] bytes) { + try (var in = input(bytes, MAX_RESPONSE_BYTES)) { + if (in.readInt() != EVIDENCE_V1) + throw new IllegalArgumentException("Unsupported evidence schema"); + Request request = requestFromStored(bytes(in, MAX_REQUEST_BYTES)); + UUID snapshotId = uuid(in); + String digest = new String(bytes(in, 71), StandardCharsets.US_ASCII); + var catalog = + EntityRuntimeFamilyCatalog.fromStored( + bytes(in, EntityRuntimeFamilyCatalog.MAX_CATALOG_BYTES)); + Evidence result = new Evidence(request, snapshotId, catalog); + if (in.available() != 0 + || !digest.equals(catalog.digest()) + || !Arrays.equals(bytes, evidenceBytes(result))) + throw new IllegalArgumentException("Changed/noncanonical catalog evidence"); + return result; + } catch (IOException invalid) { + throw new IllegalArgumentException("Incomplete Entity catalog evidence", invalid); + } + } + + public static ReadEntityRuntimeFamilyCatalogRequest toRequest(Request request) { + return ReadEntityRuntimeFamilyCatalogRequest.newBuilder() + .addCanonicalRequestBytes(ByteString.copyFrom(requestBytes(request))) + .build(); + } + + /** Workload authentication must precede decoding. */ + public static Request fromRequest(ReadEntityRuntimeFamilyCatalogRequest request) { + if (request == null + || request.getSerializedSize() > MAX_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty() + || request.getCanonicalRequestBytesCount() != 1) + throw new IllegalArgumentException("One bounded closed catalog request required"); + return requestFromStored(request.getCanonicalRequestBytes(0).toByteArray()); + } + + public static ReadEntityRuntimeFamilyCatalogResponse toResponse( + Request request, Evidence evidence) { + if (!request.equals(evidence.request())) + throw new IllegalArgumentException("Changed catalog read correlation"); + var response = + ReadEntityRuntimeFamilyCatalogResponse.newBuilder() + .addCanonicalResponseBytes(ByteString.copyFrom(evidenceBytes(evidence))) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) + throw new IllegalArgumentException("Oversized response"); + return response; + } + + public static Evidence fromResponse( + Request request, ReadEntityRuntimeFamilyCatalogResponse response) { + if (response == null + || response.getSerializedSize() > MAX_RESPONSE_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || response.getCanonicalResponseBytesCount() != 1) + throw new IllegalArgumentException("One complete bounded catalog response required"); + Evidence result = evidenceFromStored(response.getCanonicalResponseBytes(0).toByteArray()); + if (!request.equals(result.request())) + throw new IllegalArgumentException("Changed catalog read correlation"); + return result; + } + + private static DataInputStream input(byte[] value, int maximum) { + if (value == null || value.length == 0 || value.length > maximum) + throw new IllegalArgumentException("Frame bound exceeded"); + return new DataInputStream(new ByteArrayInputStream(value)); + } + + private static byte[] bytes(DataInputStream in, int maximum) throws IOException { + int length = in.readInt(); + if (length < 0 || length > maximum || length > in.available()) + throw new IllegalArgumentException("Invalid field bound"); + return in.readNBytes(length); + } + + private static void bytes(DataOutputStream out, byte[] value) throws IOException { + out.writeInt(value.length); + out.write(value); + } + + private static UUID uuid(DataInputStream in) throws IOException { + UUID result = new UUID(in.readLong(), in.readLong()); + EntityRuntimeFamilyCatalog.requireUuid(result); + return result; + } + + private static void uuid(DataOutputStream out, UUID value) throws IOException { + out.writeLong(value.getMostSignificantBits()); + out.writeLong(value.getLeastSignificantBits()); + } + + private interface Encoder { + void write(DataOutputStream out) throws IOException; + } + + private static byte[] encode(Encoder encoder) { + try (var buffer = new ByteArrayOutputStream(); + var out = new DataOutputStream(buffer)) { + encoder.write(out); + out.flush(); + return buffer.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException("Memory frame encoding failed", impossible); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalog.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalog.java new file mode 100644 index 0000000000..d5c1254f72 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalog.java @@ -0,0 +1,398 @@ +package net.firedevops.firemud.common.social; + +import com.google.protobuf.ByteString; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Immutable exact Social-local schema classification, not a row inventory or FRESH manifest. */ +public final class SocialRuntimeFamilyCatalog { + public static final String OWNER = "social-groups-service"; + public static final String SCHEMA = "social-runtime-family-catalog/v1"; + public static final int MAX_CATALOG_BYTES = 2 * 1024 * 1024; + public static final int MAX_FAMILIES = 512; + public static final int MAX_FACTS = 16384; + + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public enum Role { + GUILD_DEFINITION_ACL, + GUILD_MEMBERSHIP_ACL, + SOCIAL_RELATIONSHIP, + OWNERSHIP_DRIFT, + PLAYER_HISTORY, + EFFECT_REPLAY, + ACCOUNT_IDENTITY_CARRIER, + OPERATIONAL_EVIDENCE, + MIGRATION_HISTORY, + CATALOG + } + + /** + * Explicit current-scope qualification; no S1/S2/S3 or absence-derived disposition is implied. + */ + public enum FreshDisposition { + GUILD_SUBJECT_TYPE_UNSUPPORTED, + GUILD_CHILD_TENANT_IDENTITY_UNPROVEN, + RELATIONSHIP_BLOCK_LIFECYCLE_UNIMPLEMENTED, + ACCOUNT_PAIR_SCOPE_DRIFT, + ENTITY_VALUE_OWNERSHIP_DRIFT_BLOCKING, + CHAT_HISTORY_RETENTION_VIEW_AND_WHISPER_SCOPE_UNPROVEN, + CHAT_EFFECT_REPLAY_DIGEST_AND_HORIZON_UNPROVEN, + MAIL_HISTORY_RETENTION_AND_ACKNOWLEDGEMENT_UNPROVEN, + ACCOUNT_IDENTITY_CARRIER_ONLY, + SAGA_ADOPTER_UNRESOLVED, + MIGRATION_HISTORY_ONLY, + CATALOG_ONLY + } + + public enum TargetOwner { + NONE, + ACCOUNT_SERVICE, + ENTITY_MANAGEMENT_SERVICE + } + + public enum ContractGap { + CHAT_RESTRICTION_AND_REVISION, + DIRECTIONAL_BLOCK_LIFECYCLE, + ENTITY_ESCROW_REFERENCE_FAMILIES, + GAMEPLAY_WHISPER_NAMESPACE_SCOPE, + SAFETY_EVIDENCE_AND_CONTENT_FREE_RECEIPTS, + SOCIAL_PLAYER_STANDING_OWNER, + SOCIAL_SAGA_ADOPTER_CLASSIFICATION + } + + public enum FactKind { + TABLE, + COLUMN, + CONSTRAINT, + INDEX, + TRIGGER, + ROUTINE, + SEQUENCE, + VIEW, + TYPE, + POLICY, + RULE, + MIGRATION + } + + public record Family( + String familyId, + String relation, + String component, + Role role, + FreshDisposition freshDisposition, + TargetOwner targetOwner) { + public Family { + identifier(relation); + if (!component.isEmpty()) identifier(component); + if (!familyId.equals(relation + (component.isEmpty() ? "" : "." + component))) { + throw new IllegalArgumentException("Family identity must name its exact schema component"); + } + Objects.requireNonNull(role, "role"); + Objects.requireNonNull(freshDisposition, "freshDisposition"); + Objects.requireNonNull(targetOwner, "targetOwner"); + Role expectedRole = + switch (freshDisposition) { + case GUILD_SUBJECT_TYPE_UNSUPPORTED -> + role == Role.GUILD_DEFINITION_ACL || role == Role.GUILD_MEMBERSHIP_ACL + ? role + : null; + case GUILD_CHILD_TENANT_IDENTITY_UNPROVEN, + RELATIONSHIP_BLOCK_LIFECYCLE_UNIMPLEMENTED, + ACCOUNT_PAIR_SCOPE_DRIFT -> + Role.SOCIAL_RELATIONSHIP; + case ENTITY_VALUE_OWNERSHIP_DRIFT_BLOCKING -> Role.OWNERSHIP_DRIFT; + case CHAT_HISTORY_RETENTION_VIEW_AND_WHISPER_SCOPE_UNPROVEN, + MAIL_HISTORY_RETENTION_AND_ACKNOWLEDGEMENT_UNPROVEN -> + Role.PLAYER_HISTORY; + case CHAT_EFFECT_REPLAY_DIGEST_AND_HORIZON_UNPROVEN -> Role.EFFECT_REPLAY; + case ACCOUNT_IDENTITY_CARRIER_ONLY -> Role.ACCOUNT_IDENTITY_CARRIER; + case SAGA_ADOPTER_UNRESOLVED -> Role.OPERATIONAL_EVIDENCE; + case MIGRATION_HISTORY_ONLY -> Role.MIGRATION_HISTORY; + case CATALOG_ONLY -> Role.CATALOG; + }; + if (role != expectedRole) + throw new IllegalArgumentException("Contradictory family disposition"); + TargetOwner expectedOwner = + switch (freshDisposition) { + case ENTITY_VALUE_OWNERSHIP_DRIFT_BLOCKING -> TargetOwner.ENTITY_MANAGEMENT_SERVICE; + case ACCOUNT_IDENTITY_CARRIER_ONLY -> TargetOwner.ACCOUNT_SERVICE; + default -> TargetOwner.NONE; + }; + if (targetOwner != expectedOwner) { + throw new IllegalArgumentException("Contradictory Social target-owner classification"); + } + } + } + + /** Definition digests cover live PostgreSQL facts, not row counts or caller assertions. */ + public record SchemaFact(FactKind kind, String identity, String definitionDigest) { + public SchemaFact { + Objects.requireNonNull(kind, "kind"); + if (identity == null + || identity.isBlank() + || identity.length() > 8192 + || identity.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Invalid schema fact identity"); + } + requireDigest(definitionDigest); + } + } + + public record Request(UUID readRequestId, String targetNamespace) { + public Request { + requireUuid(readRequestId); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Exact workload namespace required"); + } + } + } + + public record Evidence(Request request, UUID snapshotId, SocialRuntimeFamilyCatalog catalog) { + public Evidence { + Objects.requireNonNull(request, "request"); + requireUuid(snapshotId); + Objects.requireNonNull(catalog, "catalog"); + } + + public String digest() { + return sha256(SocialRuntimeFamilyCatalogCodec.evidenceBytes(this)); + } + } + + private final long catalogEpoch; + private final List families; + private final List schemaFacts; + private final List unimplementedContracts; + private final ByteString exactBytes; + + private SocialRuntimeFamilyCatalog( + long epoch, + List families, + List facts, + List gaps, + byte[] bytes) { + catalogEpoch = epoch; + this.families = List.copyOf(families); + schemaFacts = List.copyOf(facts); + unimplementedContracts = List.copyOf(gaps); + exactBytes = ByteString.copyFrom(bytes); + } + + public long catalogEpoch() { + return catalogEpoch; + } + + public List families() { + return families; + } + + public List schemaFacts() { + return schemaFacts; + } + + public List unimplementedContracts() { + return unimplementedContracts; + } + + public byte[] exactBytes() { + return exactBytes.toByteArray(); + } + + public String digest() { + return sha256(exactBytes.toByteArray()); + } + + @Override + public boolean equals(Object other) { + return other instanceof SocialRuntimeFamilyCatalog catalog + && exactBytes.equals(catalog.exactBytes); + } + + @Override + public int hashCode() { + return exactBytes.hashCode(); + } + + /** Closed bounded decoding retains original PostgreSQL-sealed bytes without recanonicalizing. */ + public static SocialRuntimeFamilyCatalog fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CATALOG_BYTES) { + throw new IllegalArgumentException("Social catalog exceeds its complete-source bound"); + } + try { + String text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + JsonNode root = JSON.readTree(text); + fields( + root, + Set.of( + "schema", + "owner", + "catalogEpoch", + "families", + "schemaFacts", + "unimplementedContracts")); + if (!SCHEMA.equals(text(root, "schema")) || !OWNER.equals(text(root, "owner"))) { + throw new IllegalArgumentException("Unsupported Social catalog schema/owner"); + } + String epochText = text(root, "catalogEpoch"); + if (!epochText.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("Invalid Social catalog epoch"); + } + long epoch = Long.parseLong(epochText); + var families = new ArrayList(); + var facts = new ArrayList(); + var gaps = new ArrayList(); + array(root.get("families"), MAX_FAMILIES); + String previous = ""; + Set familyIds = new HashSet<>(); + for (JsonNode node : root.get("families")) { + fields( + node, + Set.of("familyId", "relation", "component", "role", "freshDisposition", "targetOwner")); + Family family = + new Family( + text(node, "familyId"), + text(node, "relation"), + text(node, "component"), + Role.valueOf(text(node, "role")), + FreshDisposition.valueOf(text(node, "freshDisposition")), + TargetOwner.valueOf(text(node, "targetOwner"))); + if (previous.compareTo(family.familyId()) >= 0 || !familyIds.add(family.familyId())) { + throw new IllegalArgumentException("Unordered/duplicate Social family"); + } + previous = family.familyId(); + families.add(family); + } + array(root.get("schemaFacts"), MAX_FACTS); + previous = ""; + Set tables = new HashSet<>(); + Set columns = new HashSet<>(); + for (JsonNode node : root.get("schemaFacts")) { + fields(node, Set.of("kind", "identity", "definitionDigest")); + SchemaFact fact = + new SchemaFact( + FactKind.valueOf(text(node, "kind")), + text(node, "identity"), + text(node, "definitionDigest")); + String key = fact.kind().name() + "/" + fact.identity(); + if (previous.compareTo(key) >= 0) { + throw new IllegalArgumentException("Unordered/duplicate Social schema fact"); + } + previous = key; + if (fact.kind() == FactKind.TABLE) tables.add(fact.identity()); + if (fact.kind() == FactKind.COLUMN) columns.add(fact.identity()); + facts.add(fact); + } + Set declaredTables = new HashSet<>(); + for (Family family : families) { + if (!tables.contains(family.relation())) { + throw new IllegalArgumentException("Missing Social family table fact"); + } + if (family.component().isEmpty()) { + declaredTables.add(family.relation()); + } else if (!columns.contains(family.familyId())) { + throw new IllegalArgumentException("Missing Social family component fact"); + } + } + if (!tables.equals(declaredTables) || tables.isEmpty()) { + throw new IllegalArgumentException("Every installed Social table needs a disposition"); + } + array(root.get("unimplementedContracts"), ContractGap.values().length); + previous = ""; + Set uniqueGaps = EnumSet.noneOf(ContractGap.class); + for (JsonNode node : root.get("unimplementedContracts")) { + if (!node.isTextual()) + throw new IllegalArgumentException("Text Social contract gap required"); + ContractGap gap = ContractGap.valueOf(node.asText()); + if (previous.compareTo(gap.name()) >= 0 || !uniqueGaps.add(gap)) { + throw new IllegalArgumentException("Unordered/duplicate Social contract gap"); + } + previous = gap.name(); + gaps.add(gap); + } + if (!uniqueGaps.equals(EnumSet.allOf(ContractGap.class))) { + throw new IllegalArgumentException( + "Social catalog must retain every known contract blocker"); + } + return new SocialRuntimeFamilyCatalog(epoch, families, facts, gaps, bytes); + } catch (java.io.IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Invalid closed Social catalog", invalid); + } + } + + static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Non-nil UUID required"); + } + } + + static void requireDigest(String value) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("SHA-256 required"); + } + } + + public static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 required by Java", impossible); + } + } + + private static void identifier(String value) { + if (value == null || !value.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalArgumentException("Schema identifier required"); + } + } + + private static void fields(JsonNode node, Set expected) { + if (node == null || !node.isObject()) + throw new IllegalArgumentException("Closed object required"); + Set actual = new HashSet<>(); + node.propertyNames().forEach(actual::add); + if (!actual.equals(expected)) + throw new IllegalArgumentException("Unknown or missing Social field"); + } + + private static String text(JsonNode node, String key) { + JsonNode value = node.get(key); + if (value == null || !value.isTextual()) + throw new IllegalArgumentException("Text field required"); + return value.asText(); + } + + private static void array(JsonNode node, int maximum) { + if (node == null || !node.isArray() || node.isEmpty() || node.size() > maximum) { + throw new IllegalArgumentException("Complete bounded Social catalog array required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogCodec.java new file mode 100644 index 0000000000..9e29a09983 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogCodec.java @@ -0,0 +1,180 @@ +package net.firedevops.firemud.common.social; + +import com.google.protobuf.ByteString; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.socialgroups.v1.ReadSocialRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.socialgroups.v1.ReadSocialRuntimeFamilyCatalogResponse; + +/** One closed finite binary frame per method; no generic parser or compatibility interpretation. */ +public final class SocialRuntimeFamilyCatalogCodec { + public static final int MAX_REQUEST_BYTES = 1024; + public static final int MAX_RESPONSE_BYTES = SocialRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 4096; + private static final int REQUEST_V1 = 0x53435231; + private static final int EVIDENCE_V1 = 0x53434531; + + private SocialRuntimeFamilyCatalogCodec() {} + + public static byte[] requestBytes(Request request) { + return encode( + out -> { + out.writeInt(REQUEST_V1); + uuid(out, request.readRequestId()); + bytes(out, request.targetNamespace().getBytes(StandardCharsets.US_ASCII)); + }); + } + + public static Request requestFromStored(byte[] bytes) { + try (var in = input(bytes, MAX_REQUEST_BYTES)) { + if (in.readInt() != REQUEST_V1) throw new IllegalArgumentException("Unsupported read schema"); + UUID id = uuid(in); + String namespace = new String(bytes(in, 63), StandardCharsets.US_ASCII); + Request result = new Request(id, namespace); + if (in.available() != 0 || !Arrays.equals(bytes, requestBytes(result))) { + throw new IllegalArgumentException("Noncanonical Social catalog request"); + } + return result; + } catch (IOException invalid) { + throw new IllegalArgumentException("Incomplete Social catalog request", invalid); + } + } + + public static byte[] evidenceBytes(Evidence evidence) { + byte[] result = + encode( + out -> { + out.writeInt(EVIDENCE_V1); + bytes(out, requestBytes(evidence.request())); + uuid(out, evidence.snapshotId()); + bytes(out, evidence.catalog().digest().getBytes(StandardCharsets.US_ASCII)); + bytes(out, evidence.catalog().exactBytes()); + }); + if (result.length > MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("Oversized complete Social catalog evidence"); + } + return result; + } + + public static Evidence evidenceFromStored(byte[] bytes) { + try (var in = input(bytes, MAX_RESPONSE_BYTES)) { + if (in.readInt() != EVIDENCE_V1) + throw new IllegalArgumentException("Unsupported evidence schema"); + Request request = requestFromStored(bytes(in, MAX_REQUEST_BYTES)); + UUID snapshotId = uuid(in); + String digest = new String(bytes(in, 71), StandardCharsets.US_ASCII); + SocialRuntimeFamilyCatalog catalog = + SocialRuntimeFamilyCatalog.fromStored( + bytes(in, SocialRuntimeFamilyCatalog.MAX_CATALOG_BYTES)); + Evidence result = new Evidence(request, snapshotId, catalog); + if (in.available() != 0 + || !digest.equals(catalog.digest()) + || !Arrays.equals(bytes, evidenceBytes(result))) { + throw new IllegalArgumentException("Changed/noncanonical Social catalog evidence"); + } + return result; + } catch (IOException invalid) { + throw new IllegalArgumentException("Incomplete Social catalog evidence", invalid); + } + } + + public static ReadSocialRuntimeFamilyCatalogRequest toRequest(Request request) { + return ReadSocialRuntimeFamilyCatalogRequest.newBuilder() + .addCanonicalRequestBytes(ByteString.copyFrom(requestBytes(request))) + .build(); + } + + /** Receiver must authenticate its workload before invoking this decoder. */ + public static Request fromRequest(ReadSocialRuntimeFamilyCatalogRequest request) { + if (request == null + || request.getSerializedSize() > MAX_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty() + || request.getCanonicalRequestBytesCount() != 1) { + throw new IllegalArgumentException("One bounded closed Social catalog request required"); + } + return requestFromStored(request.getCanonicalRequestBytes(0).toByteArray()); + } + + public static ReadSocialRuntimeFamilyCatalogResponse toResponse( + Request request, Evidence evidence) { + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException("Changed Social catalog read correlation"); + } + var response = + ReadSocialRuntimeFamilyCatalogResponse.newBuilder() + .addCanonicalResponseBytes(ByteString.copyFrom(evidenceBytes(evidence))) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("Oversized Social catalog response"); + } + return response; + } + + public static Evidence fromResponse( + Request request, ReadSocialRuntimeFamilyCatalogResponse response) { + if (response == null + || response.getSerializedSize() > MAX_RESPONSE_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || response.getCanonicalResponseBytesCount() != 1) { + throw new IllegalArgumentException("One complete bounded Social catalog response required"); + } + Evidence result = evidenceFromStored(response.getCanonicalResponseBytes(0).toByteArray()); + if (!request.equals(result.request())) { + throw new IllegalArgumentException("Changed Social catalog read correlation"); + } + return result; + } + + private static DataInputStream input(byte[] value, int maximum) { + if (value == null || value.length == 0 || value.length > maximum) { + throw new IllegalArgumentException("Social catalog frame bound exceeded"); + } + return new DataInputStream(new ByteArrayInputStream(value)); + } + + private static byte[] bytes(DataInputStream in, int maximum) throws IOException { + int length = in.readInt(); + if (length < 0 || length > maximum || length > in.available()) { + throw new IllegalArgumentException("Invalid Social catalog field bound"); + } + return in.readNBytes(length); + } + + private static void bytes(DataOutputStream out, byte[] value) throws IOException { + out.writeInt(value.length); + out.write(value); + } + + private static UUID uuid(DataInputStream in) throws IOException { + UUID result = new UUID(in.readLong(), in.readLong()); + SocialRuntimeFamilyCatalog.requireUuid(result); + return result; + } + + private static void uuid(DataOutputStream out, UUID value) throws IOException { + out.writeLong(value.getMostSignificantBits()); + out.writeLong(value.getLeastSignificantBits()); + } + + private interface Encoder { + void write(DataOutputStream out) throws IOException; + } + + private static byte[] encode(Encoder encoder) { + try (var buffer = new ByteArrayOutputStream(); + var out = new DataOutputStream(buffer)) { + encoder.write(out); + out.flush(); + return buffer.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException("Memory frame encoding failed", impossible); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java new file mode 100644 index 0000000000..bc42b1c1e5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java @@ -0,0 +1,324 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Immutable exact World-local schema classification, not runtime-state or FRESH completeness. */ +public final class WorldRuntimeFamilyCatalog { + public static final String OWNER = "world-management-service"; + public static final String SCHEMA = "world-runtime-family-catalog/v1"; + public static final int MAX_CATALOG_BYTES = 2 * 1024 * 1024; + public static final int MAX_FAMILIES = 512; + public static final int MAX_FACTS = 16384; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public enum Role { + RUNTIME_PAYLOAD, + LIFECYCLE, + SOURCE, + CONTROL, + AUDIT, + PROVENANCE, + EXCLUDED, + CATALOG + } + + public enum StateClass { + S3, + NOT_PAYLOAD + } + + public enum FreshDisposition { + REQUIRED_TOPOLOGY, + REQUIRED_LIFECYCLE, + NOT_INITIALIZED_ACTOR_LOCATION, + UNSUPPORTED_WEATHER, + OWNER_EVENT_PROOF_REQUIRED, + LEGACY_EXCLUDED, + SOURCE_ONLY, + CONTROL_ONLY, + AUDIT_ONLY, + PROVENANCE_ONLY, + CATALOG_ONLY + } + + public enum FactKind { + TABLE, + COLUMN, + CONSTRAINT, + INDEX, + TRIGGER, + ROUTINE, + SEQUENCE, + VIEW, + TYPE, + POLICY, + RULE, + MIGRATION + } + + public record Family( + String familyId, + String relation, + String component, + Role role, + StateClass stateClass, + FreshDisposition freshDisposition) { + public Family { + identifier(relation); + if (!component.isEmpty()) identifier(component); + if (!familyId.equals(relation + (component.isEmpty() ? "" : "." + component))) { + throw new IllegalArgumentException("Family identity must name its exact schema component"); + } + Objects.requireNonNull(role, "role"); + Objects.requireNonNull(stateClass, "stateClass"); + Objects.requireNonNull(freshDisposition, "freshDisposition"); + if ((role == Role.RUNTIME_PAYLOAD || role == Role.LIFECYCLE || role == Role.EXCLUDED) + != (stateClass == StateClass.S3)) { + throw new IllegalArgumentException("Payload and non-payload classifications differ"); + } + Role expected = + switch (freshDisposition) { + case REQUIRED_TOPOLOGY, + NOT_INITIALIZED_ACTOR_LOCATION, + UNSUPPORTED_WEATHER, + OWNER_EVENT_PROOF_REQUIRED -> + Role.RUNTIME_PAYLOAD; + case REQUIRED_LIFECYCLE -> Role.LIFECYCLE; + case LEGACY_EXCLUDED -> Role.EXCLUDED; + case SOURCE_ONLY -> Role.SOURCE; + case CONTROL_ONLY -> Role.CONTROL; + case AUDIT_ONLY -> Role.AUDIT; + case PROVENANCE_ONLY -> Role.PROVENANCE; + case CATALOG_ONLY -> Role.CATALOG; + }; + if (role != expected) throw new IllegalArgumentException("Contradictory family disposition"); + } + } + + /** Definition digests cover actual PostgreSQL facts, not row counts or caller assertions. */ + public record SchemaFact(FactKind kind, String identity, String definitionDigest) { + public SchemaFact { + Objects.requireNonNull(kind, "kind"); + if (identity == null + || identity.isBlank() + || identity.length() > 8192 + || identity.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Invalid schema fact identity"); + } + requireDigest(definitionDigest); + } + } + + public record Request(UUID readRequestId, String targetNamespace) { + public Request { + requireUuid(readRequestId); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Exact workload namespace required"); + } + } + } + + public record Evidence(Request request, UUID snapshotId, WorldRuntimeFamilyCatalog catalog) { + public Evidence { + Objects.requireNonNull(request, "request"); + requireUuid(snapshotId); + Objects.requireNonNull(catalog, "catalog"); + } + + public String digest() { + return sha256(WorldRuntimeFamilyCatalogCodec.evidenceBytes(this)); + } + } + + private final long catalogEpoch; + private final List families; + private final List schemaFacts; + private final ByteString exactBytes; + + private WorldRuntimeFamilyCatalog( + long epoch, List families, List facts, byte[] bytes) { + catalogEpoch = epoch; + this.families = List.copyOf(families); + schemaFacts = List.copyOf(facts); + exactBytes = ByteString.copyFrom(bytes); + } + + public long catalogEpoch() { + return catalogEpoch; + } + + public List families() { + return families; + } + + public List schemaFacts() { + return schemaFacts; + } + + public byte[] exactBytes() { + return exactBytes.toByteArray(); + } + + public String digest() { + return sha256(exactBytes.toByteArray()); + } + + @Override + public boolean equals(Object other) { + return other instanceof WorldRuntimeFamilyCatalog catalog + && exactBytes.equals(catalog.exactBytes); + } + + @Override + public int hashCode() { + return exactBytes.hashCode(); + } + + /** + * Closed bounded decoding retains the original PostgreSQL-sealed bytes without recanonicalizing. + */ + public static WorldRuntimeFamilyCatalog fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CATALOG_BYTES) { + throw new IllegalArgumentException("World catalog exceeds its complete-source bound"); + } + try { + String text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + JsonNode root = JSON.readTree(text); + fields(root, Set.of("schema", "owner", "catalogEpoch", "families", "schemaFacts")); + if (!SCHEMA.equals(text(root, "schema")) || !OWNER.equals(text(root, "owner"))) { + throw new IllegalArgumentException("Unsupported World catalog schema/owner"); + } + String epochText = text(root, "catalogEpoch"); + if (!epochText.matches("[1-9][0-9]{0,18}")) + throw new IllegalArgumentException("Invalid epoch"); + long epoch = Long.parseLong(epochText); + var families = new ArrayList(); + var facts = new ArrayList(); + array(root.get("families"), MAX_FAMILIES); + String previous = ""; + for (JsonNode node : root.get("families")) { + fields( + node, + Set.of("familyId", "relation", "component", "role", "stateClass", "freshDisposition")); + Family family = + new Family( + text(node, "familyId"), + text(node, "relation"), + text(node, "component"), + Role.valueOf(text(node, "role")), + StateClass.valueOf(text(node, "stateClass")), + FreshDisposition.valueOf(text(node, "freshDisposition"))); + if (previous.compareTo(family.familyId()) >= 0) + throw new IllegalArgumentException("Unordered/duplicate family"); + previous = family.familyId(); + families.add(family); + } + array(root.get("schemaFacts"), MAX_FACTS); + previous = ""; + Set tables = new HashSet<>(); + Set columns = new HashSet<>(); + for (JsonNode node : root.get("schemaFacts")) { + fields(node, Set.of("kind", "identity", "definitionDigest")); + SchemaFact fact = + new SchemaFact( + FactKind.valueOf(text(node, "kind")), + text(node, "identity"), + text(node, "definitionDigest")); + String key = fact.kind().name() + "/" + fact.identity(); + if (previous.compareTo(key) >= 0) + throw new IllegalArgumentException("Unordered/duplicate schema fact"); + previous = key; + if (fact.kind() == FactKind.TABLE) tables.add(fact.identity()); + if (fact.kind() == FactKind.COLUMN) columns.add(fact.identity()); + facts.add(fact); + } + Set declaredTables = new HashSet<>(); + for (Family family : families) { + if (!tables.contains(family.relation())) + throw new IllegalArgumentException("Missing family table"); + if (family.component().isEmpty()) declaredTables.add(family.relation()); + else if (!columns.contains(family.familyId())) + throw new IllegalArgumentException("Missing family component"); + } + if (!tables.equals(declaredTables) || tables.isEmpty()) { + throw new IllegalArgumentException("Every installed table needs an explicit disposition"); + } + return new WorldRuntimeFamilyCatalog(epoch, families, facts, bytes); + } catch (java.io.IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Invalid closed World catalog", invalid); + } + } + + static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) + throw new IllegalArgumentException("Non-nil UUID required"); + } + + static void requireDigest(String value) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException("SHA-256 required"); + } + + public static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 required by Java", impossible); + } + } + + private static void identifier(String value) { + if (value == null || !value.matches("[a-z][a-z0-9_]{0,62}")) + throw new IllegalArgumentException("Schema identifier required"); + } + + private static void fields(JsonNode node, Set expected) { + if (node == null || !node.isObject()) + throw new IllegalArgumentException("Closed object required"); + Set actual = new HashSet<>(); + node.propertyNames().forEach(actual::add); + if (!actual.equals(expected)) + throw new IllegalArgumentException("Unknown or missing catalog field"); + } + + private static String text(JsonNode node, String key) { + JsonNode value = node.get(key); + if (value == null || !value.isTextual()) + throw new IllegalArgumentException("Text field required"); + return value.asText(); + } + + private static void array(JsonNode node, int maximum) { + if (node == null || !node.isArray() || node.isEmpty() || node.size() > maximum) { + throw new IllegalArgumentException("Complete bounded catalog array required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java new file mode 100644 index 0000000000..7019b99386 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java @@ -0,0 +1,175 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldRuntimeFamilyCatalogResponse; + +/** One closed finite binary frame per method; no generic parser or compatibility interpretation. */ +public final class WorldRuntimeFamilyCatalogCodec { + public static final int MAX_REQUEST_BYTES = 1024; + public static final int MAX_RESPONSE_BYTES = WorldRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 4096; + private static final int REQUEST_V1 = 0x57435231; + private static final int EVIDENCE_V1 = 0x57434531; + + private WorldRuntimeFamilyCatalogCodec() {} + + public static byte[] requestBytes(Request request) { + return encode( + out -> { + out.writeInt(REQUEST_V1); + uuid(out, request.readRequestId()); + bytes(out, request.targetNamespace().getBytes(StandardCharsets.US_ASCII)); + }); + } + + public static Request requestFromStored(byte[] bytes) { + try (var in = input(bytes, MAX_REQUEST_BYTES)) { + if (in.readInt() != REQUEST_V1) throw new IllegalArgumentException("Unsupported read schema"); + UUID id = uuid(in); + byte[] namespaceBytes = bytes(in, 63); + String namespace = new String(namespaceBytes, StandardCharsets.US_ASCII); + Request result = new Request(id, namespace); + if (in.available() != 0 || !Arrays.equals(bytes, requestBytes(result))) { + throw new IllegalArgumentException("Noncanonical World catalog request"); + } + return result; + } catch (IOException invalid) { + throw new IllegalArgumentException("Incomplete World catalog request", invalid); + } + } + + public static byte[] evidenceBytes(Evidence evidence) { + byte[] result = + encode( + out -> { + out.writeInt(EVIDENCE_V1); + bytes(out, requestBytes(evidence.request())); + uuid(out, evidence.snapshotId()); + bytes(out, evidence.catalog().digest().getBytes(StandardCharsets.US_ASCII)); + bytes(out, evidence.catalog().exactBytes()); + }); + if (result.length > MAX_RESPONSE_BYTES) + throw new IllegalArgumentException("Oversized complete catalog evidence"); + return result; + } + + public static Evidence evidenceFromStored(byte[] bytes) { + try (var in = input(bytes, MAX_RESPONSE_BYTES)) { + if (in.readInt() != EVIDENCE_V1) + throw new IllegalArgumentException("Unsupported evidence schema"); + Request request = requestFromStored(bytes(in, MAX_REQUEST_BYTES)); + UUID snapshotId = uuid(in); + String digest = new String(bytes(in, 71), StandardCharsets.US_ASCII); + WorldRuntimeFamilyCatalog catalog = + WorldRuntimeFamilyCatalog.fromStored( + bytes(in, WorldRuntimeFamilyCatalog.MAX_CATALOG_BYTES)); + Evidence result = new Evidence(request, snapshotId, catalog); + if (in.available() != 0 + || !digest.equals(catalog.digest()) + || !Arrays.equals(bytes, evidenceBytes(result))) { + throw new IllegalArgumentException("Changed/noncanonical catalog evidence"); + } + return result; + } catch (IOException invalid) { + throw new IllegalArgumentException("Incomplete World catalog evidence", invalid); + } + } + + public static ReadWorldRuntimeFamilyCatalogRequest toRequest(Request request) { + return ReadWorldRuntimeFamilyCatalogRequest.newBuilder() + .addCanonicalRequestBytes(ByteString.copyFrom(requestBytes(request))) + .build(); + } + + /** Receiver must authenticate its workload before invoking this decoder. */ + public static Request fromRequest(ReadWorldRuntimeFamilyCatalogRequest request) { + if (request == null + || request.getSerializedSize() > MAX_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty() + || request.getCanonicalRequestBytesCount() != 1) { + throw new IllegalArgumentException("One bounded closed catalog request required"); + } + return requestFromStored(request.getCanonicalRequestBytes(0).toByteArray()); + } + + public static ReadWorldRuntimeFamilyCatalogResponse toResponse( + Request request, Evidence evidence) { + if (!request.equals(evidence.request())) + throw new IllegalArgumentException("Changed catalog read correlation"); + var response = + ReadWorldRuntimeFamilyCatalogResponse.newBuilder() + .addCanonicalResponseBytes(ByteString.copyFrom(evidenceBytes(evidence))) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) + throw new IllegalArgumentException("Oversized response"); + return response; + } + + public static Evidence fromResponse( + Request request, ReadWorldRuntimeFamilyCatalogResponse response) { + if (response == null + || response.getSerializedSize() > MAX_RESPONSE_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || response.getCanonicalResponseBytesCount() != 1) { + throw new IllegalArgumentException("One complete bounded catalog response required"); + } + Evidence result = evidenceFromStored(response.getCanonicalResponseBytes(0).toByteArray()); + if (!request.equals(result.request())) + throw new IllegalArgumentException("Changed catalog read correlation"); + return result; + } + + private static DataInputStream input(byte[] value, int maximum) { + if (value == null || value.length == 0 || value.length > maximum) + throw new IllegalArgumentException("Frame bound exceeded"); + return new DataInputStream(new ByteArrayInputStream(value)); + } + + private static byte[] bytes(DataInputStream in, int maximum) throws IOException { + int length = in.readInt(); + if (length < 0 || length > maximum || length > in.available()) + throw new IllegalArgumentException("Invalid field bound"); + return in.readNBytes(length); + } + + private static void bytes(DataOutputStream out, byte[] value) throws IOException { + out.writeInt(value.length); + out.write(value); + } + + private static UUID uuid(DataInputStream in) throws IOException { + UUID result = new UUID(in.readLong(), in.readLong()); + WorldRuntimeFamilyCatalog.requireUuid(result); + return result; + } + + private static void uuid(DataOutputStream out, UUID value) throws IOException { + out.writeLong(value.getMostSignificantBits()); + out.writeLong(value.getLeastSignificantBits()); + } + + private interface Encoder { + void write(DataOutputStream out) throws IOException; + } + + private static byte[] encode(Encoder encoder) { + try (var buffer = new ByteArrayOutputStream(); + var out = new DataOutputStream(buffer)) { + encoder.write(out); + out.flush(); + return buffer.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException("Memory frame encoding failed", impossible); + } + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogTest.java new file mode 100644 index 0000000000..99cc58e22d --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogTest.java @@ -0,0 +1,284 @@ +package unit.net.firedevops.firemud.common.automation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collections; +import java.util.UUID; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalogCodec; +import org.junit.jupiter.api.Test; + +/** + * Controlled catalog bytes prove only the value/framing boundary, not installed SQL completeness. + */ +class AutomationRuntimeFamilyCatalogTest { + private static final String FAMILY = + """ + {"familyId":"npc_memory","relation":"npc_memory","component":"","role":"RUNTIME_PAYLOAD", + "stateClass":"UNKNOWN","freshDisposition":"STATE_CLASS_UNKNOWN_BLOCKING", + "retentionDisposition":"UNRESOLVED_RETAINED","ownerConsequence":"Namespace and actor class unresolved; no clone."} + """; + private static final String FACT = + """ + {"kind":"TABLE","identity":"npc_memory", + "definitionDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"} + """; + private static final String GAP = + """ + {"id":"DURABLE_CHARGE_MARKERS","disposition":"UNSUPPORTED_BLOCKING", + "ownerConsequence":"No durable charge rows or admission/execution markers exist."} + """; + private static final String PREFIX = + """ + {"schema":"automation-runtime-family-catalog/v1","owner":"automation-scripting-service","catalogEpoch":"1", + """; + private static final String CATALOG = + PREFIX + + "\"families\":[" + + FAMILY + + "],\"schemaFacts\":[" + + FACT + + "],\"nonSqlGaps\":[" + + GAP + + "]}"; + + @Test + void stablePurposeSpecificRequestFramingAndDigestVector() { + var read = new Request(UUID.fromString("11111111-1111-4111-8111-111111111111"), "test"); + assertThat( + java.util.HexFormat.of() + .formatHex(AutomationRuntimeFamilyCatalogCodec.requestBytes(read))) + .isEqualTo("41435231111111111111411181111111111111110000000474657374"); + assertThat(AutomationRuntimeFamilyCatalog.sha256("abc".getBytes(StandardCharsets.US_ASCII))) + .isEqualTo("sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + } + + @Test + void exactRoundtripRetainsOriginalBytesDigestsRequestAndImmutableCollections() { + byte[] source = CATALOG.getBytes(StandardCharsets.UTF_8); + var catalog = AutomationRuntimeFamilyCatalog.fromStored(source); + var read = new Request(UUID.randomUUID(), "test"); + var evidence = new Evidence(read, UUID.randomUUID(), catalog); + assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat(catalog.digest()).isEqualTo(AutomationRuntimeFamilyCatalog.sha256(source)); + assertThat( + AutomationRuntimeFamilyCatalogCodec.fromRequest( + AutomationRuntimeFamilyCatalogCodec.toRequest(read))) + .isEqualTo(read); + assertThat( + AutomationRuntimeFamilyCatalogCodec.fromResponse( + read, AutomationRuntimeFamilyCatalogCodec.toResponse(read, evidence))) + .isEqualTo(evidence); + assertThat( + AutomationRuntimeFamilyCatalogCodec.evidenceFromStored( + AutomationRuntimeFamilyCatalogCodec.evidenceBytes(evidence)) + .digest()) + .isEqualTo(evidence.digest()); + source[0] = 0; + catalog.exactBytes()[0] = 0; + assertThat(catalog.exactBytes()).isEqualTo(CATALOG.getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> catalog.families().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> catalog.schemaFacts().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> catalog.nonSqlGaps().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void unknownDuplicateMissingInconsistentAndTrailingCatalogFieldsRefuse() { + for (String invalid : + new String[] { + CATALOG.replace("\"owner\":", "\"extra\":true,\"owner\":"), + CATALOG.replace( + "\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"1\",\"catalogEpoch\":\"1\""), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"0\""), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":1"), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"9223372036854775808\""), + CATALOG.replace( + "automation-runtime-family-catalog/v1", "automation-runtime-family-catalog/v2"), + CATALOG.replace("automation-scripting-service", "social-groups-service"), + CATALOG.replace("\"UNKNOWN\"", "\"S3\""), + CATALOG.replace("\"UNKNOWN\"", "\"NOT_PAYLOAD\""), + CATALOG.replace("\"RUNTIME_PAYLOAD\"", "\"SOURCE\""), + CATALOG.replace("STATE_CLASS_UNKNOWN_BLOCKING", "OWNERSHIP_DRIFT_BLOCKING"), + CATALOG.replace("\"identity\":\"npc_memory\"", "\"identity\":\"future_family\""), + CATALOG.replace("\"component\":\"\"", "\"component\":\"key\""), + CATALOG.replace("UNRESOLVED_RETAINED", "DISPOSABLE"), + CATALOG.replace("DURABLE_CHARGE_MARKERS", "REDIS_CENSUS_COMPLETE"), + CATALOG.replace("UNSUPPORTED_BLOCKING", "COMPLETE"), + CATALOG.replace(FAMILY, FAMILY + "," + FAMILY), + CATALOG.replace(FACT, FACT + "," + FACT), + CATALOG.replace(GAP, GAP + "," + GAP), + CATALOG.replace("Namespace and actor class unresolved; no clone.", ""), + CATALOG + "{}" + }) { + assertThatThrownBy( + () -> + AutomationRuntimeFamilyCatalog.fromStored( + invalid.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void familyFactGapAndSourceBoundsAreIndependentOfNoPayloadRows() { + String manyFamilies = + PREFIX + + "\"families\":[" + + String.join(",", Collections.nCopies(513, FAMILY)) + + "],\"schemaFacts\":[" + + FACT + + "],\"nonSqlGaps\":[" + + GAP + + "]}"; + String compactFact = + "{\"kind\":\"TYPE\",\"identity\":\"x\",\"definitionDigest\":\"sha256:" + + "a".repeat(64) + + "\"}"; + String manyFacts = + PREFIX + + "\"families\":[" + + FAMILY + + "],\"schemaFacts\":[" + + String.join(",", Collections.nCopies(16385, compactFact)) + + "],\"nonSqlGaps\":[" + + GAP + + "]}"; + String manyGaps = CATALOG.replace(GAP, String.join(",", Collections.nCopies(33, GAP))); + for (String invalid : + new String[] { + manyFamilies, + manyFacts, + manyGaps, + CATALOG.replace(FAMILY, ""), + CATALOG.replace(FACT, ""), + CATALOG.replace(GAP, "") + }) { + assertThatThrownBy( + () -> + AutomationRuntimeFamilyCatalog.fromStored( + invalid.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + AutomationRuntimeFamilyCatalog.fromStored( + new byte[AutomationRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void duplicateUnknownOversizedAndChangedCorrelationWireValuesRefuse() { + var read = new Request(UUID.randomUUID(), "test"); + var request = AutomationRuntimeFamilyCatalogCodec.toRequest(read); + var unknown = + UnknownFieldSet.newBuilder() + .addField(9, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertThatThrownBy( + () -> + AutomationRuntimeFamilyCatalogCodec.fromRequest( + request.toBuilder() + .addCanonicalRequestBytes(request.getCanonicalRequestBytes(0)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationRuntimeFamilyCatalogCodec.fromRequest( + request.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationRuntimeFamilyCatalogCodec.fromRequest( + request.toBuilder() + .setCanonicalRequestBytes(0, ByteString.copyFrom(new byte[1025])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + var evidence = new Evidence(read, UUID.randomUUID(), catalog()); + var response = AutomationRuntimeFamilyCatalogCodec.toResponse(read, evidence); + assertThatThrownBy( + () -> + AutomationRuntimeFamilyCatalogCodec.fromResponse( + new Request(UUID.randomUUID(), "test"), response)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationRuntimeFamilyCatalogCodec.fromResponse( + new Request(read.readRequestId(), "other"), response)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationRuntimeFamilyCatalogCodec.fromResponse( + read, + response.toBuilder() + .addCanonicalResponseBytes(response.getCanonicalResponseBytes(0)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationRuntimeFamilyCatalogCodec.fromResponse( + read, response.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationRuntimeFamilyCatalogCodec.fromResponse( + read, + response.toBuilder() + .setCanonicalResponseBytes( + 0, + ByteString.copyFrom( + new byte + [AutomationRuntimeFamilyCatalogCodec.MAX_RESPONSE_BYTES + 1])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void truncationTrailingInvalidLengthsMagicDigestUtf8AndIdentityRefuse() { + var evidence = + new Evidence(new Request(UUID.randomUUID(), "test"), UUID.randomUUID(), catalog()); + byte[] frame = AutomationRuntimeFamilyCatalogCodec.evidenceBytes(evidence); + for (byte[] invalid : + new byte[][] { + Arrays.copyOf(frame, frame.length - 1), Arrays.copyOf(frame, frame.length + 1) + }) { + assertThatThrownBy(() -> AutomationRuntimeFamilyCatalogCodec.evidenceFromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + int digestOffset = + 4 + + 4 + + AutomationRuntimeFamilyCatalogCodec.requestBytes(evidence.request()).length + + 16 + + 4; + frame[digestOffset + 7] = frame[digestOffset + 7] == 'a' ? (byte) 'b' : (byte) 'a'; + assertThatThrownBy(() -> AutomationRuntimeFamilyCatalogCodec.evidenceFromStored(frame)) + .isInstanceOf(IllegalArgumentException.class); + byte[] request = AutomationRuntimeFamilyCatalogCodec.requestBytes(evidence.request()); + request[20] = (byte) 0x7f; + assertThatThrownBy(() -> AutomationRuntimeFamilyCatalogCodec.requestFromStored(request)) + .isInstanceOf(IllegalArgumentException.class); + request[0] = 'W'; + assertThatThrownBy(() -> AutomationRuntimeFamilyCatalogCodec.requestFromStored(request)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> AutomationRuntimeFamilyCatalog.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(new UUID(0, 0), "test")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(UUID.randomUUID(), "1/sa/automation-scripting-service")) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AutomationRuntimeFamilyCatalog catalog() { + return AutomationRuntimeFamilyCatalog.fromStored(CATALOG.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogTest.java new file mode 100644 index 0000000000..dd6ea6870d --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogTest.java @@ -0,0 +1,268 @@ +package unit.net.firedevops.firemud.common.entity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Family; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.FreshDisposition; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Role; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.StateClass; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalogCodec; +import org.junit.jupiter.api.Test; + +/** Controlled bytes prove closed value behavior, never actual schema or runtime completeness. */ +class EntityRuntimeFamilyCatalogTest { + private static final String CATALOG = + """ + {"schema":"entity-runtime-family-catalog/v1","owner":"entity-management-service", + "catalogEpoch":"1","families":[ + {"familyId":"characters","relation":"characters","component":"", + "role":"RUNTIME_PAYLOAD","stateClass":"S1","freshDisposition":"PROVISIONAL_NAMESPACE"}], + "schemaFacts":[{"kind":"TABLE","identity":"characters", + "definitionDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]} + """; + + @Test + void stableFramingAndDigestVector() { + var request = new Request(UUID.fromString("11111111-1111-4111-8111-111111111111"), "test"); + assertThat( + java.util.HexFormat.of() + .formatHex(EntityRuntimeFamilyCatalogCodec.requestBytes(request))) + .isEqualTo("45435231111111111111411181111111111111110000000474657374"); + assertThat(EntityRuntimeFamilyCatalog.sha256("abc".getBytes(StandardCharsets.US_ASCII))) + .isEqualTo("sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + } + + @Test + void exactRoundtripAndImmutableOriginalBytes() { + byte[] source = CATALOG.getBytes(StandardCharsets.UTF_8); + var catalog = EntityRuntimeFamilyCatalog.fromStored(source); + var read = request(); + var evidence = new Evidence(read, UUID.randomUUID(), catalog); + assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat(catalog.families().getFirst().logicalFamily()).isEqualTo("character"); + assertThat( + EntityRuntimeFamilyCatalogCodec.fromRequest( + EntityRuntimeFamilyCatalogCodec.toRequest(read))) + .isEqualTo(read); + assertThat( + EntityRuntimeFamilyCatalogCodec.fromResponse( + read, EntityRuntimeFamilyCatalogCodec.toResponse(read, evidence))) + .isEqualTo(evidence); + assertThat( + EntityRuntimeFamilyCatalogCodec.evidenceFromStored( + EntityRuntimeFamilyCatalogCodec.evidenceBytes(evidence)) + .digest()) + .isEqualTo(evidence.digest()); + assertThat(catalog.digest()).isEqualTo(EntityRuntimeFamilyCatalog.sha256(source)); + source[0] = 0; + catalog.exactBytes()[0] = 0; + assertThat(catalog.exactBytes()).isEqualTo(CATALOG.getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> catalog.families().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> catalog.schemaFacts().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void conditionalAndUnresolvedAreExplicitFactsNotSuccessfulRowClassifications() { + assertThat( + new Family( + "actor_resource_states", + "actor_resource_states", + "", + Role.RUNTIME_PAYLOAD, + StateClass.CONDITIONAL_S1_S2, + FreshDisposition.BLOCKING_NAMESPACE_REMAP) + .stateClass()) + .isEqualTo(StateClass.CONDITIONAL_S1_S2); + assertThat( + new Family( + "npcs.last_defeated_at", + "npcs", + "last_defeated_at", + Role.MIXED, + StateClass.UNRESOLVED, + FreshDisposition.BLOCKING_MIXED_NPC) + .stateClass()) + .isEqualTo(StateClass.UNRESOLVED); + assertThat( + new Family( + "item_instances", + "item_instances", + "", + Role.RUNTIME_PAYLOAD, + StateClass.CONDITIONAL_HOLDER, + FreshDisposition.BLOCKING_HOLDER_CLOSURE) + .stateClass()) + .isEqualTo(StateClass.CONDITIONAL_HOLDER); + assertThatThrownBy( + () -> + new Family( + "item_instances", + "item_instances", + "", + Role.RUNTIME_PAYLOAD, + StateClass.S3, + FreshDisposition.BLOCKING_HOLDER_CLOSURE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new Family( + "item_visible_ref_counters", + "item_visible_ref_counters", + "", + Role.ALLOCATOR, + StateClass.S3, + FreshDisposition.BLOCKING_ALLOCATOR_CLASS)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void unknownMissingDuplicateNumericAndContradictoryCatalogsRefuse() { + for (String invalid : + List.of( + CATALOG.replace("\"owner\":", "\"extra\":true,\"owner\":"), + CATALOG.replace( + "\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"1\",\"catalogEpoch\":\"1\""), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":1"), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"0\""), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"9223372036854775808\""), + CATALOG.replace("catalog/v1", "catalog/v2"), + CATALOG.replace("entity-management-service", "world-management-service"), + CATALOG.replace("\"S1\"", "\"S3\""), + CATALOG.replace("\"RUNTIME_PAYLOAD\"", "\"UNKNOWN\""), + CATALOG.replace("\"identity\":\"characters\"", "\"identity\":\"other_table\""), + CATALOG.replace("\"component\":\"\"", "\"component\":\"body_layout_key\""), + CATALOG + "{}")) + assertThatThrownBy( + () -> EntityRuntimeFamilyCatalog.fromStored(invalid.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void arrayAndByteBoundsDoNotDependOnPayloadAbsence() { + String family = + "{\"familyId\":\"characters\",\"relation\":\"characters\",\"component\":\"\"," + + "\"role\":\"RUNTIME_PAYLOAD\",\"stateClass\":\"S1\",\"freshDisposition\":\"PROVISIONAL_NAMESPACE\"}"; + String fact = + "{\"kind\":\"TYPE\",\"identity\":\"x\",\"definitionDigest\":\"sha256:" + + "a".repeat(64) + + "\"}"; + String prefix = + "{\"schema\":\"entity-runtime-family-catalog/v1\",\"owner\":\"entity-management-service\",\"catalogEpoch\":\"1\","; + for (String invalid : + List.of( + prefix + + "\"families\":[" + + String.join(",", java.util.Collections.nCopies(513, family)) + + "],\"schemaFacts\":[" + + fact + + "]}", + prefix + + "\"families\":[" + + family + + "],\"schemaFacts\":[" + + String.join(",", java.util.Collections.nCopies(16385, fact)) + + "]}", + prefix + "\"families\":[],\"schemaFacts\":[]}")) + assertThatThrownBy( + () -> EntityRuntimeFamilyCatalog.fromStored(invalid.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntityRuntimeFamilyCatalog.fromStored( + new byte[EntityRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> EntityRuntimeFamilyCatalog.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void duplicateUnknownOversizedAndChangedCorrelationFramesRefuse() { + var read = request(); + var wire = EntityRuntimeFamilyCatalogCodec.toRequest(read); + assertThatThrownBy( + () -> + EntityRuntimeFamilyCatalogCodec.fromRequest( + wire.toBuilder() + .addCanonicalRequestBytes(wire.getCanonicalRequestBytes(0)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + var unknown = + UnknownFieldSet.newBuilder() + .addField(9, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertThatThrownBy( + () -> + EntityRuntimeFamilyCatalogCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntityRuntimeFamilyCatalogCodec.fromRequest( + wire.toBuilder() + .setCanonicalRequestBytes(0, ByteString.copyFrom(new byte[1025])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + var evidence = new Evidence(read, UUID.randomUUID(), catalog()); + var response = EntityRuntimeFamilyCatalogCodec.toResponse(read, evidence); + for (var invalid : + List.of( + response.toBuilder().setUnknownFields(unknown).build(), + response.toBuilder() + .addCanonicalResponseBytes(response.getCanonicalResponseBytes(0)) + .build(), + response.toBuilder() + .setCanonicalResponseBytes( + 0, + ByteString.copyFrom( + new byte[EntityRuntimeFamilyCatalogCodec.MAX_RESPONSE_BYTES + 1])) + .build())) + assertThatThrownBy(() -> EntityRuntimeFamilyCatalogCodec.fromResponse(read, invalid)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> EntityRuntimeFamilyCatalogCodec.fromResponse(request(), response)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntityRuntimeFamilyCatalogCodec.fromResponse( + new Request(read.readRequestId(), "other"), response)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(new UUID(0, 0), "test")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(UUID.randomUUID(), "ns/sa/entity-management-service")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void truncationTrailingDataAndDigestTamperingRefuse() { + var evidence = new Evidence(request(), UUID.randomUUID(), catalog()); + byte[] bytes = EntityRuntimeFamilyCatalogCodec.evidenceBytes(evidence); + for (byte[] invalid : + List.of(Arrays.copyOf(bytes, bytes.length - 1), Arrays.copyOf(bytes, bytes.length + 1))) + assertThatThrownBy(() -> EntityRuntimeFamilyCatalogCodec.evidenceFromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + int digestOffset = + 4 + 4 + EntityRuntimeFamilyCatalogCodec.requestBytes(evidence.request()).length + 16 + 4; + bytes[digestOffset + 7] = bytes[digestOffset + 7] == 'a' ? (byte) 'b' : (byte) 'a'; + assertThatThrownBy(() -> EntityRuntimeFamilyCatalogCodec.evidenceFromStored(bytes)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Request request() { + return new Request(UUID.randomUUID(), "test"); + } + + private static EntityRuntimeFamilyCatalog catalog() { + return EntityRuntimeFamilyCatalog.fromStored(CATALOG.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogTest.java new file mode 100644 index 0000000000..588b974763 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogTest.java @@ -0,0 +1,266 @@ +package unit.net.firedevops.firemud.common.social; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalogCodec; +import org.junit.jupiter.api.Test; + +/** + * Controlled exact catalog bytes exercise the value/codec, not an installed schema or FRESH proof. + */ +class SocialRuntimeFamilyCatalogTest { + private static final String CATALOG = + """ + {"schema":"social-runtime-family-catalog/v1","owner":"social-groups-service", + "catalogEpoch":"1","families":[ + {"familyId":"account_friend_links","relation":"account_friend_links","component":"", + "role":"SOCIAL_RELATIONSHIP","freshDisposition":"ACCOUNT_PAIR_SCOPE_DRIFT","targetOwner":"NONE"}, + {"familyId":"account_friend_links.account_id","relation":"account_friend_links","component":"account_id", + "role":"ACCOUNT_IDENTITY_CARRIER","freshDisposition":"ACCOUNT_IDENTITY_CARRIER_ONLY","targetOwner":"ACCOUNT_SERVICE"}, + {"familyId":"account_friend_links.friend_account_id","relation":"account_friend_links","component":"friend_account_id", + "role":"ACCOUNT_IDENTITY_CARRIER","freshDisposition":"ACCOUNT_IDENTITY_CARRIER_ONLY","targetOwner":"ACCOUNT_SERVICE"}], + "schemaFacts":[ + {"kind":"COLUMN","identity":"account_friend_links.account_id","definitionDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, + {"kind":"COLUMN","identity":"account_friend_links.friend_account_id","definitionDigest":"sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}, + {"kind":"TABLE","identity":"account_friend_links","definitionDigest":"sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"}], + "unimplementedContracts":["CHAT_RESTRICTION_AND_REVISION","DIRECTIONAL_BLOCK_LIFECYCLE", + "ENTITY_ESCROW_REFERENCE_FAMILIES","GAMEPLAY_WHISPER_NAMESPACE_SCOPE", + "SAFETY_EVIDENCE_AND_CONTENT_FREE_RECEIPTS","SOCIAL_PLAYER_STANDING_OWNER", + "SOCIAL_SAGA_ADOPTER_CLASSIFICATION"]} + """; + + @Test + void fixedRequestFramingAndStandardDigestVectorAreStable() { + var request = new Request(UUID.fromString("11111111-1111-4111-8111-111111111111"), "test"); + assertThat( + java.util.HexFormat.of() + .formatHex(SocialRuntimeFamilyCatalogCodec.requestBytes(request))) + .isEqualTo("53435231111111111111411181111111111111110000000474657374"); + assertThat(SocialRuntimeFamilyCatalog.sha256("abc".getBytes(StandardCharsets.US_ASCII))) + .isEqualTo("sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + } + + @Test + void exactTypedRoundtripPreservesOriginalBytesIdentityDigestsAndBlockingScope() { + byte[] source = CATALOG.getBytes(StandardCharsets.UTF_8); + var catalog = SocialRuntimeFamilyCatalog.fromStored(source); + var request = new Request(UUID.randomUUID(), "workload-test"); + var evidence = new Evidence(request, UUID.randomUUID(), catalog); + assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat(catalog.families()).hasSize(3); + assertThat(catalog.unimplementedContracts()) + .containsExactly( + SocialRuntimeFamilyCatalog.ContractGap.CHAT_RESTRICTION_AND_REVISION, + SocialRuntimeFamilyCatalog.ContractGap.DIRECTIONAL_BLOCK_LIFECYCLE, + SocialRuntimeFamilyCatalog.ContractGap.ENTITY_ESCROW_REFERENCE_FAMILIES, + SocialRuntimeFamilyCatalog.ContractGap.GAMEPLAY_WHISPER_NAMESPACE_SCOPE, + SocialRuntimeFamilyCatalog.ContractGap.SAFETY_EVIDENCE_AND_CONTENT_FREE_RECEIPTS, + SocialRuntimeFamilyCatalog.ContractGap.SOCIAL_PLAYER_STANDING_OWNER, + SocialRuntimeFamilyCatalog.ContractGap.SOCIAL_SAGA_ADOPTER_CLASSIFICATION); + assertThat(catalog.families().getFirst().freshDisposition()) + .isEqualTo(SocialRuntimeFamilyCatalog.FreshDisposition.ACCOUNT_PAIR_SCOPE_DRIFT); + assertThat(catalog.digest()).isEqualTo(SocialRuntimeFamilyCatalog.sha256(source)); + var wire = SocialRuntimeFamilyCatalogCodec.toResponse(request, evidence); + assertThat(SocialRuntimeFamilyCatalogCodec.fromResponse(request, wire)).isEqualTo(evidence); + assertThat( + SocialRuntimeFamilyCatalogCodec.fromRequest( + SocialRuntimeFamilyCatalogCodec.toRequest(request))) + .isEqualTo(request); + assertThat( + SocialRuntimeFamilyCatalogCodec.evidenceFromStored( + SocialRuntimeFamilyCatalogCodec.evidenceBytes(evidence)) + .digest()) + .isEqualTo(evidence.digest()); + source[0] = 0; + byte[] returned = catalog.exactBytes(); + returned[0] = 0; + assertThat(catalog.exactBytes()).isEqualTo(CATALOG.getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> catalog.families().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void refusesUnknownDuplicateMissingUnsupportedOrInconsistentCatalogFacts() { + for (String invalid : + new String[] { + CATALOG.replace("\"owner\":", "\"extra\":true,\"owner\":"), + CATALOG.replace( + "\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"1\",\"catalogEpoch\":\"1\""), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"0\""), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":1"), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"9223372036854775808\""), + CATALOG.replace("social-runtime-family-catalog/v1", "social-runtime-family-catalog/v2"), + CATALOG.replace("social-groups-service", "game-session-service"), + CATALOG.replace("ACCOUNT_PAIR_SCOPE_DRIFT", "CATALOG_ONLY"), + CATALOG.replace("SOCIAL_RELATIONSHIP", "UNKNOWN"), + CATALOG.replace("account_friend_links.friend_account_id", "renamed_friend_account_id"), + CATALOG.replace("ACCOUNT_SERVICE", "NONE"), + CATALOG.replace( + "\"kind\":\"TABLE\",\"identity\":\"account_friend_links\"", + "\"kind\":\"TABLE\",\"identity\":\"unknown_table\""), + CATALOG.replace( + "\"unimplementedContracts\":[", "\"unimplementedContracts\":[\"UNKNOWN_GAP\",") + }) { + assertThatThrownBy( + () -> SocialRuntimeFamilyCatalog.fromStored(invalid.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void familyAndFactBoundsAreIndependentOfRowAbsence() { + String family = + """ + {"familyId":"account_friend_links","relation":"account_friend_links","component":"", + "role":"SOCIAL_RELATIONSHIP","freshDisposition":"ACCOUNT_PAIR_SCOPE_DRIFT","targetOwner":"NONE"} + """; + String fact = + """ + {"kind":"TABLE","identity":"account_friend_links","definitionDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"} + """; + String prefix = + "{\"schema\":\"social-runtime-family-catalog/v1\",\"owner\":\"social-groups-service\",\"catalogEpoch\":\"1\","; + String gaps = + "\"unimplementedContracts\":[\"CHAT_RESTRICTION_AND_REVISION\",\"DIRECTIONAL_BLOCK_LIFECYCLE\"," + + "\"ENTITY_ESCROW_REFERENCE_FAMILIES\",\"GAMEPLAY_WHISPER_NAMESPACE_SCOPE\"," + + "\"SAFETY_EVIDENCE_AND_CONTENT_FREE_RECEIPTS\",\"SOCIAL_PLAYER_STANDING_OWNER\"," + + "\"SOCIAL_SAGA_ADOPTER_CLASSIFICATION\"]}"; + String manyFamilies = + prefix + + "\"families\":[" + + String.join(",", java.util.Collections.nCopies(513, family)) + + "],\"schemaFacts\":[" + + fact + + "]," + + gaps; + assertThatThrownBy( + () -> + SocialRuntimeFamilyCatalog.fromStored( + manyFamilies.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + String compactFact = + "{\"kind\":\"TYPE\",\"identity\":\"x\",\"definitionDigest\":\"sha256:" + + "a".repeat(64) + + "\"}"; + String manyFacts = + prefix + + "\"families\":[" + + family + + "],\"schemaFacts\":[" + + String.join(",", java.util.Collections.nCopies(16385, compactFact)) + + "]," + + gaps; + assertThatThrownBy( + () -> SocialRuntimeFamilyCatalog.fromStored(manyFacts.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsDuplicateUnknownOversizedAndChangedCorrelationWireValues() { + var request = new Request(UUID.randomUUID(), "test"); + var wire = SocialRuntimeFamilyCatalogCodec.toRequest(request); + assertThatThrownBy( + () -> + SocialRuntimeFamilyCatalogCodec.fromRequest( + wire.toBuilder() + .addCanonicalRequestBytes(wire.getCanonicalRequestBytes(0)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SocialRuntimeFamilyCatalogCodec.fromRequest( + wire.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 9, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SocialRuntimeFamilyCatalogCodec.fromRequest( + wire.toBuilder() + .setCanonicalRequestBytes(0, ByteString.copyFrom(new byte[1025])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + var evidence = new Evidence(request, UUID.randomUUID(), catalog()); + var response = SocialRuntimeFamilyCatalogCodec.toResponse(request, evidence); + assertThatThrownBy( + () -> + SocialRuntimeFamilyCatalogCodec.fromResponse( + new Request(UUID.randomUUID(), "test"), response)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SocialRuntimeFamilyCatalogCodec.fromResponse( + new Request(request.readRequestId(), "other"), response)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SocialRuntimeFamilyCatalogCodec.fromResponse( + request, + response.toBuilder() + .addCanonicalResponseBytes(response.getCanonicalResponseBytes(0)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SocialRuntimeFamilyCatalogCodec.fromResponse( + request, + response.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 9, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesTruncationTrailingDataDigestTamperingInvalidUtf8AndSourceBounds() { + var evidence = + new Evidence(new Request(UUID.randomUUID(), "test"), UUID.randomUUID(), catalog()); + byte[] bytes = SocialRuntimeFamilyCatalogCodec.evidenceBytes(evidence); + assertThatThrownBy( + () -> + SocialRuntimeFamilyCatalogCodec.evidenceFromStored( + Arrays.copyOf(bytes, bytes.length - 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SocialRuntimeFamilyCatalogCodec.evidenceFromStored( + Arrays.copyOf(bytes, bytes.length + 1))) + .isInstanceOf(IllegalArgumentException.class); + int digestOffset = + 4 + 4 + SocialRuntimeFamilyCatalogCodec.requestBytes(evidence.request()).length + 16 + 4; + bytes[digestOffset + 7] = bytes[digestOffset + 7] == 'a' ? (byte) 'b' : (byte) 'a'; + assertThatThrownBy(() -> SocialRuntimeFamilyCatalogCodec.evidenceFromStored(bytes)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> SocialRuntimeFamilyCatalog.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SocialRuntimeFamilyCatalog.fromStored( + new byte[SocialRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(new UUID(0, 0), "test")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(UUID.randomUUID(), "test/sa/social-groups-service")) + .isInstanceOf(IllegalArgumentException.class); + } + + private static SocialRuntimeFamilyCatalog catalog() { + return SocialRuntimeFamilyCatalog.fromStored(CATALOG.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogTest.java new file mode 100644 index 0000000000..c9f8ac334d --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogTest.java @@ -0,0 +1,222 @@ +package unit.net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalogCodec; +import org.junit.jupiter.api.Test; + +/** Controlled catalog bytes exercise the value/codec, not an installed schema or enrollment. */ +class WorldRuntimeFamilyCatalogTest { + private static final String CATALOG = + """ + {"schema":"world-runtime-family-catalog/v1","owner":"world-management-service", + "catalogEpoch":"1","families":[ + {"familyId":"world_instance","relation":"world_instance","component":"", + "role":"LIFECYCLE","stateClass":"S3","freshDisposition":"REQUIRED_LIFECYCLE"}], + "schemaFacts":[{"kind":"TABLE","identity":"world_instance", + "definitionDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]} + """; + + @Test + void fixedRequestFramingAndStandardDigestVectorAreStable() { + var request = new Request(UUID.fromString("11111111-1111-4111-8111-111111111111"), "test"); + assertThat( + java.util.HexFormat.of() + .formatHex(WorldRuntimeFamilyCatalogCodec.requestBytes(request))) + .isEqualTo("57435231111111111111411181111111111111110000000474657374"); + assertThat(WorldRuntimeFamilyCatalog.sha256("abc".getBytes(StandardCharsets.US_ASCII))) + .isEqualTo("sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + } + + @Test + void familyAndFactArrayBoundsAreIndependentOfPayloadRowAbsence() { + String family = + """ + {"familyId":"world_instance","relation":"world_instance","component":"", + "role":"LIFECYCLE","stateClass":"S3","freshDisposition":"REQUIRED_LIFECYCLE"} + """; + String fact = + """ + {"kind":"TABLE","identity":"world_instance", + "definitionDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"} + """; + String prefix = + "{\"schema\":\"world-runtime-family-catalog/v1\",\"owner\":\"world-management-service\",\"catalogEpoch\":\"1\","; + String manyFamilies = + prefix + + "\"families\":[" + + String.join(",", java.util.Collections.nCopies(513, family)) + + "],\"schemaFacts\":[" + + fact + + "]}"; + assertThatThrownBy( + () -> + WorldRuntimeFamilyCatalog.fromStored(manyFamilies.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + String compactFact = + "{\"kind\":\"TYPE\",\"identity\":\"x\",\"definitionDigest\":\"sha256:" + + "a".repeat(64) + + "\"}"; + String manyFacts = + prefix + + "\"families\":[" + + family + + "],\"schemaFacts\":[" + + String.join(",", java.util.Collections.nCopies(16385, compactFact)) + + "]}"; + assertThatThrownBy( + () -> WorldRuntimeFamilyCatalog.fromStored(manyFacts.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void exactTypedRoundtripPreservesOriginalBytesIdentityAndDigests() { + byte[] source = CATALOG.getBytes(StandardCharsets.UTF_8); + var catalog = WorldRuntimeFamilyCatalog.fromStored(source); + var read = new Request(UUID.randomUUID(), "test"); + var evidence = new Evidence(read, UUID.randomUUID(), catalog); + assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat(catalog.families()).hasSize(1); + assertThat(catalog.digest()).isEqualTo(WorldRuntimeFamilyCatalog.sha256(source)); + var response = WorldRuntimeFamilyCatalogCodec.toResponse(read, evidence); + assertThat(WorldRuntimeFamilyCatalogCodec.fromResponse(read, response)).isEqualTo(evidence); + assertThat( + WorldRuntimeFamilyCatalogCodec.fromRequest( + WorldRuntimeFamilyCatalogCodec.toRequest(read))) + .isEqualTo(read); + assertThat( + WorldRuntimeFamilyCatalogCodec.evidenceFromStored( + WorldRuntimeFamilyCatalogCodec.evidenceBytes(evidence)) + .digest()) + .isEqualTo(evidence.digest()); + source[0] = 0; + byte[] returned = catalog.exactBytes(); + returned[0] = 0; + assertThat(catalog.exactBytes()).isEqualTo(CATALOG.getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> catalog.families().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void refusesUnknownDuplicateMissingUnsupportedOrInconsistentCatalogFacts() { + for (String invalid : + new String[] { + CATALOG.replace("\"owner\":", "\"extra\":true,\"owner\":"), + CATALOG.replace( + "\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"1\",\"catalogEpoch\":\"1\""), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"0\""), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":1"), + CATALOG.replace("\"catalogEpoch\":\"1\"", "\"catalogEpoch\":\"9223372036854775808\""), + CATALOG.replace("world-runtime-family-catalog/v1", "world-runtime-family-catalog/v2"), + CATALOG.replace("world-management-service", "game-session-service"), + CATALOG.replace("\"S3\"", "\"NOT_PAYLOAD\""), + CATALOG.replace("\"LIFECYCLE\"", "\"UNKNOWN\""), + CATALOG.replace("\"REQUIRED_LIFECYCLE\"", "\"REQUIRED_TOPOLOGY\""), + CATALOG.replace("\"identity\":\"world_instance\"", "\"identity\":\"future_family\""), + CATALOG.replace("\"component\":\"\"", "\"component\":\"weather\""), + CATALOG + "{}" + }) { + assertThatThrownBy( + () -> WorldRuntimeFamilyCatalog.fromStored(invalid.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsUnknownDuplicateOversizedAndChangedCorrelationWireValues() { + var read = new Request(UUID.randomUUID(), "test"); + var request = WorldRuntimeFamilyCatalogCodec.toRequest(read); + assertThatThrownBy( + () -> + WorldRuntimeFamilyCatalogCodec.fromRequest( + request.toBuilder() + .addCanonicalRequestBytes(request.getCanonicalRequestBytes(0)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldRuntimeFamilyCatalogCodec.fromRequest( + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 9, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldRuntimeFamilyCatalogCodec.fromRequest( + request.toBuilder() + .setCanonicalRequestBytes(0, ByteString.copyFrom(new byte[1025])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + var evidence = new Evidence(read, UUID.randomUUID(), catalog()); + var response = WorldRuntimeFamilyCatalogCodec.toResponse(read, evidence); + assertThatThrownBy( + () -> + WorldRuntimeFamilyCatalogCodec.fromResponse( + new Request(UUID.randomUUID(), "test"), response)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldRuntimeFamilyCatalogCodec.fromResponse( + new Request(read.readRequestId(), "other"), response)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldRuntimeFamilyCatalogCodec.fromResponse( + read, + response.toBuilder() + .addCanonicalResponseBytes(response.getCanonicalResponseBytes(0)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesTruncationTrailingDataDigestTamperingInvalidUtf8AndSourceBounds() { + var evidence = + new Evidence(new Request(UUID.randomUUID(), "test"), UUID.randomUUID(), catalog()); + byte[] bytes = WorldRuntimeFamilyCatalogCodec.evidenceBytes(evidence); + assertThatThrownBy( + () -> + WorldRuntimeFamilyCatalogCodec.evidenceFromStored( + Arrays.copyOf(bytes, bytes.length - 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldRuntimeFamilyCatalogCodec.evidenceFromStored( + Arrays.copyOf(bytes, bytes.length + 1))) + .isInstanceOf(IllegalArgumentException.class); + // The digest string is outside the catalog bytes, so a complete parse must still refuse it. + int digestOffset = + 4 + 4 + WorldRuntimeFamilyCatalogCodec.requestBytes(evidence.request()).length + 16 + 4; + bytes[digestOffset + 7] = bytes[digestOffset + 7] == 'a' ? (byte) 'b' : (byte) 'a'; + assertThatThrownBy(() -> WorldRuntimeFamilyCatalogCodec.evidenceFromStored(bytes)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> WorldRuntimeFamilyCatalog.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldRuntimeFamilyCatalog.fromStored( + new byte[WorldRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(new UUID(0, 0), "test")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(UUID.randomUUID(), "1/sa/world-management-service")) + .isInstanceOf(IllegalArgumentException.class); + } + + private static WorldRuntimeFamilyCatalog catalog() { + return WorldRuntimeFamilyCatalog.fromStored(CATALOG.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogRepository.java new file mode 100644 index 0000000000..38692604ac --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogRepository.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Manual PostgreSQL census capture/readback. No actor reads, sampling, allocation or manifest. */ +public final class EntityRuntimeFamilyCatalogRepository { + private final DSLContext dsl; + private final String schema; + private final String namespace; + private final TransactionTemplate capture; + private final TransactionTemplate readback; + + public EntityRuntimeFamilyCatalogRepository( + DSLContext dsl, PlatformTransactionManager transactions, String schema, String namespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (schema == null + || !schema.matches("[a-z][a-z0-9_]{0,62}") + || !GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Fixed owner schema and workload namespace required"); + this.schema = schema; + this.namespace = namespace; + capture = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + capture.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + capture.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + readback = new TransactionTemplate(transactions); + readback.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readback.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readback.setReadOnly(true); + } + + public Evidence read(Request request) { + requireIndependent(request); + byte[] committed = + capture.execute( + status -> { + var catalog = currentCatalog(); + byte[] requestBytes = EntityRuntimeFamilyCatalogCodec.requestBytes(request); + var proposed = new Evidence(request, UUID.randomUUID(), catalog); + byte[] evidenceBytes = EntityRuntimeFamilyCatalogCodec.evidenceBytes(proposed); + dsl.execute( + "INSERT INTO " + + table("entity_runtime_family_catalog_snapshot") + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," + + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" + + " ON CONFLICT (read_request_id) DO NOTHING", + request.readRequestId(), + request.targetNamespace(), + requestBytes, + EntityRuntimeFamilyCatalog.sha256(requestBytes), + proposed.snapshotId(), + catalog.catalogEpoch(), + catalog.digest(), + evidenceBytes, + proposed.digest()); + return retained(request, catalog); + }); + Evidence result = readExact(request); + if (!Arrays.equals(committed, EntityRuntimeFamilyCatalogCodec.evidenceBytes(result))) + throw new CatalogConflictException("Committed catalog readback changed"); + return result; + } + + /** Independent committed readback; drift or missing evidence never becomes an empty success. */ + public Evidence readExact(Request request) { + requireIndependent(request); + return readback.execute( + status -> + EntityRuntimeFamilyCatalogCodec.evidenceFromStored( + retained(request, currentCatalog()))); + } + + private EntityRuntimeFamilyCatalog currentCatalog() { + Record row = + dsl.fetchOne( + "SELECT catalog_epoch,catalog_bytes,catalog_digest," + + schema + + ".entity_runtime_family_catalog_bytes(catalog_epoch) AS current_bytes FROM " + + table("entity_runtime_family_catalog_epoch") + + " WHERE " + + schema + + ".entity_runtime_family_catalog_installed() ORDER BY catalog_epoch DESC LIMIT 1"); + if (row == null) throw new CatalogConflictException("No durable Entity catalog epoch"); + byte[] sealed = row.get("catalog_bytes", byte[].class); + if (!Arrays.equals(sealed, row.get("current_bytes", byte[].class))) + throw new CatalogConflictException( + "Entity schema/classification drift invalidates its epoch"); + var catalog = EntityRuntimeFamilyCatalog.fromStored(sealed); + if (catalog.catalogEpoch() != row.get("catalog_epoch", Long.class) + || !catalog.digest().equals(row.get("catalog_digest", String.class))) + throw new CatalogConflictException("Entity catalog epoch/digest binding is inconsistent"); + return catalog; + } + + private byte[] retained(Request request, EntityRuntimeFamilyCatalog current) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + table("entity_runtime_family_catalog_snapshot") + + " WHERE read_request_id=?", + request.readRequestId()); + if (row == null) throw new CatalogConflictException("Exact Entity catalog snapshot is absent"); + byte[] bytes = row.get("evidence_bytes", byte[].class); + Evidence result = EntityRuntimeFamilyCatalogCodec.evidenceFromStored(bytes); + byte[] requestBytes = EntityRuntimeFamilyCatalogCodec.requestBytes(request); + if (!request.equals(result.request()) + || !request.targetNamespace().equals(row.get("target_namespace", String.class)) + || !Arrays.equals(requestBytes, row.get("request_bytes", byte[].class)) + || !EntityRuntimeFamilyCatalog.sha256(requestBytes) + .equals(row.get("request_digest", String.class)) + || !result.snapshotId().equals(row.get("snapshot_id", UUID.class)) + || result.catalog().catalogEpoch() != row.get("catalog_epoch", Long.class) + || !result.catalog().digest().equals(row.get("catalog_digest", String.class)) + || !result.digest().equals(row.get("evidence_digest", String.class)) + || !Arrays.equals(current.exactBytes(), result.catalog().exactBytes())) + throw new CatalogConflictException("Changed request or invalidated Entity catalog snapshot"); + return bytes; + } + + private String table(String name) { + return schema + "." + name; + } + + private void requireIndependent(Request request) { + Objects.requireNonNull(request, "request"); + if (!namespace.equals(request.targetNamespace())) + throw new CatalogConflictException("Wrong workload namespace"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException("Catalog evidence requires independent owner transactions"); + } + + public static final class CatalogConflictException extends IllegalStateException { + public CatalogConflictException(String message) { + super(message); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java new file mode 100644 index 0000000000..2868caea1c --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.entitymanagement.runtimecatalog; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Objects; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.repository.EntityRuntimeFamilyCatalogRepository; +import net.firedevops.firemud.entitymanagement.v1.EntityRuntimeFamilyCatalogReadServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ReadEntityRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadEntityRuntimeFamilyCatalogResponse; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Manually composed and unregistered. Workload guard precedes decoding and every SQL access. */ +public final class EntityRuntimeFamilyCatalogReadGrpcService + extends EntityRuntimeFamilyCatalogReadServiceGrpc + .EntityRuntimeFamilyCatalogReadServiceImplBase { + private final EntityRuntimeFamilyCatalogRepository repository; + private final String namespace; + + public EntityRuntimeFamilyCatalogReadGrpcService( + EntityRuntimeFamilyCatalogRepository repository, String namespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Fixed workload namespace required"); + this.namespace = namespace; + } + + @Override + public void readEntityRuntimeFamilyCatalog( + ReadEntityRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + refuse(observer, Status.UNAUTHENTICATED, "Authenticated workload required"); + return; + } + if (!peer.isService("game-session-service") + || !peer.isInNamespace(namespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + refuse( + observer, + Status.PERMISSION_DENIED, + "Exact same-namespace Game Session workload required without caller context"); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + refuse(observer, Status.FAILED_PRECONDITION, "Independent Entity owner operation required"); + return; + } + Request request; + try { + request = EntityRuntimeFamilyCatalogCodec.fromRequest(wire); + } catch (IllegalArgumentException invalid) { + refuse(observer, Status.INVALID_ARGUMENT, "Complete bounded catalog request required"); + return; + } + if (!namespace.equals(request.targetNamespace())) { + refuse( + observer, + Status.PERMISSION_DENIED, + "Request namespace differs from authenticated workload"); + return; + } + ReadEntityRuntimeFamilyCatalogResponse response; + try { + response = EntityRuntimeFamilyCatalogCodec.toResponse(request, repository.read(request)); + } catch (EntityRuntimeFamilyCatalogRepository.CatalogConflictException + | IllegalArgumentException invalid) { + refuse( + observer, + Status.FAILED_PRECONDITION, + "Entity catalog is changed, unsupported or inconsistent"); + return; + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException failure) { + refuse(observer, storageStatus(failure), "Entity catalog storage read failed"); + return; + } catch (org.springframework.transaction.CannotCreateTransactionException unavailable) { + refuse(observer, Status.UNAVAILABLE, "Entity catalog storage unavailable"); + return; + } catch (RuntimeException failure) { + refuse(observer, Status.INTERNAL, "Entity catalog read failed"); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static Status storageStatus(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql && sql.getSQLState() != null) { + String state = sql.getSQLState(); + if (state.startsWith("23") || state.startsWith("P0") || state.equals("55000")) + return Status.FAILED_PRECONDITION; + if (state.equals("40001") || state.equals("40P01")) return Status.ABORTED; + if (state.startsWith("08") || state.startsWith("57") || state.equals("55P03")) + return Status.UNAVAILABLE; + if (state.startsWith("22") || state.startsWith("42") || state.startsWith("XX")) + return Status.INTERNAL; + } + } + if (failure instanceof org.springframework.dao.DataIntegrityViolationException) + return Status.FAILED_PRECONDITION; + if (failure instanceof org.springframework.dao.TransientDataAccessException + || failure instanceof org.springframework.dao.DataAccessResourceFailureException + || failure instanceof org.jooq.exception.DataAccessException) return Status.UNAVAILABLE; + return Status.INTERNAL; + } + + private static void refuse(StreamObserver observer, Status status, String description) { + observer.onError(status.withDescription(description).asRuntimeException()); + } +} diff --git a/services/entity-management-service/src/main/resources/db/migration/V1025__entity_owner_runtime_family_catalog.sql b/services/entity-management-service/src/main/resources/db/migration/V1025__entity_owner_runtime_family_catalog.sql new file mode 100644 index 0000000000..80474a9828 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1025__entity_owner_runtime_family_catalog.sql @@ -0,0 +1,304 @@ +-- Additive owner-local metadata only. No actor, holder, source, history or sequence is rewritten. +CREATE TABLE entity_runtime_family_classification ( + family_id VARCHAR(127) PRIMARY KEY, + relation_name VARCHAR(63) NOT NULL, + component_name VARCHAR(63) NOT NULL DEFAULT '', + family_role VARCHAR(32) NOT NULL CHECK (family_role IN + ('RUNTIME_PAYLOAD','MIXED','SOURCE','IDENTITY','ASSIGNMENT','CREATION','DISCOVERY', + 'RETENTION','PROJECTION','REPLAY','AUDIT','CONTROL','PROVENANCE','ALLOCATOR','HISTORY','CATALOG')), + state_class VARCHAR(24) NOT NULL CHECK (state_class IN + ('S1','S2','S3','CONDITIONAL_S1_S2','CONDITIONAL_HOLDER','UNRESOLVED','NOT_PAYLOAD')), + fresh_disposition VARCHAR(48) NOT NULL CHECK (fresh_disposition IN + ('PROVISIONAL_NAMESPACE','TEMPLATE_MAPPING_REQUIRED','BLOCKING_NAMESPACE_REMAP', + 'BLOCKING_HOLDER_CLOSURE','BLOCKING_MIXED_NPC','BLOCKING_ALLOCATOR_CLASS', + 'GROUND_ONLY_S3','PROJECTION_S3_RETAIN_LINEAGE','AUTHORED_SOURCE_ONLY', + 'SELECTED_EMPTY_SOURCE_ONLY','IDENTITY_ONLY','ASSIGNMENT_ONLY','CREATE_ONLY', + 'DISCOVERY_ONLY','RETENTION_ONLY','REPLAY_ONLY','AUDIT_ONLY','CONTROL_ONLY', + 'PROVENANCE_ONLY','HISTORY_ONLY','CATALOG_ONLY')), + UNIQUE (relation_name, component_name), + CHECK (relation_name ~ '^[a-z][a-z0-9_]{0,62}$'), + CHECK (component_name = '' OR component_name ~ '^[a-z][a-z0-9_]{0,62}$'), + CHECK (family_id = relation_name || CASE WHEN component_name = '' THEN '' ELSE '.' || component_name END), + CHECK (family_role = CASE fresh_disposition + WHEN 'PROVISIONAL_NAMESPACE' THEN 'RUNTIME_PAYLOAD' + WHEN 'TEMPLATE_MAPPING_REQUIRED' THEN 'RUNTIME_PAYLOAD' + WHEN 'BLOCKING_NAMESPACE_REMAP' THEN 'RUNTIME_PAYLOAD' + WHEN 'BLOCKING_HOLDER_CLOSURE' THEN 'RUNTIME_PAYLOAD' + WHEN 'GROUND_ONLY_S3' THEN 'RUNTIME_PAYLOAD' + WHEN 'BLOCKING_MIXED_NPC' THEN 'MIXED' + WHEN 'BLOCKING_ALLOCATOR_CLASS' THEN 'ALLOCATOR' + WHEN 'PROJECTION_S3_RETAIN_LINEAGE' THEN 'PROJECTION' + WHEN 'AUTHORED_SOURCE_ONLY' THEN 'SOURCE' + WHEN 'SELECTED_EMPTY_SOURCE_ONLY' THEN 'SOURCE' + WHEN 'IDENTITY_ONLY' THEN 'IDENTITY' WHEN 'ASSIGNMENT_ONLY' THEN 'ASSIGNMENT' + WHEN 'CREATE_ONLY' THEN 'CREATION' WHEN 'DISCOVERY_ONLY' THEN 'DISCOVERY' + WHEN 'RETENTION_ONLY' THEN 'RETENTION' WHEN 'REPLAY_ONLY' THEN 'REPLAY' + WHEN 'AUDIT_ONLY' THEN 'AUDIT' WHEN 'CONTROL_ONLY' THEN 'CONTROL' + WHEN 'PROVENANCE_ONLY' THEN 'PROVENANCE' WHEN 'HISTORY_ONLY' THEN 'HISTORY' + WHEN 'CATALOG_ONLY' THEN 'CATALOG' END), + CHECK (state_class = CASE fresh_disposition + WHEN 'PROVISIONAL_NAMESPACE' THEN 'S1' WHEN 'TEMPLATE_MAPPING_REQUIRED' THEN 'S2' + WHEN 'BLOCKING_NAMESPACE_REMAP' THEN 'CONDITIONAL_S1_S2' + WHEN 'BLOCKING_HOLDER_CLOSURE' THEN 'CONDITIONAL_HOLDER' + WHEN 'BLOCKING_MIXED_NPC' THEN 'UNRESOLVED' + WHEN 'BLOCKING_ALLOCATOR_CLASS' THEN 'UNRESOLVED' + WHEN 'GROUND_ONLY_S3' THEN 'S3' WHEN 'PROJECTION_S3_RETAIN_LINEAGE' THEN 'S3' + ELSE 'NOT_PAYLOAD' END) +); + +CREATE TABLE entity_runtime_family_catalog_epoch ( + catalog_epoch BIGINT PRIMARY KEY CHECK (catalog_epoch > 0), + catalog_bytes BYTEA NOT NULL CHECK (octet_length(catalog_bytes) BETWEEN 1 AND 2097152), + catalog_digest VARCHAR(71) NOT NULL CHECK (catalog_digest = 'sha256:' || encode(sha256(catalog_bytes), 'hex')), + installed_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE entity_runtime_family_catalog_snapshot ( + read_request_id UUID PRIMARY KEY CHECK (read_request_id <> '00000000-0000-0000-0000-000000000000'), + target_namespace VARCHAR(63) NOT NULL CHECK (target_namespace ~ '^[a-z0-9]([-a-z0-9]*[a-z0-9])?$'), + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) BETWEEN 1 AND 1024), + request_digest VARCHAR(71) NOT NULL CHECK (request_digest = 'sha256:' || encode(sha256(request_bytes), 'hex')), + snapshot_id UUID NOT NULL UNIQUE CHECK (snapshot_id <> '00000000-0000-0000-0000-000000000000'), + catalog_epoch BIGINT NOT NULL REFERENCES entity_runtime_family_catalog_epoch(catalog_epoch), + catalog_digest VARCHAR(71) NOT NULL, + evidence_bytes BYTEA NOT NULL CHECK (octet_length(evidence_bytes) BETWEEN 1 AND 2101248), + evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest = 'sha256:' || encode(sha256(evidence_bytes), 'hex')), + retained_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +-- One explicit base disposition per actual installed table; components preserve mixed roles. +-- "character" is the logical family; characters is its sole physical and wire spelling. +INSERT INTO entity_runtime_family_classification + (family_id,relation_name,component_name,family_role,state_class,fresh_disposition) +VALUES + ('characters','characters','','RUNTIME_PAYLOAD','S1','PROVISIONAL_NAMESPACE'), + ('characters.body_layout_key','characters','body_layout_key','RUNTIME_PAYLOAD','S2','TEMPLATE_MAPPING_REQUIRED'), + ('characters.authored_initial_core_json','characters','authored_initial_core_json','RUNTIME_PAYLOAD','S2','TEMPLATE_MAPPING_REQUIRED'), + ('character_friend','character_friend','','RUNTIME_PAYLOAD','S1','PROVISIONAL_NAMESPACE'), + ('inventory','inventory','','RUNTIME_PAYLOAD','S2','TEMPLATE_MAPPING_REQUIRED'), + ('character_equipment','character_equipment','','RUNTIME_PAYLOAD','S2','TEMPLATE_MAPPING_REQUIRED'), + ('actor_resource_states','actor_resource_states','','RUNTIME_PAYLOAD','CONDITIONAL_S1_S2','BLOCKING_NAMESPACE_REMAP'), + ('actor_active_conditions','actor_active_conditions','','RUNTIME_PAYLOAD','CONDITIONAL_S1_S2','BLOCKING_NAMESPACE_REMAP'), + ('container_instances','container_instances','','RUNTIME_PAYLOAD','CONDITIONAL_HOLDER','BLOCKING_HOLDER_CLOSURE'), + ('item_instances','item_instances','','RUNTIME_PAYLOAD','CONDITIONAL_HOLDER','BLOCKING_HOLDER_CLOSURE'), + ('item_stacks','item_stacks','','RUNTIME_PAYLOAD','CONDITIONAL_HOLDER','BLOCKING_HOLDER_CLOSURE'), + ('room_ground_inventory','room_ground_inventory','','RUNTIME_PAYLOAD','S3','GROUND_ONLY_S3'), + ('npcs','npcs','','MIXED','UNRESOLVED','BLOCKING_MIXED_NPC'), + ('npcs.last_defeated_at','npcs','last_defeated_at','MIXED','UNRESOLVED','BLOCKING_MIXED_NPC'), + ('item_visible_ref_counters','item_visible_ref_counters','','ALLOCATOR','UNRESOLVED','BLOCKING_ALLOCATOR_CLASS'), + ('entity_preseeded_actor_runtime_projections','entity_preseeded_actor_runtime_projections','','PROJECTION','S3','PROJECTION_S3_RETAIN_LINEAGE'), + ('entity_player_created_runtime_projections','entity_player_created_runtime_projections','','PROJECTION','S3','PROJECTION_S3_RETAIN_LINEAGE'); + +INSERT INTO entity_runtime_family_classification + (family_id,relation_name,component_name,family_role,state_class,fresh_disposition) +SELECT 'characters.'||component,'characters',component,'PROVENANCE','NOT_PAYLOAD','PROVENANCE_ONLY' +FROM (VALUES ('account_id'),('tenant_id'),('playable_state_key'),('actor_identity_status'), + ('actor_identity_quarantine_reason'),('creation_target_namespace'),('creation_operation_id'), + ('actor_entry_policy'),('creation_descriptor_json'),('creation_descriptor_digest')) AS retained(component); + +INSERT INTO entity_runtime_family_classification + (family_id,relation_name,component_name,family_role,state_class,fresh_disposition) +SELECT 'npcs.'||component,'npcs',component,'SOURCE','NOT_PAYLOAD','AUTHORED_SOURCE_ONLY' +FROM (VALUES ('id'),('name'),('behavior'),('respawn_delay'),('tenant_id'),('version'),('version_id')) AS authored(component); + +INSERT INTO entity_runtime_family_classification + (family_id,relation_name,family_role,state_class,fresh_disposition) +SELECT name,name,'SOURCE','NOT_PAYLOAD','AUTHORED_SOURCE_ONLY' FROM (VALUES + ('items'),('crafting_recipes'),('crafting_ingredients'), + ('equipment_slot_definitions'),('body_layout_slot_definitions')) AS authored(name); + +INSERT INTO entity_runtime_family_classification + (family_id,relation_name,family_role,state_class,fresh_disposition) +SELECT name,name,'SOURCE','NOT_PAYLOAD','SELECTED_EMPTY_SOURCE_ONLY' FROM (VALUES + ('entity_empty_source_other_actor_template_roots'),('entity_empty_source_equipment_capabilities'), + ('entity_empty_source_equipment_attachment_rules'),('entity_empty_source_equipment_compatibility_rules'), + ('entity_empty_source_equipment_occupancy_rules'),('entity_empty_source_actor_body_layout_assignments'), + ('entity_empty_source_loot_table_roots'),('entity_empty_source_loot_item_mappings'), + ('entity_empty_source_inbound_loot_bindings'),('entity_empty_source_balance_curve_roots'), + ('entity_empty_source_balance_curve_attachments'),('entity_empty_source_archetype_roots'), + ('entity_empty_source_archetype_constraints'),('entity_empty_source_archetype_assignments')) AS empty_source(name); + +INSERT INTO entity_runtime_family_classification + (family_id,relation_name,family_role,state_class,fresh_disposition) +VALUES + ('entity_playable_state_namespace_scopes','entity_playable_state_namespace_scopes','IDENTITY','NOT_PAYLOAD','IDENTITY_ONLY'), + ('entity_tenant_identities','entity_tenant_identities','IDENTITY','NOT_PAYLOAD','IDENTITY_ONLY'), + ('entity_preseeded_actor_assignment_operations','entity_preseeded_actor_assignment_operations','ASSIGNMENT','NOT_PAYLOAD','ASSIGNMENT_ONLY'), + ('entity_character_create_roster_guards','entity_character_create_roster_guards','CONTROL','NOT_PAYLOAD','CONTROL_ONLY'), + ('entity_character_create_operations','entity_character_create_operations','CREATION','NOT_PAYLOAD','CREATE_ONLY'), + ('entity_canonical_gameplay_roster_snapshots','entity_canonical_gameplay_roster_snapshots','DISCOVERY','NOT_PAYLOAD','DISCOVERY_ONLY'), + ('entity_canonical_gameplay_roster_snapshot_actors','entity_canonical_gameplay_roster_snapshot_actors','DISCOVERY','NOT_PAYLOAD','DISCOVERY_ONLY'), + ('entity_canonical_roster_original_selections','entity_canonical_roster_original_selections','PROVENANCE','NOT_PAYLOAD','PROVENANCE_ONLY'), + ('entity_canonical_roster_admissions','entity_canonical_roster_admissions','CONTROL','NOT_PAYLOAD','CONTROL_ONLY'), + ('entity_canonical_roster_disposal_receipts','entity_canonical_roster_disposal_receipts','RETENTION','NOT_PAYLOAD','RETENTION_ONLY'), + ('entity_canonical_roster_retirement_transfers','entity_canonical_roster_retirement_transfers','RETENTION','NOT_PAYLOAD','RETENTION_ONLY'), + ('entity_canonical_roster_retention_lifecycle','entity_canonical_roster_retention_lifecycle','RETENTION','NOT_PAYLOAD','RETENTION_ONLY'), + ('entity_canonical_roster_retention_references','entity_canonical_roster_retention_references','RETENTION','NOT_PAYLOAD','RETENTION_ONLY'), + ('entity_canonical_roster_retention_releases','entity_canonical_roster_retention_releases','RETENTION','NOT_PAYLOAD','RETENTION_ONLY'), + ('entity_canonical_roster_target_classifications','entity_canonical_roster_target_classifications','CONTROL','NOT_PAYLOAD','CONTROL_ONLY'), + ('entity_canonical_roster_retired_targets','entity_canonical_roster_retired_targets','RETENTION','NOT_PAYLOAD','RETENTION_ONLY'), + ('entity_canonical_roster_snapshot_targets','entity_canonical_roster_snapshot_targets','CONTROL','NOT_PAYLOAD','CONTROL_ONLY'), + ('entity_empty_source_numeric_key_reservation','entity_empty_source_numeric_key_reservation','CONTROL','NOT_PAYLOAD','CONTROL_ONLY'), + ('entity_empty_selected_source_association','entity_empty_selected_source_association','PROVENANCE','NOT_PAYLOAD','PROVENANCE_ONLY'), + ('entity_empty_selected_source_family_state','entity_empty_selected_source_family_state','CONTROL','NOT_PAYLOAD','CONTROL_ONLY'), + ('entity_empty_selected_source_receipt','entity_empty_selected_source_receipt','PROVENANCE','NOT_PAYLOAD','PROVENANCE_ONLY'), + ('entity_mutation_effects','entity_mutation_effects','REPLAY','NOT_PAYLOAD','REPLAY_ONLY'), + ('item_transfer_audits','item_transfer_audits','AUDIT','NOT_PAYLOAD','AUDIT_ONLY'), + ('saga_instance','saga_instance','CONTROL','NOT_PAYLOAD','CONTROL_ONLY'), + ('saga_step','saga_step','CONTROL','NOT_PAYLOAD','CONTROL_ONLY'), + ('entity_runtime_family_classification','entity_runtime_family_classification','CATALOG','NOT_PAYLOAD','CATALOG_ONLY'), + ('entity_runtime_family_catalog_epoch','entity_runtime_family_catalog_epoch','CATALOG','NOT_PAYLOAD','CATALOG_ONLY'), + ('entity_runtime_family_catalog_snapshot','entity_runtime_family_catalog_snapshot','CATALOG','NOT_PAYLOAD','CATALOG_ONLY'); + +-- Flyway 13 supplies the ACTUAL configured history identifier. No deployment-name fallback. +-- Ordinary tables/metadata above remain visible to jOOQ. Only PostgreSQL census/guards/seed below +-- are excluded from DDLDatabase simulation. This is not an H2 simulation of pg_catalog. +-- [jooq ignore start] +INSERT INTO entity_runtime_family_classification + (family_id,relation_name,family_role,state_class,fresh_disposition) +VALUES ('${flyway:table}','${flyway:table}','HISTORY','NOT_PAYLOAD','HISTORY_ONLY'); + +CREATE FUNCTION entity_runtime_family_catalog_installed() RETURNS BOOLEAN LANGUAGE SQL STABLE +SET search_path = "${serviceSchema}", pg_catalog AS $$ + SELECT EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1025' AND script='V1025__entity_owner_runtime_family_catalog.sql' AND success); +$$; + +CREATE FUNCTION entity_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE v_families JSONB; v_facts JSONB; +BEGIN + IF p_epoch IS NULL OR p_epoch<=0 THEN + RAISE EXCEPTION 'Positive Entity catalog epoch required' USING ERRCODE='23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM entity_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM entity_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed Entity schema family' USING ERRCODE='23514'; + END IF; + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name, + 'component',component_name,'role',family_role,'stateClass',state_class, + 'freshDisposition',fresh_disposition) ORDER BY family_id COLLATE "C") + INTO v_families FROM entity_runtime_family_classification; + + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname,jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,pg_get_viewdef(c.oid,true) FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1025' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1025','V1025__entity_owner_runtime_family_catalog.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + IF jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 THEN + RAISE EXCEPTION 'Complete Entity catalog exceeds source bounds' USING ERRCODE='23514'; + END IF; + RETURN convert_to(jsonb_build_object('schema','entity-runtime-family-catalog/v1', + 'owner','entity-management-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts)::TEXT,'UTF8'); +END; +$$; + +CREATE FUNCTION entity_runtime_catalog_immutable() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Entity runtime catalog evidence is immutable' USING ERRCODE='23514'; +END; +$$; +CREATE TRIGGER entity_runtime_classification_retained BEFORE UPDATE OR DELETE OR TRUNCATE +ON entity_runtime_family_classification FOR EACH STATEMENT EXECUTE FUNCTION entity_runtime_catalog_immutable(); +CREATE TRIGGER entity_runtime_epoch_retained BEFORE UPDATE OR DELETE OR TRUNCATE +ON entity_runtime_family_catalog_epoch FOR EACH STATEMENT EXECUTE FUNCTION entity_runtime_catalog_immutable(); +CREATE TRIGGER entity_runtime_snapshot_retained BEFORE UPDATE OR DELETE OR TRUNCATE +ON entity_runtime_family_catalog_snapshot FOR EACH STATEMENT EXECUTE FUNCTION entity_runtime_catalog_immutable(); + +CREATE FUNCTION entity_runtime_catalog_epoch_guard() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = "${serviceSchema}", pg_catalog AS $$ +BEGIN + IF NEW.catalog_epoch<>coalesce((SELECT max(catalog_epoch) FROM entity_runtime_family_catalog_epoch),0)+1 + OR NEW.catalog_bytes<>entity_runtime_family_catalog_bytes(NEW.catalog_epoch) THEN + RAISE EXCEPTION 'Entity epoch must bind the exact classified installed schema' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER entity_runtime_epoch_exact BEFORE INSERT ON entity_runtime_family_catalog_epoch +FOR EACH ROW EXECUTE FUNCTION entity_runtime_catalog_epoch_guard(); + +CREATE FUNCTION entity_runtime_catalog_snapshot_guard() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE v_epoch entity_runtime_family_catalog_epoch%ROWTYPE; +BEGIN + SELECT * INTO STRICT v_epoch FROM entity_runtime_family_catalog_epoch ORDER BY catalog_epoch DESC LIMIT 1; + IF NEW.catalog_epoch<>v_epoch.catalog_epoch OR NEW.catalog_digest<>v_epoch.catalog_digest + OR entity_runtime_family_catalog_bytes(v_epoch.catalog_epoch)<>v_epoch.catalog_bytes + OR NOT entity_runtime_family_catalog_installed() THEN + RAISE EXCEPTION 'Entity runtime catalog changed; new owner epoch required' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER entity_runtime_snapshot_current BEFORE INSERT ON entity_runtime_family_catalog_snapshot +FOR EACH ROW EXECUTE FUNCTION entity_runtime_catalog_snapshot_guard(); + +-- Flyway writes V1025's own history row AFTER this transaction. The stable marker above replaces +-- that row in the seal; readers separately require its successful exact script installation. +-- Its post-transaction checksum/timing is not falsely claimed as part of this initial preimage. +INSERT INTO entity_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT 1,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM (SELECT entity_runtime_family_catalog_bytes(1) AS bytes) seal; +-- [jooq ignore stop] diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index 4bdb401b53..75f0a23473 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -505,7 +505,7 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( .extracting(AppliedMigration::version) .containsExactly( "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016", "1017", - "1018", "1019", "1020", "1021", "1022", "1023", "1024"); + "1018", "1019", "1020", "1021", "1022", "1023", "1024", "1025"); assertThat(successorHistory) .extracting(AppliedMigration::script) .containsExactly( @@ -526,7 +526,8 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( "V1021__character_create_binary_safe_immutability.sql", "V1022__preseeded_runtime_actor_projection.sql", "V1023__player_created_runtime_projection.sql", - "V1024__ordinary_account_uuid_owner.sql"); + "V1024__ordinary_account_uuid_owner.sql", + "V1025__entity_owner_runtime_family_catalog.sql"); assertThat(successorHistory).extracting(AppliedMigration::checksum).doesNotContainNull(); try (Connection connection = connectToSchema(schema)) { diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index 8a99c99f21..276f2c49d9 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -642,7 +642,7 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020", "1021", - "1022", "1023", "1024"); + "1022", "1023", "1024", "1025"); assertThat(flyway.info().applied()) .filteredOn(migration -> migration.getVersion() != null) .extracting(migration -> migration.getScript()) @@ -671,9 +671,10 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { "V1021__character_create_binary_safe_immutability.sql", "V1022__preseeded_runtime_actor_projection.sql", "V1023__player_created_runtime_projection.sql", - "V1024__ordinary_account_uuid_owner.sql"); + "V1024__ordinary_account_uuid_owner.sql", + "V1025__entity_owner_runtime_family_catalog.sql"); assertThat(flyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1024")); + .isEqualTo(MigrationVersion.fromVersion("1025")); assertThat(flyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); @@ -747,7 +748,7 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020", "1021", - "1022", "1023", "1024"); + "1022", "1023", "1024", "1025"); assertThat(upgradedHistory) .extracting(MigrationHistoryEntry::script) .containsExactly( @@ -775,7 +776,8 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro "V1021__character_create_binary_safe_immutability.sql", "V1022__preseeded_runtime_actor_projection.sql", "V1023__player_created_runtime_projection.sql", - "V1024__ordinary_account_uuid_owner.sql"); + "V1024__ordinary_account_uuid_owner.sql", + "V1025__entity_owner_runtime_family_catalog.sql"); assertThat(upgradedHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); try (Connection connection = connectToMigrationSchema(); @@ -1041,7 +1043,7 @@ private void migrateLegacySchemaToLatest() { assertThat(upgradeFlyway.getConfiguration().isOutOfOrder()).isFalse(); upgradeFlyway.migrate(); assertThat(upgradeFlyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1024")); + .isEqualTo(MigrationVersion.fromVersion("1025")); assertThat(upgradeFlyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java index 14d22663a2..57808515fb 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java @@ -137,7 +137,7 @@ void upgradesActualEntity1014ParentWithoutChangingRetainedActorOrRosterRows() { DSLContext upgradedDsl = DSL.using(parentDataSource, SQLDialect.POSTGRES); assertThat(migrationHistory(upgradedDsl).subList(0, parentHistory.size())) .containsExactlyElementsOf(parentHistory); - assertThat(migrationVersions(upgradedDsl)).contains("1017").last().isEqualTo("1024"); + assertThat(migrationVersions(upgradedDsl)).contains("1017").last().isEqualTo("1025"); assertThat(retainedParentRows(upgradedDsl, character, snapshot)) .containsExactlyElementsOf(retainedRows); assertThat( @@ -183,7 +183,7 @@ void binaryGuardUpgradePreservesCreatedRowsHistoryAndTerminalReplay() throws Exc assertThat(migrationHistory(retainedDsl).subList(0, historyBefore.size())) .containsExactlyElementsOf(historyBefore); - assertThat(migrationVersions(retainedDsl)).last().isEqualTo("1024"); + assertThat(migrationVersions(retainedDsl)).last().isEqualTo("1025"); assertThat(retainedDsl.fetch(retainedRowsSql).getValues(0, String.class)) .containsExactlyElementsOf(before); assertThat(retainedRepository.settle(retainedProof, null)).isEqualTo(terminal); @@ -256,7 +256,7 @@ void upgradesRetainedV1016CreatedActorBeforeQuarantineWithoutChangingRows() thro migrate(retainedDataSource, retainedSchema, null); - assertThat(migrationVersions(retainedDsl)).contains("1017").last().isEqualTo("1024"); + assertThat(migrationVersions(retainedDsl)).contains("1017").last().isEqualTo("1025"); assertThat(retainedRow(retainedDsl, "characters", "character_uuid", characterId)) .isEqualTo(actorBefore); assertThat( diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java index 2694d5ea72..214f5de03d 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java @@ -106,7 +106,7 @@ void seedLegacyRowsBeforeV1011() { dsl.fetchSingle( "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") .get(0, String.class)) - .isEqualTo("1024"); + .isEqualTo("1025"); } @AfterEach diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java new file mode 100644 index 0000000000..b9c0c29a1b --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -0,0 +1,677 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.FactKind; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.FreshDisposition; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Role; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.StateClass; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.entitymanagement.runtimecatalog.EntityRuntimeFamilyCatalogReadGrpcService; +import net.firedevops.firemud.entitymanagement.v1.ReadEntityRuntimeFamilyCatalogResponse; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real Entity/Saga migrations and PostgreSQL census. Controlled SQL identities and RPC context are + * not genuine upstream custody/PKI, FRESH materialization or cross-owner completeness proof. + * Repository reconstruction proves durable readback, not operating-system process-death recovery. + */ +@Testcontainers +@Timeout(value = 3, unit = TimeUnit.MINUTES) +@SuppressWarnings("resource") +class EntityRuntimeFamilyCatalogPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private static final String HISTORY = "flyway_schema_history_entity_management_service"; + + @Test + void actualCombinedMigrationsYieldExactCompleteCensusIncludingOwnInfrastructure() { + try (var f = fixture(null, HISTORY)) { + var catalog = f.owner().read(request()).catalog(); + assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat( + catalog.schemaFacts().stream() + .filter(fact -> fact.kind() == FactKind.TABLE) + .map(EntityRuntimeFamilyCatalog.SchemaFact::identity) + .toList()) + .hasSize(62) + .containsExactlyInAnyOrderElementsOf( + f.dsl + .fetch( + "SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=? AND c.relkind IN ('r','p','f')", + f.schema) + .getValues(0, String.class)); + assertThat(catalog.families().stream().filter(family -> family.component().isEmpty()).count()) + .isEqualTo(62); + assertFamily( + catalog, + "saga_instance", + Role.CONTROL, + StateClass.NOT_PAYLOAD, + FreshDisposition.CONTROL_ONLY); + assertFamily( + catalog, + "saga_step", + Role.CONTROL, + StateClass.NOT_PAYLOAD, + FreshDisposition.CONTROL_ONLY); + assertFamily( + catalog, HISTORY, Role.HISTORY, StateClass.NOT_PAYLOAD, FreshDisposition.HISTORY_ONLY); + assertFamily( + catalog, + "entity_runtime_family_catalog_snapshot", + Role.CATALOG, + StateClass.NOT_PAYLOAD, + FreshDisposition.CATALOG_ONLY); + assertThat(catalog.schemaFacts()) + .anyMatch(fact -> fact.kind() == FactKind.ROUTINE) + .anyMatch(fact -> fact.kind() == FactKind.COLUMN) + .anyMatch( + fact -> + fact.kind() == FactKind.SEQUENCE + && fact.identity().equals("entity_runtime_entity_id_sequence")) + .anyMatch(fact -> fact.kind() == FactKind.MIGRATION && fact.identity().contains("1004")) + .anyMatch( + fact -> + fact.kind() == FactKind.MIGRATION + && fact.identity().equals("catalog-installation:1025")); + assertThat( + f.dsl + .fetchSingle( + "SELECT catalog_bytes=entity_runtime_family_catalog_bytes(catalog_epoch) FROM entity_runtime_family_catalog_epoch") + .get(0, Boolean.class)) + .isTrue(); + assertThat( + f.dsl + .fetch( + "SELECT version FROM " + + HISTORY + + " WHERE version IS NOT NULL ORDER BY installed_rank") + .getValues(0, String.class)) + .containsExactly( + "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", + "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020", + "1021", "1022", "1023", "1024", "1025"); + } + } + + @Test + void conditionalAndMixedFamiliesAreExplicitBlockingFactsEvenWithZeroRows() { + try (var f = fixture(null, HISTORY)) { + var catalog = f.owner().read(request()).catalog(); + for (String name : List.of("actor_resource_states", "actor_active_conditions")) { + assertFamily( + catalog, + name, + Role.RUNTIME_PAYLOAD, + StateClass.CONDITIONAL_S1_S2, + FreshDisposition.BLOCKING_NAMESPACE_REMAP); + assertThat(f.count(name)).isZero(); + } + for (String name : List.of("item_instances", "container_instances", "item_stacks")) + assertFamily( + catalog, + name, + Role.RUNTIME_PAYLOAD, + StateClass.CONDITIONAL_HOLDER, + FreshDisposition.BLOCKING_HOLDER_CLOSURE); + assertFamily( + catalog, "npcs", Role.MIXED, StateClass.UNRESOLVED, FreshDisposition.BLOCKING_MIXED_NPC); + assertFamily( + catalog, + "npcs.last_defeated_at", + Role.MIXED, + StateClass.UNRESOLVED, + FreshDisposition.BLOCKING_MIXED_NPC); + assertFamily( + catalog, + "npcs.behavior", + Role.SOURCE, + StateClass.NOT_PAYLOAD, + FreshDisposition.AUTHORED_SOURCE_ONLY); + assertFamily( + catalog, + "item_visible_ref_counters", + Role.ALLOCATOR, + StateClass.UNRESOLVED, + FreshDisposition.BLOCKING_ALLOCATOR_CLASS); + assertFamily( + catalog, + "inventory", + Role.RUNTIME_PAYLOAD, + StateClass.S2, + FreshDisposition.TEMPLATE_MAPPING_REQUIRED); + assertFamily( + catalog, + "character_equipment", + Role.RUNTIME_PAYLOAD, + StateClass.S2, + FreshDisposition.TEMPLATE_MAPPING_REQUIRED); + assertFamily( + catalog, + "characters", + Role.RUNTIME_PAYLOAD, + StateClass.S1, + FreshDisposition.PROVISIONAL_NAMESPACE); + assertFamily( + catalog, + "characters.body_layout_key", + Role.RUNTIME_PAYLOAD, + StateClass.S2, + FreshDisposition.TEMPLATE_MAPPING_REQUIRED); + assertFamily( + catalog, + "character_friend", + Role.RUNTIME_PAYLOAD, + StateClass.S1, + FreshDisposition.PROVISIONAL_NAMESPACE); + assertFamily( + catalog, + "room_ground_inventory", + Role.RUNTIME_PAYLOAD, + StateClass.S3, + FreshDisposition.GROUND_ONLY_S3); + for (String name : + List.of( + "entity_preseeded_actor_runtime_projections", + "entity_player_created_runtime_projections")) + assertFamily( + catalog, + name, + Role.PROJECTION, + StateClass.S3, + FreshDisposition.PROJECTION_S3_RETAIN_LINEAGE); + assertFamily( + catalog, + "entity_mutation_effects", + Role.REPLAY, + StateClass.NOT_PAYLOAD, + FreshDisposition.REPLAY_ONLY); + assertFamily( + catalog, + "entity_character_create_operations", + Role.CREATION, + StateClass.NOT_PAYLOAD, + FreshDisposition.CREATE_ONLY); + assertFamily( + catalog, + "entity_preseeded_actor_assignment_operations", + Role.ASSIGNMENT, + StateClass.NOT_PAYLOAD, + FreshDisposition.ASSIGNMENT_ONLY); + assertFamily( + catalog, + "entity_empty_source_archetype_roots", + Role.SOURCE, + StateClass.NOT_PAYLOAD, + FreshDisposition.SELECTED_EMPTY_SOURCE_ONLY); + assertThat(catalog.families()) + .noneMatch( + family -> + family.familyId().equals("entity_tick_state") + || family.familyId().equals("character")); + } + } + + @Test + void configuredHistoryNamesBindActualHistoryWithoutHardcodedFallback() { + for (String history : + List.of("flyway_schema_history", "flyway_schema_history_public", "custom_entity_history")) { + try (var f = fixture(null, history)) { + var original = f.owner().read(request()); + assertFamily( + original.catalog(), + history, + Role.HISTORY, + StateClass.NOT_PAYLOAD, + FreshDisposition.HISTORY_ONLY); + assertThat(f.owner().readExact(original.request())).isEqualTo(original); + assertThat( + f.dsl + .fetchSingle("SELECT to_regclass(?) IS NULL", f.schema + "." + HISTORY) + .get(0, Boolean.class)) + .isTrue(); + } + } + } + + @Test + void exactReplayRestartIndependentReadbackAndChangedRequestConflict() { + try (var f = fixture(null, HISTORY)) { + var read = request(); + var original = f.owner().read(read); + assertThat(f.owner().read(read)).isEqualTo(original); + assertThat(f.owner().readExact(read)).isEqualTo(original); + assertThat(f.count("entity_runtime_family_catalog_snapshot")).isEqualTo(1); + var other = f.owner().read(request()); + assertThat(other.snapshotId()).isNotEqualTo(original.snapshotId()); + assertThat(other.catalog().exactBytes()).isEqualTo(original.catalog().exactBytes()); + var otherOwner = + new EntityRuntimeFamilyCatalogRepository(f.dsl, f.manager, f.schema, "other"); + assertThatThrownBy(() -> otherOwner.read(new Request(read.readRequestId(), "other"))) + .isInstanceOf(EntityRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.count("entity_runtime_family_catalog_snapshot")).isEqualTo(2); + assertThatThrownBy(() -> f.owner().readExact(request())) + .isInstanceOf(EntityRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy( + () -> new TransactionTemplate(f.manager).execute(status -> f.owner().read(request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent"); + } + } + + @Test + void actualConcurrentIdenticalRequestsConvergeOnOneCommittedSnapshot() throws Exception { + try (var f = fixture(null, HISTORY); + var workers = Executors.newFixedThreadPool(2)) { + var read = request(); + var first = workers.submit(() -> f.owner().read(read)); + var second = workers.submit(() -> f.owner().read(read)); + assertThat(first.get(30, TimeUnit.SECONDS)).isEqualTo(second.get(30, TimeUnit.SECONDS)); + assertThat(f.count("entity_runtime_family_catalog_snapshot")).isEqualTo(1); + } + } + + @Test + void additiveUpgradePreservesPopulatedActorHolderAuthoredReplayAuditSagaAndHistoryRows() { + try (var f = fixture("1024", HISTORY)) { + seedRetained(f.dsl); + List tables = + List.of( + "characters", + "npcs", + "items", + "inventory", + "character_friend", + "character_equipment", + "actor_resource_states", + "actor_active_conditions", + "container_instances", + "item_instances", + "item_stacks", + "item_visible_ref_counters", + "room_ground_inventory", + "crafting_recipes", + "crafting_ingredients", + "equipment_slot_definitions", + "body_layout_slot_definitions", + "item_transfer_audits", + "entity_mutation_effects", + "saga_instance", + "saga_step"); + var before = new LinkedHashMap>(); + tables.forEach(table -> before.put(table, f.rows(table))); + var history = f.rows(HISTORY); + String sequence = + f.dsl + .fetchSingle( + "SELECT last_value::text||':'||is_called::text FROM entity_runtime_entity_id_sequence") + .get(0, String.class); + migration(f.source, f.schema, HISTORY, null).load().migrate(); + tables.forEach(table -> assertThat(f.rows(table)).as(table).isEqualTo(before.get(table))); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(t)::text||':'||xmin::text FROM " + + HISTORY + + " t WHERE version IS DISTINCT FROM '1025' ORDER BY installed_rank") + .getValues(0, String.class)) + .containsExactlyInAnyOrderElementsOf(history); + f.owner().read(request()); + tables.forEach(table -> assertThat(f.rows(table)).as(table).isEqualTo(before.get(table))); + assertThat( + f.dsl + .fetchSingle( + "SELECT last_value::text||':'||is_called::text FROM entity_runtime_entity_id_sequence") + .get(0, String.class)) + .isEqualTo(sequence); + assertThat(f.count("entity_preseeded_actor_runtime_projections")).isZero(); + assertThat(f.count("entity_player_created_runtime_projections")).isZero(); + migration(f.source, f.schema, HISTORY, null).load().validate(); + } + } + + @Test + void unknownEmptyTableRefusesInitialInstallAtomicallyAndInvalidatesExistingSeal() { + try (var f = fixture("1024", HISTORY)) { + var history = f.rows(HISTORY); + f.dsl.execute("CREATE TABLE unknown_runtime_family(id BIGINT PRIMARY KEY)"); + assertThatThrownBy(() -> migration(f.source, f.schema, HISTORY, null).load().migrate()) + .hasMessageContaining("Unclassified or changed"); + assertThat( + f.dsl + .fetchSingle( + "SELECT to_regclass(?) IS NULL", + f.schema + ".entity_runtime_family_catalog_epoch") + .get(0, Boolean.class)) + .isTrue(); + assertThat(f.rows(HISTORY)).isEqualTo(history); + } + try (var f = fixture(null, HISTORY)) { + var read = request(); + f.owner().read(read); + f.dsl.execute("CREATE TABLE unknown_runtime_family(id BIGINT PRIMARY KEY)"); + assertThatThrownBy(() -> f.owner().readExact(read)) + .hasMessageContaining("Unclassified or changed"); + assertThatThrownBy(() -> f.owner().read(request())) + .hasMessageContaining("Unclassified or changed"); + assertThat(f.count("unknown_runtime_family")).isZero(); + assertThat(f.count("entity_runtime_family_catalog_snapshot")).isEqualTo(1); + } + } + + @Test + void columnTableRoutineConstraintAndSequenceDefinitionDriftCannotResample() { + for (String change : + List.of( + "ALTER TABLE npcs ADD COLUMN future_state TEXT", + "ALTER TABLE npcs RENAME COLUMN last_defeated_at TO defeated_later", + "ALTER TABLE npcs ALTER COLUMN behavior TYPE VARCHAR(120)", + "ALTER TABLE npcs ADD CONSTRAINT catalog_probe CHECK(id>0)", + "ALTER TABLE npcs RENAME TO renamed_npcs", + "CREATE FUNCTION future_writer() RETURNS INTEGER LANGUAGE SQL AS 'SELECT 1'", + "ALTER SEQUENCE entity_runtime_entity_id_sequence INCREMENT BY 2")) { + try (var f = fixture(null, HISTORY)) { + var read = request(); + f.owner().read(read); + f.dsl.execute(change); + assertThatThrownBy(() -> f.owner().readExact(read)).isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> f.owner().read(request())).isInstanceOf(RuntimeException.class); + assertThat(f.count("entity_runtime_family_catalog_snapshot")).isEqualTo(1); + } + } + } + + @Test + void missingTableClassificationAndMigrationChangesInvalidateWithoutRewritingEvidence() { + for (String change : + List.of( + "DROP TABLE npcs", + "INSERT INTO entity_runtime_family_classification VALUES ('npcs.version_id_extra','npcs','version_id_extra','SOURCE','NOT_PAYLOAD','AUTHORED_SOURCE_ONLY')", + "UPDATE " + HISTORY + " SET checksum=checksum+1 WHERE version='1'", + "UPDATE " + HISTORY + " SET success=false WHERE version='1025'", + "UPDATE " + HISTORY + " SET script='other.sql' WHERE version='1025'")) { + try (var f = fixture(null, HISTORY)) { + var read = request(); + var original = f.owner().read(read); + f.dsl.execute(change); + assertThatThrownBy(() -> f.owner().readExact(read)).isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> f.owner().read(request())).isInstanceOf(RuntimeException.class); + assertThat( + f.dsl + .fetchSingle( + "SELECT evidence_bytes FROM entity_runtime_family_catalog_snapshot WHERE read_request_id=?", + read.readRequestId()) + .get(0, byte[].class)) + .isEqualTo(EntityRuntimeFamilyCatalogCodec.evidenceBytes(original)); + } + } + } + + @Test + void validNewClassificationRequiresExplicitNewOwnerEpochAndInvalidatesOldRequest() { + try (var f = fixture(null, HISTORY)) { + var read = request(); + var original = f.owner().read(read); + f.dsl.execute( + "INSERT INTO entity_runtime_family_classification VALUES ('items.name','items','name','SOURCE','NOT_PAYLOAD','AUTHORED_SOURCE_ONLY')"); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(EntityRuntimeFamilyCatalogRepository.CatalogConflictException.class); + f.dsl.execute( + "INSERT INTO entity_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" + + " SELECT 2,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM (SELECT entity_runtime_family_catalog_bytes(2) AS bytes) revised"); + assertThatThrownBy(() -> f.owner().read(read)) + .isInstanceOf(EntityRuntimeFamilyCatalogRepository.CatalogConflictException.class); + var revised = f.owner().read(request()); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(2); + assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); + assertThat( + f.dsl + .fetchSingle( + "SELECT evidence_bytes FROM entity_runtime_family_catalog_snapshot WHERE read_request_id=?", + read.readRequestId()) + .get(0, byte[].class)) + .isEqualTo(EntityRuntimeFamilyCatalogCodec.evidenceBytes(original)); + } + } + + @Test + void metadataEpochAndSnapshotsRemainImmutableAndWrongSealCannotBeInserted() { + try (var f = fixture(null, HISTORY)) { + f.owner().read(request()); + for (String table : + List.of( + "entity_runtime_family_classification", + "entity_runtime_family_catalog_epoch", + "entity_runtime_family_catalog_snapshot")) { + assertThatThrownBy(() -> f.dsl.execute("DELETE FROM " + table)) + .hasMessageContaining("immutable"); + assertThatThrownBy(() -> f.dsl.execute("TRUNCATE " + table + " CASCADE")) + .hasMessageContaining("immutable"); + } + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE entity_runtime_family_classification SET state_class='S3' WHERE family_id='item_instances'")) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO entity_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" + + " SELECT 2,catalog_bytes,catalog_digest FROM entity_runtime_family_catalog_epoch WHERE catalog_epoch=1")) + .hasMessageContaining("exact classified installed schema"); + } + } + + @Test + void actualHandlerReturnsCommittedExactEvidenceWithoutCreatingActorsOrRuntime() { + try (var f = fixture(null, HISTORY)) { + var read = request(); + var collector = new Collector(); + var service = new EntityRuntimeFamilyCatalogReadGrpcService(f.owner(), "test"); + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") + .orElseThrow(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> + service.readEntityRuntimeFamilyCatalog( + EntityRuntimeFamilyCatalogCodec.toRequest(read), collector)); + assertThat(collector.error).isNull(); + assertThat(collector.completed).isTrue(); + assertThat(EntityRuntimeFamilyCatalogCodec.fromResponse(read, collector.value)) + .isEqualTo(f.owner().readExact(read)); + for (String table : + List.of( + "characters", + "actor_resource_states", + "actor_active_conditions", + "entity_character_create_operations", + "entity_preseeded_actor_runtime_projections", + "entity_player_created_runtime_projections")) assertThat(f.count(table)).isZero(); + } + } + + private static void seedRetained(DSLContext dsl) { + dsl.execute( + "INSERT INTO characters(id,account_id,name,tenant_id) VALUES (101,81,'retained',71),(102,82,'friend',71)"); + dsl.execute( + "INSERT INTO npcs(name,behavior,last_defeated_at,tenant_id) VALUES ('mixed','guard','2020-01-01',71)"); + dsl.execute( + "INSERT INTO items(id,name,tenant_id,is_container) VALUES (201,'bag',71,true),(202,'gem',71,false)"); + dsl.execute("INSERT INTO inventory(character_id,item_id,quantity) VALUES (101,202,6)"); + dsl.execute( + "INSERT INTO character_friend(character_id,friend_id,tenant_id) VALUES (101,102,71)"); + dsl.execute( + "INSERT INTO character_equipment(character_id,slot,item_id) VALUES (101,'hand',202)"); + dsl.execute( + "INSERT INTO actor_resource_states(tenant_id,character_id,stat_key,current_value,playable_state_key) VALUES (71,101,'health',31,'shared-live')"); + dsl.execute( + "INSERT INTO actor_active_conditions(tenant_id,character_id,condition_key,source_type,playable_state_key,effect_payload_json) VALUES (71,101,'stunned','retained','shared-live','{}')"); + dsl.execute( + "INSERT INTO container_instances(id,tenant_id,character_id,game_instance_id,item_id) VALUES (401,71,101,'44',201)"); + dsl.execute( + "INSERT INTO item_instances(id,tenant_id,character_id,game_instance_id,item_id,visible_ref_token,visible_ref_sequence,visible_ref) VALUES (501,71,101,'44',201,'retained',1,'retained-bag')"); + dsl.execute("UPDATE container_instances SET item_instance_id=501 WHERE id=401"); + dsl.execute( + "INSERT INTO item_instances(id,tenant_id,game_instance_id,container_instance_id,item_id,visible_ref_token,visible_ref_sequence,visible_ref) VALUES (502,71,'44',401,202,'retained',2,'retained-gem')"); + dsl.execute( + "INSERT INTO item_stacks(tenant_id,character_id,game_instance_id,item_id,compatibility_fingerprint,quantity) VALUES (71,101,'44',202,'retained',13)"); + dsl.execute( + "INSERT INTO item_visible_ref_counters(tenant_id,visible_ref_token,next_sequence) VALUES (71,'retained',3)"); + dsl.execute( + "INSERT INTO room_ground_inventory(tenant_id,game_instance_id,room_instance_id,item_id,quantity) VALUES (71,'44','room-9',202,15)"); + dsl.execute( + "INSERT INTO crafting_recipes(id,tenant_id,name,result_item_id,result_quantity) VALUES (601,71,'retained',202,1)"); + dsl.execute("INSERT INTO crafting_ingredients(recipe_id,item_id,quantity) VALUES (601,202,2)"); + dsl.execute( + "INSERT INTO equipment_slot_definitions(tenant_id,slot_key,display_name) VALUES (71,'hand','Hand')"); + dsl.execute( + "INSERT INTO body_layout_slot_definitions(tenant_id,body_layout_key,slot_key) VALUES (71,'DEFAULT','hand')"); + dsl.execute( + "INSERT INTO item_transfer_audits(tenant_id,item_id,quantity,verb,correlation_key,source_holder_kind,destination_holder_kind) VALUES (71,202,1,'DROP','retained','CHARACTER','ROOM')"); + dsl.execute( + "INSERT INTO entity_mutation_effects(tenant_id,effect_id,operation_name,response_payload,status) VALUES (71,'retained','DROP',decode('cafe','hex'),'APPLIED')"); + dsl.execute("INSERT INTO saga_instance(saga_name,state) VALUES ('retained','PENDING')"); + dsl.execute( + "INSERT INTO saga_step(instance_id,name,status) SELECT id,'retained','PENDING' FROM saga_instance WHERE saga_name='retained'"); + } + + private static void assertFamily( + EntityRuntimeFamilyCatalog catalog, + String name, + Role role, + StateClass state, + FreshDisposition disposition) { + assertThat(catalog.families()) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo(name); + assertThat(family.role()).isEqualTo(role); + assertThat(family.stateClass()).isEqualTo(state); + assertThat(family.freshDisposition()).isEqualTo(disposition); + }); + } + + private static Request request() { + return new Request(UUID.randomUUID(), "test"); + } + + private static FluentConfiguration migration( + DriverManagerDataSource source, String schema, String history, String target) { + var config = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .table(history) + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + "classpath:db/migration/saga") + .placeholders(Map.of("serviceSchema", schema)); + config + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + if (target != null) config.target(target); + return config; + } + + private static Fixture fixture(String target, String history) { + String schema = "entity_catalog_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + try { + migration(source, schema, history, target).load().migrate(); + return new Fixture(schema, source, dsl, new DataSourceTransactionManager(source)); + } catch (RuntimeException failed) { + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + throw failed; + } + } + + private record Fixture( + String schema, + DriverManagerDataSource source, + DSLContext dsl, + DataSourceTransactionManager manager) + implements AutoCloseable { + EntityRuntimeFamilyCatalogRepository owner() { + return new EntityRuntimeFamilyCatalogRepository(dsl, manager, schema, "test"); + } + + long count(String table) { + return dsl.fetchSingle("SELECT count(*) FROM " + table).get(0, Long.class); + } + + List rows(String table) { + return dsl.fetch( + "SELECT to_jsonb(t)::text||':'||xmin::text AS value FROM " + + table + + " t ORDER BY value") + .getValues(0, String.class); + } + + @Override + public void close() { + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + private static final class Collector + implements StreamObserver { + private ReadEntityRuntimeFamilyCatalogResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadEntityRuntimeFamilyCatalogResponse next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcServiceTest.java new file mode 100644 index 0000000000..51ff324e64 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcServiceTest.java @@ -0,0 +1,202 @@ +package unit.net.firedevops.firemud.entitymanagement.runtimecatalog; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.repository.EntityRuntimeFamilyCatalogRepository; +import net.firedevops.firemud.entitymanagement.runtimecatalog.EntityRuntimeFamilyCatalogReadGrpcService; +import net.firedevops.firemud.entitymanagement.v1.ReadEntityRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadEntityRuntimeFamilyCatalogResponse; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Controlled peer context, not certificate proof. Separate client fixture exercises physical mTLS. + */ +class EntityRuntimeFamilyCatalogReadGrpcServiceTest { + @Test + void workloadRefusalPrecedesMalformedDecodeAndSql() { + var repository = mock(EntityRuntimeFamilyCatalogRepository.class); + var service = new EntityRuntimeFamilyCatalogReadGrpcService(repository, "test"); + var malformed = + ReadEntityRuntimeFamilyCatalogRequest.newBuilder() + .addCanonicalRequestBytes(ByteString.copyFromUtf8("bad frame")) + .build(); + assertThat(call(service, malformed, null).error).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(call(service, malformed, peer("account-service", "test")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(call(service, malformed, peer("game-session-service", "other")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext(UUID.randomUUID().toString(), List.of(), Map.of()); + try { + assertThat(call(service, malformed, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-session-service", "controlled"); + try { + assertThat(call(service, malformed, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(repository); + } + + @Test + void ambientSqlAndSynchronizationRefuseBeforeDecode() { + var repository = mock(EntityRuntimeFamilyCatalogRepository.class); + var service = new EntityRuntimeFamilyCatalogReadGrpcService(repository, "test"); + var malformed = ReadEntityRuntimeFamilyCatalogRequest.getDefaultInstance(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThat(call(service, malformed, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThat(call(service, malformed, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(repository); + } + + @Test + void authenticatedMalformedOversizedAndWrongNamespaceRefuseBeforeSql() { + var repository = mock(EntityRuntimeFamilyCatalogRepository.class); + var service = new EntityRuntimeFamilyCatalogReadGrpcService(repository, "test"); + var peer = peer("game-session-service", "test"); + assertThat( + call(service, ReadEntityRuntimeFamilyCatalogRequest.getDefaultInstance(), peer).error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + call( + service, + ReadEntityRuntimeFamilyCatalogRequest.newBuilder() + .addCanonicalRequestBytes(ByteString.copyFrom(new byte[1025])) + .build(), + peer) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + call( + service, + EntityRuntimeFamilyCatalogCodec.toRequest( + new Request(UUID.randomUUID(), "other")), + peer) + .error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void completePositiveResponseAndDriftOutageRefusalsPreserveCorrelationWithoutPrivateDetails() { + var repository = mock(EntityRuntimeFamilyCatalogRepository.class); + var service = new EntityRuntimeFamilyCatalogReadGrpcService(repository, "test"); + var request = new Request(UUID.randomUUID(), "test"); + var wire = EntityRuntimeFamilyCatalogCodec.toRequest(request); + String json = + """ + {"schema":"entity-runtime-family-catalog/v1","owner":"entity-management-service","catalogEpoch":"1", + "families":[{"familyId":"characters","relation":"characters","component":"","role":"RUNTIME_PAYLOAD", + "stateClass":"S1","freshDisposition":"PROVISIONAL_NAMESPACE"}], + "schemaFacts":[{"kind":"TABLE","identity":"characters", + "definitionDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]} + """; + var evidence = + new Evidence( + request, + UUID.randomUUID(), + EntityRuntimeFamilyCatalog.fromStored(json.getBytes(StandardCharsets.UTF_8))); + when(repository.read(request)).thenReturn(evidence); + var success = call(service, wire, peer("game-session-service", "test")); + assertThat(success.error).isNull(); + assertThat(success.completed).isTrue(); + assertThat(EntityRuntimeFamilyCatalogCodec.fromResponse(request, success.value)) + .isEqualTo(evidence); + verify(repository).read(request); + doThrow(new EntityRuntimeFamilyCatalogRepository.CatalogConflictException("private details")) + .when(repository) + .read(request); + var drift = call(service, wire, peer("game-session-service", "test")); + assertThat(drift.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(drift.value).isNull(); + assertThat(drift.description).doesNotContain("private details"); + doThrow( + new org.jooq.exception.DataAccessException( + "private SQL", new SQLException("private SQL", "08006"))) + .when(repository) + .read(request); + var outage = call(service, wire, peer("game-session-service", "test")); + assertThat(outage.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(outage.value).isNull(); + assertThat(outage.description).doesNotContain("private SQL"); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static Collector call( + EntityRuntimeFamilyCatalogReadGrpcService service, + ReadEntityRuntimeFamilyCatalogRequest wire, + GrpcPeerIdentity peer) { + var result = new Collector(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run(() -> service.readEntityRuntimeFamilyCatalog(wire, result)); + return result; + } + + private static final class Collector + implements StreamObserver { + private Status.Code error; + private String description; + private ReadEntityRuntimeFamilyCatalogResponse value; + private boolean completed; + + @Override + public void onNext(ReadEntityRuntimeFamilyCatalogResponse next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + assertThat(value).isNull(); + error = Status.fromThrowable(failure).getCode(); + description = Status.fromThrowable(failure).getDescription(); + } + + @Override + public void onCompleted() { + assertThat(value).isNotNull(); + completed = true; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClient.java new file mode 100644 index 0000000000..7ee30c3a4f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClient.java @@ -0,0 +1,84 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.automationscripting.v1.AutomationRuntimeFamilyCatalogReadServiceGrpc; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** + * Manual concrete source consumer only; no owner-set enumeration, FRESH coordinator or + * registration. + */ +public final class AutomationRuntimeFamilyCatalogClient + extends AbstractReloadingBlockingGrpcClient< + AutomationRuntimeFamilyCatalogReadServiceGrpc + .AutomationRuntimeFamilyCatalogReadServiceBlockingStub> { + private final String namespace; + + public AutomationRuntimeFamilyCatalogClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tls, "Automation runtime catalog"), + channels, + AutomationRuntimeFamilyCatalogClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Fixed workload namespace required"); + this.namespace = namespace; + } + + public void init() throws IOException { + requireNoAmbientSql("Catalog client initialization requires no ambient SQL"); + initOnce("Automation catalog client closed", "Automation catalog client unavailable"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAutomationScriptingService(); + } + + @Override + protected String defaultTarget() { + return "automation-scripting-service:6565"; + } + + @Override + protected AutomationRuntimeFamilyCatalogReadServiceGrpc + .AutomationRuntimeFamilyCatalogReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/automation-scripting-service"; + return AutomationRuntimeFamilyCatalogReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)); + } + + /** Complete exact evidence or refusal; unavailable is not empty or initialized state. */ + public Evidence read(Request request) { + requireNoAmbientSql("Automation catalog RPC requires no ambient SQL"); + Objects.requireNonNull(request, "request"); + if (!namespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Wrong workload namespace"); + var response = + requireInitializedStub("Automation catalog client unavailable") + .withDeadlineAfter(5, TimeUnit.SECONDS) + .withMaxInboundMessageSize(AutomationRuntimeFamilyCatalogCodec.MAX_RESPONSE_BYTES) + .withMaxOutboundMessageSize(AutomationRuntimeFamilyCatalogCodec.MAX_REQUEST_BYTES) + .readAutomationRuntimeFamilyCatalog( + AutomationRuntimeFamilyCatalogCodec.toRequest(request)); + return AutomationRuntimeFamilyCatalogCodec.fromResponse(request, response); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClient.java new file mode 100644 index 0000000000..bda73d9fad --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClient.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.entitymanagement.v1.EntityRuntimeFamilyCatalogReadServiceGrpc; + +/** Manual exact Entity source consumer. No FRESH coordinator, registration or allocation wiring. */ +public final class EntityRuntimeFamilyCatalogClient + extends AbstractReloadingBlockingGrpcClient< + EntityRuntimeFamilyCatalogReadServiceGrpc + .EntityRuntimeFamilyCatalogReadServiceBlockingStub> { + private final String namespace; + + public EntityRuntimeFamilyCatalogClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tls, "Entity runtime catalog"), + channels, + EntityRuntimeFamilyCatalogClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Fixed workload namespace required"); + this.namespace = namespace; + } + + public void init() throws IOException { + requireNoAmbientSql("Catalog client initialization requires no ambient SQL"); + initOnce("Entity catalog client closed", "Entity catalog client unavailable"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getEntityManagementService(); + } + + @Override + protected String defaultTarget() { + return "entity-management-service:6565"; + } + + @Override + protected EntityRuntimeFamilyCatalogReadServiceGrpc + .EntityRuntimeFamilyCatalogReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service"; + return EntityRuntimeFamilyCatalogReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)); + } + + public Evidence read(Request request) { + requireNoAmbientSql("Entity catalog RPC requires no ambient SQL"); + Objects.requireNonNull(request, "request"); + if (!namespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Wrong workload namespace"); + var response = + requireInitializedStub("Entity catalog client unavailable") + .withDeadlineAfter(5, TimeUnit.SECONDS) + .withMaxInboundMessageSize(EntityRuntimeFamilyCatalogCodec.MAX_RESPONSE_BYTES) + .withMaxOutboundMessageSize(EntityRuntimeFamilyCatalogCodec.MAX_REQUEST_BYTES) + .readEntityRuntimeFamilyCatalog(EntityRuntimeFamilyCatalogCodec.toRequest(request)); + return EntityRuntimeFamilyCatalogCodec.fromResponse(request, response); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialRuntimeFamilyCatalogClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialRuntimeFamilyCatalogClient.java new file mode 100644 index 0000000000..6c75945a89 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialRuntimeFamilyCatalogClient.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.socialgroups.v1.SocialRuntimeFamilyCatalogReadServiceGrpc; + +/** + * Manual concrete Social source consumer; no owner aggregation, manifest, FRESH or admission + * wiring. + */ +public final class SocialRuntimeFamilyCatalogClient + extends AbstractReloadingBlockingGrpcClient< + SocialRuntimeFamilyCatalogReadServiceGrpc + .SocialRuntimeFamilyCatalogReadServiceBlockingStub> { + private final String namespace; + + public SocialRuntimeFamilyCatalogClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tls, "Social runtime catalog"), + channels, + SocialRuntimeFamilyCatalogClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixed workload namespace required"); + } + this.namespace = namespace; + } + + public void init() throws IOException { + requireNoAmbientSql("Social catalog client initialization requires no ambient SQL"); + initOnce("Social catalog client closed", "Social catalog client unavailable"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getSocialGroupsService(); + } + + @Override + protected String defaultTarget() { + return "social-groups-service:6565"; + } + + @Override + protected SocialRuntimeFamilyCatalogReadServiceGrpc + .SocialRuntimeFamilyCatalogReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/social-groups-service"; + return SocialRuntimeFamilyCatalogReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)); + } + + /** Preserves exact complete typed source evidence; outages never become empty success. */ + public Evidence read(Request request) { + requireNoAmbientSql("Social catalog RPC requires no ambient SQL"); + Objects.requireNonNull(request, "request"); + if (!namespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException("Wrong Social workload namespace"); + } + var response = + requireInitializedStub("Social catalog client unavailable") + .withDeadlineAfter(5, TimeUnit.SECONDS) + .withMaxInboundMessageSize(SocialRuntimeFamilyCatalogCodec.MAX_RESPONSE_BYTES) + .withMaxOutboundMessageSize(SocialRuntimeFamilyCatalogCodec.MAX_REQUEST_BYTES) + .readSocialRuntimeFamilyCatalog(SocialRuntimeFamilyCatalogCodec.toRequest(request)); + return SocialRuntimeFamilyCatalogCodec.fromResponse(request, response); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClient.java new file mode 100644 index 0000000000..e5dc4b65e1 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClient.java @@ -0,0 +1,81 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.worldmanagement.v1.WorldRuntimeFamilyCatalogReadServiceGrpc; + +/** + * Manual concrete source consumer. It neither enumerates other owners nor prepares/adopts FRESH. + */ +public final class WorldRuntimeFamilyCatalogClient + extends AbstractReloadingBlockingGrpcClient< + WorldRuntimeFamilyCatalogReadServiceGrpc.WorldRuntimeFamilyCatalogReadServiceBlockingStub> { + private final String namespace; + + public WorldRuntimeFamilyCatalogClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tls, "World runtime catalog"), + channels, + WorldRuntimeFamilyCatalogClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Fixed workload namespace required"); + this.namespace = namespace; + } + + public void init() throws IOException { + requireNoAmbientSql("Catalog client initialization requires no ambient SQL"); + initOnce("World catalog client closed", "World catalog client unavailable"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldRuntimeFamilyCatalogReadServiceGrpc + .WorldRuntimeFamilyCatalogReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + return WorldRuntimeFamilyCatalogReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)); + } + + /** Preserves the complete exact typed source or refuses; outage never becomes empty evidence. */ + public Evidence read(Request request) { + requireNoAmbientSql("World catalog RPC requires no ambient SQL"); + Objects.requireNonNull(request, "request"); + if (!namespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Wrong workload namespace"); + var response = + requireInitializedStub("World catalog client unavailable") + .withDeadlineAfter(5, TimeUnit.SECONDS) + .withMaxInboundMessageSize(WorldRuntimeFamilyCatalogCodec.MAX_RESPONSE_BYTES) + .withMaxOutboundMessageSize(WorldRuntimeFamilyCatalogCodec.MAX_REQUEST_BYTES) + .readWorldRuntimeFamilyCatalog(WorldRuntimeFamilyCatalogCodec.toRequest(request)); + return WorldRuntimeFamilyCatalogCodec.fromResponse(request, response); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClientMtlsTest.java new file mode 100644 index 0000000000..eea605570d --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClientMtlsTest.java @@ -0,0 +1,329 @@ +package unit.net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.TlsServerCredentials; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.automationscripting.v1.AutomationRuntimeFamilyCatalogReadServiceGrpc; +import net.firedevops.firemud.automationscripting.v1.ReadAutomationRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.automationscripting.v1.ReadAutomationRuntimeFamilyCatalogResponse; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.gamesession.client.AutomationRuntimeFamilyCatalogClient; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Actual loopback mTLS client with controlled source bytes/upstream and local test trust. Separate + * PostgreSQL/producer-context fixtures do not establish a deployed combined owner/PKI boundary, + * live private authority, enrollment, absence, initialized state or FRESH readiness. + */ +@Timeout(60) +class AutomationRuntimeFamilyCatalogClientMtlsTest { + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + private static final String NAMESPACE = "catalog-test"; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Automation runtime catalog test CA", + new LoopbackMtlsTestPki.IdentitySpec( + "client", uri("game-session-service", NAMESPACE), false), + new LoopbackMtlsTestPki.IdentitySpec( + "automation", uri("automation-scripting-service", NAMESPACE), true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-role", uri("entity-management-service", NAMESPACE), true), + new LoopbackMtlsTestPki.IdentitySpec( + "foreign-namespace", uri("automation-scripting-service", "other"), true)); + } + + @Test + void exactPeerClientRetainsCorrelationSnapshotBytesDigestsAndFiniteDeadline() throws Exception { + Request request = new Request(UUID.randomUUID(), NAMESPACE); + Evidence expected = evidence(request); + var observed = new AtomicReference(); + var peer = new AtomicReference(); + var remaining = new AtomicLong(); + Server server = + server( + "automation", + new AutomationRuntimeFamilyCatalogReadServiceGrpc + .AutomationRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readAutomationRuntimeFamilyCatalog( + ReadAutomationRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + peer.set(GrpcPeerIdentity.current().uri()); + remaining.set(Context.current().getDeadline().timeRemaining(TimeUnit.MILLISECONDS)); + observed.set(AutomationRuntimeFamilyCatalogCodec.fromRequest(wire)); + observer.onNext(AutomationRuntimeFamilyCatalogCodec.toResponse(request, expected)); + observer.onCompleted(); + } + }); + try (var client = client(server)) { + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + client.init(); + Evidence actual = client.read(request); + assertThat(actual).isEqualTo(expected); + assertThat(actual.catalog().exactBytes()).isEqualTo(expected.catalog().exactBytes()); + assertThat(actual.catalog().digest()).isEqualTo(expected.catalog().digest()); + assertThat(actual.digest()).isEqualTo(expected.digest()); + assertThat(observed.get()).isEqualTo(request); + assertThat(peer.get()).isEqualTo(uri("game-session-service", NAMESPACE)); + assertThat(remaining.get()).isBetween(1L, 5000L); + } finally { + stop(server); + } + } + + @Test + void sameCaWrongServiceAndForeignNamespaceRefuseBeforeUpstreamHandler() throws Exception { + for (String identity : List.of("wrong-role", "foreign-namespace")) { + var calls = new AtomicInteger(); + Server server = + server( + identity, + new AutomationRuntimeFamilyCatalogReadServiceGrpc + .AutomationRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readAutomationRuntimeFamilyCatalog( + ReadAutomationRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onError(Status.INTERNAL.asRuntimeException()); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> + assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(0); + } finally { + stop(server); + } + } + } + + @Test + void changedCorrelationNamespaceIncompleteDuplicateCorruptAndOversizedResponsesRefuse() + throws Exception { + Request request = new Request(UUID.randomUUID(), NAMESPACE); + Request changed = new Request(UUID.randomUUID(), NAMESPACE); + Request foreign = new Request(request.readRequestId(), "other"); + var valid = AutomationRuntimeFamilyCatalogCodec.toResponse(request, evidence(request)); + byte[] corrupt = valid.getCanonicalResponseBytes(0).toByteArray(); + corrupt[corrupt.length - 1] ^= 1; + for (var response : + List.of( + AutomationRuntimeFamilyCatalogCodec.toResponse(changed, evidence(changed)), + AutomationRuntimeFamilyCatalogCodec.toResponse(foreign, evidence(foreign)), + ReadAutomationRuntimeFamilyCatalogResponse.getDefaultInstance(), + valid.toBuilder().addCanonicalResponseBytes(valid.getCanonicalResponseBytes(0)).build(), + valid.toBuilder().setCanonicalResponseBytes(0, ByteString.copyFrom(corrupt)).build(), + valid.toBuilder() + .setCanonicalResponseBytes( + 0, + ByteString.copyFrom( + new byte[AutomationRuntimeFamilyCatalogCodec.MAX_RESPONSE_BYTES + 1])) + .build())) { + Server server = server("automation", returning(response)); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOfAny(IllegalArgumentException.class, StatusRuntimeException.class); + } finally { + stop(server); + } + } + } + + @Test + void wrongLocalNamespaceAndAmbientSqlNeverCallOwnerAndStorageFailureIsNotEmptySource() + throws Exception { + var calls = new AtomicInteger(); + Server server = + server( + "automation", + new AutomationRuntimeFamilyCatalogReadServiceGrpc + .AutomationRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readAutomationRuntimeFamilyCatalog( + ReadAutomationRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), "other"))) + .isInstanceOf(IllegalArgumentException.class); + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + assertThat(calls).hasValue(0); + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new AutomationRuntimeFamilyCatalogClient( + new ServiceEndpointsProperties(), + plaintext, + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void stalledOwnerReachesTheRealFiniteDeadlineRatherThanReturningEmptyEvidence() throws Exception { + var calls = new AtomicInteger(); + Server server = + server( + "automation", + new AutomationRuntimeFamilyCatalogReadServiceGrpc + .AutomationRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readAutomationRuntimeFamilyCatalog( + ReadAutomationRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + // Intentionally no terminal signal: the real client deadline must end the call. + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> + assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + } + + private static AutomationRuntimeFamilyCatalogClient client(Server server) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAutomationScriptingService("localhost:" + server.getPort()); + return new AutomationRuntimeFamilyCatalogClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static Server server( + String identity, + AutomationRuntimeFamilyCatalogReadServiceGrpc + .AutomationRuntimeFamilyCatalogReadServiceImplBase + service) + throws Exception { + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + pki.keyManagerFactory(pki.identity(identity)), + pki.trustManagerFactory(), + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + factory.addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())); + return factory.createServer().start(); + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private static AutomationRuntimeFamilyCatalogReadServiceGrpc + .AutomationRuntimeFamilyCatalogReadServiceImplBase + returning(ReadAutomationRuntimeFamilyCatalogResponse response) { + return new AutomationRuntimeFamilyCatalogReadServiceGrpc + .AutomationRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readAutomationRuntimeFamilyCatalog( + ReadAutomationRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + observer.onNext(response); + observer.onCompleted(); + } + }; + } + + private static Evidence evidence(Request request) { + String json = + """ + {"schema":"automation-runtime-family-catalog/v1","owner":"automation-scripting-service","catalogEpoch":"1", + "families":[{"familyId":"npc_memory","relation":"npc_memory","component":"", + "role":"RUNTIME_PAYLOAD","stateClass":"UNKNOWN","freshDisposition":"STATE_CLASS_UNKNOWN_BLOCKING", + "retentionDisposition":"UNRESOLVED_RETAINED","ownerConsequence":"Controlled fixture remains blocking."}], + "schemaFacts":[{"kind":"TABLE","identity":"npc_memory", + "definitionDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}], + "nonSqlGaps":[{"id":"DURABLE_CHARGE_MARKERS","disposition":"UNSUPPORTED_BLOCKING", + "ownerConsequence":"Controlled limitation; no SQL charge rows or Redis census."}]} + """; + return new Evidence( + request, + UUID.randomUUID(), + AutomationRuntimeFamilyCatalog.fromStored(json.getBytes(StandardCharsets.UTF_8))); + } + + private static String uri(String service, String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + service; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClientMtlsTest.java new file mode 100644 index 0000000000..21143a911a --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClientMtlsTest.java @@ -0,0 +1,296 @@ +package unit.net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.TlsServerCredentials; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.entitymanagement.v1.EntityRuntimeFamilyCatalogReadServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ReadEntityRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadEntityRuntimeFamilyCatalogResponse; +import net.firedevops.firemud.gamesession.client.EntityRuntimeFamilyCatalogClient; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Physical transport with controlled local PKI/owner bytes, not a live SQL-to-mTLS composition. */ +@Timeout(60) +class EntityRuntimeFamilyCatalogClientMtlsTest { + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + private static final String NAMESPACE = "entity-catalog-test"; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Entity catalog test CA", + new LoopbackMtlsTestPki.IdentitySpec( + "client", uri("game-session-service", NAMESPACE), false), + new LoopbackMtlsTestPki.IdentitySpec( + "entity", uri("entity-management-service", NAMESPACE), true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-role", uri("world-management-service", NAMESPACE), true), + new LoopbackMtlsTestPki.IdentitySpec( + "foreign", uri("entity-management-service", "other"), true)); + } + + @Test + void actualClientPreservesTypedBytesCorrelationIdentityAndDeadline() throws Exception { + var request = new Request(UUID.randomUUID(), NAMESPACE); + var expected = evidence(request); + var observed = new AtomicReference(); + var peer = new AtomicReference(); + var remaining = new AtomicLong(); + Server server = + server( + "entity", + new EntityRuntimeFamilyCatalogReadServiceGrpc + .EntityRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readEntityRuntimeFamilyCatalog( + ReadEntityRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + peer.set(GrpcPeerIdentity.current().uri()); + remaining.set(Context.current().getDeadline().timeRemaining(TimeUnit.MILLISECONDS)); + observed.set(EntityRuntimeFamilyCatalogCodec.fromRequest(wire)); + observer.onNext(EntityRuntimeFamilyCatalogCodec.toResponse(request, expected)); + observer.onCompleted(); + } + }); + try (var client = client(server)) { + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + client.init(); + var actual = client.read(request); + assertThat(actual).isEqualTo(expected); + assertThat(actual.digest()).isEqualTo(expected.digest()); + assertThat(actual.catalog().exactBytes()).isEqualTo(expected.catalog().exactBytes()); + assertThat(observed.get()).isEqualTo(request); + assertThat(peer.get()).isEqualTo(uri("game-session-service", NAMESPACE)); + assertThat(remaining.get()).isBetween(1L, 5000L); + } finally { + stop(server); + } + } + + @Test + void sameCaWrongEntityRoleOrNamespaceRefusesBeforeHandler() throws Exception { + for (String identity : List.of("wrong-role", "foreign")) { + var calls = new AtomicInteger(); + Server server = + server( + identity, + new EntityRuntimeFamilyCatalogReadServiceGrpc + .EntityRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readEntityRuntimeFamilyCatalog( + ReadEntityRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onError(Status.INTERNAL.asRuntimeException()); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> + assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(0); + } finally { + stop(server); + } + } + } + + @Test + void wrongCorrelationEmptyDuplicateAndOversizedResponsesNeverBecomeEvidence() throws Exception { + var request = new Request(UUID.randomUUID(), NAMESPACE); + var other = new Request(UUID.randomUUID(), NAMESPACE); + var valid = EntityRuntimeFamilyCatalogCodec.toResponse(request, evidence(request)); + for (var response : + List.of( + EntityRuntimeFamilyCatalogCodec.toResponse(other, evidence(other)), + ReadEntityRuntimeFamilyCatalogResponse.getDefaultInstance(), + valid.toBuilder().addCanonicalResponseBytes(valid.getCanonicalResponseBytes(0)).build(), + valid.toBuilder() + .setCanonicalResponseBytes( + 0, + com.google.protobuf.ByteString.copyFrom( + new byte[EntityRuntimeFamilyCatalogCodec.MAX_RESPONSE_BYTES + 1])) + .build())) { + Server server = + server( + "entity", + new EntityRuntimeFamilyCatalogReadServiceGrpc + .EntityRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readEntityRuntimeFamilyCatalog( + ReadEntityRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + observer.onNext(response); + observer.onCompleted(); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOfAny(IllegalArgumentException.class, StatusRuntimeException.class); + } finally { + stop(server); + } + } + } + + @Test + void refusalWrongLocalNamespaceAmbientSqlAndPlaintextAreNotEmptySuccess() throws Exception { + var calls = new AtomicInteger(); + Server server = + server( + "entity", + new EntityRuntimeFamilyCatalogReadServiceGrpc + .EntityRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readEntityRuntimeFamilyCatalog( + ReadEntityRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), "other"))) + .isInstanceOf(IllegalArgumentException.class); + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(calls).hasValue(0); + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new EntityRuntimeFamilyCatalogClient( + new ServiceEndpointsProperties(), tls, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void nonrespondingOwnerIsBoundedByActualFiveSecondRpcDeadline() throws Exception { + Server server = + server( + "entity", + new EntityRuntimeFamilyCatalogReadServiceGrpc + .EntityRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readEntityRuntimeFamilyCatalog( + ReadEntityRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + /* deliberately no response */ + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> + assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + } finally { + stop(server); + } + } + + private static EntityRuntimeFamilyCatalogClient client(Server server) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setEntityManagementService("localhost:" + server.getPort()); + return new EntityRuntimeFamilyCatalogClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static Server server( + String identity, + EntityRuntimeFamilyCatalogReadServiceGrpc.EntityRuntimeFamilyCatalogReadServiceImplBase + service) + throws Exception { + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + pki.keyManagerFactory(pki.identity(identity)), + pki.trustManagerFactory(), + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + factory.addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())); + return factory.createServer().start(); + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private static Evidence evidence(Request request) { + String json = + """ + {"schema":"entity-runtime-family-catalog/v1","owner":"entity-management-service","catalogEpoch":"1", + "families":[{"familyId":"actor_resource_states","relation":"actor_resource_states","component":"", + "role":"RUNTIME_PAYLOAD","stateClass":"CONDITIONAL_S1_S2","freshDisposition":"BLOCKING_NAMESPACE_REMAP"}], + "schemaFacts":[{"kind":"TABLE","identity":"actor_resource_states", + "definitionDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]} + """; + return new Evidence( + request, + UUID.randomUUID(), + EntityRuntimeFamilyCatalog.fromStored(json.getBytes(StandardCharsets.UTF_8))); + } + + private static String uri(String service, String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + service; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/SocialRuntimeFamilyCatalogClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/SocialRuntimeFamilyCatalogClientMtlsTest.java new file mode 100644 index 0000000000..0c3b6dd1f0 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/SocialRuntimeFamilyCatalogClientMtlsTest.java @@ -0,0 +1,289 @@ +package unit.net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.TlsServerCredentials; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.gamesession.client.SocialRuntimeFamilyCatalogClient; +import net.firedevops.firemud.socialgroups.v1.ReadSocialRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.socialgroups.v1.ReadSocialRuntimeFamilyCatalogResponse; +import net.firedevops.firemud.socialgroups.v1.SocialRuntimeFamilyCatalogReadServiceGrpc; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Physical mTLS client/codec proof; controlled bytes are not installed-schema or FRESH proof. */ +@Timeout(60) +class SocialRuntimeFamilyCatalogClientMtlsTest { + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + private static final String NAMESPACE = "catalog-test"; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Social runtime catalog test CA", + new LoopbackMtlsTestPki.IdentitySpec( + "client", uri("game-session-service", NAMESPACE), false), + new LoopbackMtlsTestPki.IdentitySpec( + "social", uri("social-groups-service", NAMESPACE), true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-role", uri("entity-management-service", NAMESPACE), true), + new LoopbackMtlsTestPki.IdentitySpec( + "foreign-namespace", uri("social-groups-service", "other"), true)); + } + + @Test + void actualPeerQualifiedClientPreservesExactEvidenceCorrelationAndFiniteDeadline() + throws Exception { + Request request = new Request(UUID.randomUUID(), NAMESPACE); + Evidence expected = evidence(request); + var observed = new AtomicReference(); + var peer = new AtomicReference(); + var remaining = new AtomicLong(); + var service = + new SocialRuntimeFamilyCatalogReadServiceGrpc + .SocialRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readSocialRuntimeFamilyCatalog( + ReadSocialRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + peer.set(GrpcPeerIdentity.current().uri()); + remaining.set(Context.current().getDeadline().timeRemaining(TimeUnit.MILLISECONDS)); + observed.set(SocialRuntimeFamilyCatalogCodec.fromRequest(wire)); + observer.onNext(SocialRuntimeFamilyCatalogCodec.toResponse(request, expected)); + observer.onCompleted(); + } + }; + Server server = server("social", service); + try (var client = client(server)) { + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + client.init(); + Evidence result = client.read(request); + assertThat(result).isEqualTo(expected); + assertThat(result.catalog().exactBytes()).isEqualTo(expected.catalog().exactBytes()); + assertThat(result.digest()).isEqualTo(expected.digest()); + assertThat(observed.get()).isEqualTo(request); + assertThat(peer.get()).isEqualTo(uri("game-session-service", NAMESPACE)); + assertThat(remaining.get()).isBetween(1L, 5000L); + } finally { + stop(server); + } + } + + @Test + void sameCaWrongSocialRoleAndForeignNamespaceRefuseBeforeHandler() throws Exception { + for (String identity : List.of("wrong-role", "foreign-namespace")) { + var calls = new AtomicInteger(); + Server server = + server( + identity, + new SocialRuntimeFamilyCatalogReadServiceGrpc + .SocialRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readSocialRuntimeFamilyCatalog( + ReadSocialRuntimeFamilyCatalogRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onError(Status.INTERNAL.asRuntimeException()); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> + assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(0); + } finally { + stop(server); + } + } + } + + @Test + void changedCorrelationDuplicateIncompleteAndOversizedEvidenceNeverBecomeSourceInput() + throws Exception { + Request request = new Request(UUID.randomUUID(), NAMESPACE); + Request other = new Request(UUID.randomUUID(), NAMESPACE); + var wrong = SocialRuntimeFamilyCatalogCodec.toResponse(other, evidence(other)); + var valid = SocialRuntimeFamilyCatalogCodec.toResponse(request, evidence(request)); + var duplicate = + valid.toBuilder().addCanonicalResponseBytes(valid.getCanonicalResponseBytes(0)).build(); + var oversized = + valid.toBuilder() + .setCanonicalResponseBytes( + 0, + com.google.protobuf.ByteString.copyFrom( + new byte[SocialRuntimeFamilyCatalogCodec.MAX_RESPONSE_BYTES + 1])) + .build(); + for (ReadSocialRuntimeFamilyCatalogResponse response : + List.of( + wrong, + ReadSocialRuntimeFamilyCatalogResponse.getDefaultInstance(), + duplicate, + oversized)) { + Server server = server("social", returning(response)); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOfAny(IllegalArgumentException.class, StatusRuntimeException.class); + } finally { + stop(server); + } + } + } + + @Test + void unavailableAndWrongLocalNamespaceAreRefusalNotEmptyCatalog() throws Exception { + var calls = new AtomicInteger(); + Server server = + server( + "social", + new SocialRuntimeFamilyCatalogReadServiceGrpc + .SocialRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readSocialRuntimeFamilyCatalog( + ReadSocialRuntimeFamilyCatalogRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), "other"))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(calls).hasValue(0); + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(calls).hasValue(0); + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new SocialRuntimeFamilyCatalogClient( + new ServiceEndpointsProperties(), tls, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static SocialRuntimeFamilyCatalogClient client(Server server) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setSocialGroupsService("localhost:" + server.getPort()); + return new SocialRuntimeFamilyCatalogClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static Server server( + String identity, + SocialRuntimeFamilyCatalogReadServiceGrpc.SocialRuntimeFamilyCatalogReadServiceImplBase + service) + throws Exception { + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + pki.keyManagerFactory(pki.identity(identity)), + pki.trustManagerFactory(), + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + factory.addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())); + return factory.createServer().start(); + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private static SocialRuntimeFamilyCatalogReadServiceGrpc + .SocialRuntimeFamilyCatalogReadServiceImplBase + returning(ReadSocialRuntimeFamilyCatalogResponse response) { + return new SocialRuntimeFamilyCatalogReadServiceGrpc + .SocialRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readSocialRuntimeFamilyCatalog( + ReadSocialRuntimeFamilyCatalogRequest request, + StreamObserver observer) { + observer.onNext(response); + observer.onCompleted(); + } + }; + } + + private static Evidence evidence(Request request) { + String json = + """ + {"schema":"social-runtime-family-catalog/v1","owner":"social-groups-service","catalogEpoch":"1", + "families":[{"familyId":"account_friend_links","relation":"account_friend_links","component":"", + "role":"SOCIAL_RELATIONSHIP","freshDisposition":"ACCOUNT_PAIR_SCOPE_DRIFT","targetOwner":"NONE"}, + {"familyId":"account_friend_links.account_id","relation":"account_friend_links","component":"account_id", + "role":"ACCOUNT_IDENTITY_CARRIER","freshDisposition":"ACCOUNT_IDENTITY_CARRIER_ONLY","targetOwner":"ACCOUNT_SERVICE"}, + {"familyId":"account_friend_links.friend_account_id","relation":"account_friend_links","component":"friend_account_id", + "role":"ACCOUNT_IDENTITY_CARRIER","freshDisposition":"ACCOUNT_IDENTITY_CARRIER_ONLY","targetOwner":"ACCOUNT_SERVICE"}], + "schemaFacts":[{"kind":"COLUMN","identity":"account_friend_links.account_id","definitionDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, + {"kind":"COLUMN","identity":"account_friend_links.friend_account_id","definitionDigest":"sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}, + {"kind":"TABLE","identity":"account_friend_links","definitionDigest":"sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"}], + "unimplementedContracts":["CHAT_RESTRICTION_AND_REVISION","DIRECTIONAL_BLOCK_LIFECYCLE", + "ENTITY_ESCROW_REFERENCE_FAMILIES","GAMEPLAY_WHISPER_NAMESPACE_SCOPE", + "SAFETY_EVIDENCE_AND_CONTENT_FREE_RECEIPTS","SOCIAL_PLAYER_STANDING_OWNER", + "SOCIAL_SAGA_ADOPTER_CLASSIFICATION"]} + """; + return new Evidence( + request, + UUID.randomUUID(), + SocialRuntimeFamilyCatalog.fromStored(json.getBytes(StandardCharsets.UTF_8))); + } + + private static String uri(String service, String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + service; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClientMtlsTest.java new file mode 100644 index 0000000000..4d2c368620 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClientMtlsTest.java @@ -0,0 +1,283 @@ +package unit.net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.TlsServerCredentials; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.gamesession.client.WorldRuntimeFamilyCatalogClient; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldRuntimeFamilyCatalogResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldRuntimeFamilyCatalogReadServiceGrpc; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Physical mTLS client/codec proof with controlled source bytes and local test trust. The handler + * does not establish an installed owner catalog, production PKI, global enrollment or FRESH state. + */ +@Timeout(60) +class WorldRuntimeFamilyCatalogClientMtlsTest { + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + private static final String NAMESPACE = "catalog-test"; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Runtime catalog test CA", + new LoopbackMtlsTestPki.IdentitySpec( + "client", uri("game-session-service", NAMESPACE), false), + new LoopbackMtlsTestPki.IdentitySpec( + "world", uri("world-management-service", NAMESPACE), true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-role", uri("entity-management-service", NAMESPACE), true), + new LoopbackMtlsTestPki.IdentitySpec( + "foreign-namespace", uri("world-management-service", "other"), true)); + } + + @Test + void actualPeerQualifiedClientPreservesExactEvidenceCorrelationAndFiniteDeadline() + throws Exception { + Request request = new Request(UUID.randomUUID(), NAMESPACE); + Evidence expected = evidence(request); + var observed = new AtomicReference(); + var peer = new AtomicReference(); + var remaining = new AtomicLong(); + var service = + new WorldRuntimeFamilyCatalogReadServiceGrpc + .WorldRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readWorldRuntimeFamilyCatalog( + ReadWorldRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + peer.set(GrpcPeerIdentity.current().uri()); + remaining.set(Context.current().getDeadline().timeRemaining(TimeUnit.MILLISECONDS)); + observed.set(WorldRuntimeFamilyCatalogCodec.fromRequest(wire)); + observer.onNext(WorldRuntimeFamilyCatalogCodec.toResponse(request, expected)); + observer.onCompleted(); + } + }; + Server server = server("world", service); + try (var client = client(server)) { + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + client.init(); + Evidence result = client.read(request); + assertThat(result).isEqualTo(expected); + assertThat(result.catalog().exactBytes()).isEqualTo(expected.catalog().exactBytes()); + assertThat(result.digest()).isEqualTo(expected.digest()); + assertThat(observed.get()).isEqualTo(request); + assertThat(peer.get()).isEqualTo(uri("game-session-service", NAMESPACE)); + assertThat(remaining.get()).isBetween(1L, 5000L); + } finally { + stop(server); + } + } + + @Test + void sameCaWrongWorldRoleAndForeignNamespaceRefuseBeforeHandler() throws Exception { + for (String identity : List.of("wrong-role", "foreign-namespace")) { + var calls = new AtomicInteger(); + Server server = + server( + identity, + new WorldRuntimeFamilyCatalogReadServiceGrpc + .WorldRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readWorldRuntimeFamilyCatalog( + ReadWorldRuntimeFamilyCatalogRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onError(Status.INTERNAL.asRuntimeException()); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> + assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(0); + } finally { + stop(server); + } + } + } + + @Test + void changedCorrelationDuplicateIncompleteAndOversizedEvidenceNeverBecomeSourceInput() + throws Exception { + Request request = new Request(UUID.randomUUID(), NAMESPACE); + // Build a response with one internally consistent, but different, request. + Request other = new Request(UUID.randomUUID(), NAMESPACE); + var wrong = WorldRuntimeFamilyCatalogCodec.toResponse(other, evidence(other)); + var valid = WorldRuntimeFamilyCatalogCodec.toResponse(request, evidence(request)); + var duplicate = + valid.toBuilder().addCanonicalResponseBytes(valid.getCanonicalResponseBytes(0)).build(); + var oversized = + valid.toBuilder() + .setCanonicalResponseBytes( + 0, + com.google.protobuf.ByteString.copyFrom( + new byte[WorldRuntimeFamilyCatalogCodec.MAX_RESPONSE_BYTES + 1])) + .build(); + for (ReadWorldRuntimeFamilyCatalogResponse response : + List.of( + wrong, + ReadWorldRuntimeFamilyCatalogResponse.getDefaultInstance(), + duplicate, + oversized)) { + Server server = server("world", returning(response)); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOfAny(IllegalArgumentException.class, StatusRuntimeException.class); + } finally { + stop(server); + } + } + } + + @Test + void unavailableAndWrongLocalNamespaceAreRefusalNotEmptyCatalog() throws Exception { + var calls = new AtomicInteger(); + Server server = + server( + "world", + new WorldRuntimeFamilyCatalogReadServiceGrpc + .WorldRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readWorldRuntimeFamilyCatalog( + ReadWorldRuntimeFamilyCatalogRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), "other"))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(calls).hasValue(0); + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(calls).hasValue(0); + assertThatThrownBy(() -> client.read(new Request(UUID.randomUUID(), NAMESPACE))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldRuntimeFamilyCatalogClient( + new ServiceEndpointsProperties(), tls, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static WorldRuntimeFamilyCatalogClient client(Server server) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + server.getPort()); + return new WorldRuntimeFamilyCatalogClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static Server server( + String identity, + WorldRuntimeFamilyCatalogReadServiceGrpc.WorldRuntimeFamilyCatalogReadServiceImplBase service) + throws Exception { + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + pki.keyManagerFactory(pki.identity(identity)), + pki.trustManagerFactory(), + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + factory.addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())); + return factory.createServer().start(); + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private static WorldRuntimeFamilyCatalogReadServiceGrpc + .WorldRuntimeFamilyCatalogReadServiceImplBase + returning(ReadWorldRuntimeFamilyCatalogResponse response) { + return new WorldRuntimeFamilyCatalogReadServiceGrpc + .WorldRuntimeFamilyCatalogReadServiceImplBase() { + @Override + public void readWorldRuntimeFamilyCatalog( + ReadWorldRuntimeFamilyCatalogRequest request, + StreamObserver observer) { + observer.onNext(response); + observer.onCompleted(); + } + }; + } + + private static Evidence evidence(Request request) { + String json = + """ + {"schema":"world-runtime-family-catalog/v1","owner":"world-management-service","catalogEpoch":"1", + "families":[{"familyId":"world_instance","relation":"world_instance","component":"", + "role":"LIFECYCLE","stateClass":"S3","freshDisposition":"REQUIRED_LIFECYCLE"}], + "schemaFacts":[{"kind":"TABLE","identity":"world_instance", + "definitionDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]} + """; + return new Evidence( + request, + UUID.randomUUID(), + WorldRuntimeFamilyCatalog.fromStored(json.getBytes(StandardCharsets.UTF_8))); + } + + private static String uri(String service, String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + service; + } +} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcService.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcService.java new file mode 100644 index 0000000000..6fb72ac5bd --- /dev/null +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcService.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.socialgroups.runtimecatalog; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.socialgroups.v1.ReadSocialRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.socialgroups.v1.ReadSocialRuntimeFamilyCatalogResponse; +import net.firedevops.firemud.socialgroups.v1.SocialRuntimeFamilyCatalogReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Manual, unregistered, exact Game Session workload read. Authentication precedes decode and SQL. + */ +public final class SocialRuntimeFamilyCatalogReadGrpcService + extends SocialRuntimeFamilyCatalogReadServiceGrpc + .SocialRuntimeFamilyCatalogReadServiceImplBase { + private final SocialRuntimeFamilyCatalogRepository repository; + private final String namespace; + + public SocialRuntimeFamilyCatalogReadGrpcService( + SocialRuntimeFamilyCatalogRepository repository, String namespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixed Social workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void readSocialRuntimeFamilyCatalog( + ReadSocialRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + refuse(observer, Status.UNAUTHENTICATED, "Authenticated workload required"); + return; + } + if (!peer.isService("game-session-service") + || !peer.isInNamespace(namespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + refuse( + observer, + Status.PERMISSION_DENIED, + "Exact same-namespace Game Session workload required without caller context"); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + refuse(observer, Status.FAILED_PRECONDITION, "Independent Social owner operation required"); + return; + } + Request request; + try { + request = SocialRuntimeFamilyCatalogCodec.fromRequest(wire); + } catch (IllegalArgumentException invalid) { + refuse(observer, Status.INVALID_ARGUMENT, "Complete bounded Social catalog request required"); + return; + } + if (!namespace.equals(request.targetNamespace())) { + refuse( + observer, + Status.PERMISSION_DENIED, + "Request namespace differs from authenticated workload"); + return; + } + ReadSocialRuntimeFamilyCatalogResponse response; + try { + response = SocialRuntimeFamilyCatalogCodec.toResponse(request, repository.read(request)); + } catch (SocialRuntimeFamilyCatalogRepository.CatalogConflictException + | IllegalArgumentException invalid) { + refuse(observer, Status.FAILED_PRECONDITION, "Social catalog is changed or inconsistent"); + return; + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException failure) { + refuse(observer, storageStatus(failure), "Social catalog storage read failed"); + return; + } catch (org.springframework.transaction.CannotCreateTransactionException unavailable) { + refuse(observer, Status.UNAVAILABLE, "Social catalog storage unavailable"); + return; + } catch (RuntimeException failure) { + refuse(observer, Status.INTERNAL, "Social catalog read failed"); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static Status storageStatus(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql && sql.getSQLState() != null) { + String state = sql.getSQLState(); + if (state.startsWith("23") || state.startsWith("P0") || state.equals("55000")) { + return Status.FAILED_PRECONDITION; + } + if (state.equals("40001") || state.equals("40P01")) return Status.ABORTED; + if (state.startsWith("08") || state.startsWith("57") || state.equals("55P03")) { + return Status.UNAVAILABLE; + } + if (state.startsWith("22") || state.startsWith("42") || state.startsWith("XX")) { + return Status.INTERNAL; + } + } + } + if (failure instanceof org.springframework.dao.DataIntegrityViolationException) { + return Status.FAILED_PRECONDITION; + } + if (failure instanceof org.springframework.dao.TransientDataAccessException + || failure instanceof org.springframework.dao.DataAccessResourceFailureException + || failure instanceof org.jooq.exception.DataAccessException) { + return Status.UNAVAILABLE; + } + return Status.INTERNAL; + } + + private static void refuse(StreamObserver observer, Status status, String message) { + observer.onError(status.withDescription(message).asRuntimeException()); + } +} diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogRepository.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogRepository.java new file mode 100644 index 0000000000..c6db12aa7a --- /dev/null +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogRepository.java @@ -0,0 +1,160 @@ +package net.firedevops.firemud.socialgroups.runtimecatalog; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalogCodec; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Manual owner-local schema-census capture and independent exact committed readback. */ +public final class SocialRuntimeFamilyCatalogRepository { + private final DSLContext dsl; + private final String schema; + private final String namespace; + private final TransactionTemplate capture; + private final TransactionTemplate readback; + + public SocialRuntimeFamilyCatalogRepository( + DSLContext dsl, PlatformTransactionManager transactions, String schema, String namespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (schema == null + || !schema.matches("[a-z][a-z0-9_]{0,62}") + || !GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixed Social schema and workload namespace required"); + } + this.schema = schema; + this.namespace = namespace; + capture = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + capture.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + capture.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + readback = new TransactionTemplate(transactions); + readback.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readback.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readback.setReadOnly(true); + } + + /** Each exact request identity retains one immutable catalog and response correlation. */ + public Evidence read(Request request) { + requireIndependent(request); + byte[] committed = + capture.execute( + status -> { + SocialRuntimeFamilyCatalog catalog = currentCatalog(); + byte[] requestBytes = SocialRuntimeFamilyCatalogCodec.requestBytes(request); + Evidence proposed = new Evidence(request, UUID.randomUUID(), catalog); + byte[] evidenceBytes = SocialRuntimeFamilyCatalogCodec.evidenceBytes(proposed); + dsl.execute( + "INSERT INTO " + + table("social_runtime_family_catalog_snapshot") + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," + + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" + + " ON CONFLICT (read_request_id) DO NOTHING", + request.readRequestId(), + request.targetNamespace(), + requestBytes, + SocialRuntimeFamilyCatalog.sha256(requestBytes), + proposed.snapshotId(), + catalog.catalogEpoch(), + catalog.digest(), + evidenceBytes, + proposed.digest()); + return retained(request, catalog); + }); + Evidence result = readExact(request); + if (!Arrays.equals(committed, SocialRuntimeFamilyCatalogCodec.evidenceBytes(result))) { + throw new CatalogConflictException("Committed Social catalog readback changed"); + } + return result; + } + + /** Reads existing exact evidence only; drift or missing evidence is never empty success. */ + public Evidence readExact(Request request) { + requireIndependent(request); + return readback.execute( + status -> + SocialRuntimeFamilyCatalogCodec.evidenceFromStored( + retained(request, currentCatalog()))); + } + + private SocialRuntimeFamilyCatalog currentCatalog() { + Record row = + dsl.fetchOne( + "SELECT catalog_epoch,catalog_bytes,catalog_digest," + + schema + + ".social_runtime_family_catalog_bytes(catalog_epoch) AS current_bytes FROM " + + table("social_runtime_family_catalog_epoch") + + " WHERE " + + schema + + ".social_runtime_family_catalog_installed()" + + " ORDER BY catalog_epoch DESC LIMIT 1"); + if (row == null) throw new CatalogConflictException("No durable Social catalog epoch"); + byte[] sealed = row.get("catalog_bytes", byte[].class); + if (!Arrays.equals(sealed, row.get("current_bytes", byte[].class))) { + throw new CatalogConflictException( + "Social schema/classification drift invalidates its epoch"); + } + SocialRuntimeFamilyCatalog catalog = SocialRuntimeFamilyCatalog.fromStored(sealed); + if (catalog.catalogEpoch() != row.get("catalog_epoch", Long.class) + || !catalog.digest().equals(row.get("catalog_digest", String.class))) { + throw new CatalogConflictException("Social catalog epoch/digest binding is inconsistent"); + } + return catalog; + } + + private byte[] retained(Request request, SocialRuntimeFamilyCatalog current) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + table("social_runtime_family_catalog_snapshot") + + " WHERE read_request_id=?", + request.readRequestId()); + if (row == null) throw new CatalogConflictException("Exact Social catalog snapshot is absent"); + byte[] bytes = row.get("evidence_bytes", byte[].class); + Evidence result = SocialRuntimeFamilyCatalogCodec.evidenceFromStored(bytes); + byte[] requestBytes = SocialRuntimeFamilyCatalogCodec.requestBytes(request); + if (!request.equals(result.request()) + || !request.targetNamespace().equals(row.get("target_namespace", String.class)) + || !Arrays.equals(requestBytes, row.get("request_bytes", byte[].class)) + || !SocialRuntimeFamilyCatalog.sha256(requestBytes) + .equals(row.get("request_digest", String.class)) + || !result.snapshotId().equals(row.get("snapshot_id", UUID.class)) + || result.catalog().catalogEpoch() != row.get("catalog_epoch", Long.class) + || !result.catalog().digest().equals(row.get("catalog_digest", String.class)) + || !result.digest().equals(row.get("evidence_digest", String.class)) + || !Arrays.equals(current.exactBytes(), result.catalog().exactBytes())) { + throw new CatalogConflictException("Changed request or invalidated Social catalog snapshot"); + } + return bytes; + } + + private String table(String name) { + return schema + "." + name; + } + + private void requireIndependent(Request request) { + Objects.requireNonNull(request, "request"); + if (!namespace.equals(request.targetNamespace())) { + throw new CatalogConflictException("Wrong Social workload namespace"); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Social catalog evidence requires independent owner transactions"); + } + } + + public static final class CatalogConflictException extends IllegalStateException { + public CatalogConflictException(String message) { + super(message); + } + } +} diff --git a/services/social-groups-service/src/main/resources/db/migration/V1004__social_owner_runtime_family_catalog.sql b/services/social-groups-service/src/main/resources/db/migration/V1004__social_owner_runtime_family_catalog.sql new file mode 100644 index 0000000000..d593b0874b --- /dev/null +++ b/services/social-groups-service/src/main/resources/db/migration/V1004__social_owner_runtime_family_catalog.sql @@ -0,0 +1,280 @@ +-- This additive owner-local source records installed schema/classification evidence only. It does +-- not change social payload, relationship, replay, history, sequence, Saga, or authority rows. +CREATE TABLE social_runtime_family_classification ( + family_id VARCHAR(127) PRIMARY KEY, + relation_name VARCHAR(63) NOT NULL, + component_name VARCHAR(63) NOT NULL DEFAULT '', + family_role VARCHAR(40) NOT NULL CHECK (family_role IN + ('GUILD_DEFINITION_ACL','GUILD_MEMBERSHIP_ACL','SOCIAL_RELATIONSHIP','OWNERSHIP_DRIFT', + 'PLAYER_HISTORY','EFFECT_REPLAY','ACCOUNT_IDENTITY_CARRIER','OPERATIONAL_EVIDENCE', + 'MIGRATION_HISTORY','CATALOG')), + fresh_disposition VARCHAR(72) NOT NULL CHECK (fresh_disposition IN + ('GUILD_SUBJECT_TYPE_UNSUPPORTED','GUILD_CHILD_TENANT_IDENTITY_UNPROVEN', + 'RELATIONSHIP_BLOCK_LIFECYCLE_UNIMPLEMENTED','ACCOUNT_PAIR_SCOPE_DRIFT', + 'ENTITY_VALUE_OWNERSHIP_DRIFT_BLOCKING', + 'CHAT_HISTORY_RETENTION_VIEW_AND_WHISPER_SCOPE_UNPROVEN', + 'CHAT_EFFECT_REPLAY_DIGEST_AND_HORIZON_UNPROVEN', + 'MAIL_HISTORY_RETENTION_AND_ACKNOWLEDGEMENT_UNPROVEN', + 'ACCOUNT_IDENTITY_CARRIER_ONLY','SAGA_ADOPTER_UNRESOLVED', + 'MIGRATION_HISTORY_ONLY','CATALOG_ONLY')), + target_owner VARCHAR(40) NOT NULL CHECK (target_owner IN + ('NONE','ACCOUNT_SERVICE','ENTITY_MANAGEMENT_SERVICE')), + UNIQUE (relation_name, component_name), + CHECK (relation_name ~ '^[a-z][a-z0-9_]{0,62}$'), + CHECK (component_name = '' OR component_name ~ '^[a-z][a-z0-9_]{0,62}$'), + CHECK (family_id = relation_name || CASE WHEN component_name = '' THEN '' ELSE '.' || component_name END), + CHECK ( + (fresh_disposition = 'GUILD_SUBJECT_TYPE_UNSUPPORTED' + AND family_role IN ('GUILD_DEFINITION_ACL','GUILD_MEMBERSHIP_ACL') AND target_owner='NONE') + OR (fresh_disposition IN ('GUILD_CHILD_TENANT_IDENTITY_UNPROVEN', + 'RELATIONSHIP_BLOCK_LIFECYCLE_UNIMPLEMENTED', + 'ACCOUNT_PAIR_SCOPE_DRIFT') + AND family_role='SOCIAL_RELATIONSHIP' AND target_owner='NONE') + OR (fresh_disposition='ENTITY_VALUE_OWNERSHIP_DRIFT_BLOCKING' + AND family_role='OWNERSHIP_DRIFT' AND target_owner='ENTITY_MANAGEMENT_SERVICE') + OR (fresh_disposition IN ('CHAT_HISTORY_RETENTION_VIEW_AND_WHISPER_SCOPE_UNPROVEN', + 'MAIL_HISTORY_RETENTION_AND_ACKNOWLEDGEMENT_UNPROVEN') + AND family_role='PLAYER_HISTORY' AND target_owner='NONE') + OR (fresh_disposition='CHAT_EFFECT_REPLAY_DIGEST_AND_HORIZON_UNPROVEN' + AND family_role='EFFECT_REPLAY' AND target_owner='NONE') + OR (fresh_disposition='ACCOUNT_IDENTITY_CARRIER_ONLY' + AND family_role='ACCOUNT_IDENTITY_CARRIER' AND target_owner='ACCOUNT_SERVICE') + OR (fresh_disposition='SAGA_ADOPTER_UNRESOLVED' + AND family_role='OPERATIONAL_EVIDENCE' AND target_owner='NONE') + OR (fresh_disposition='MIGRATION_HISTORY_ONLY' + AND family_role='MIGRATION_HISTORY' AND target_owner='NONE') + OR (fresh_disposition='CATALOG_ONLY' AND family_role='CATALOG' AND target_owner='NONE') + ) +); + +CREATE TABLE social_runtime_family_catalog_epoch ( + catalog_epoch BIGINT PRIMARY KEY CHECK (catalog_epoch > 0), + catalog_bytes BYTEA NOT NULL CHECK (octet_length(catalog_bytes) BETWEEN 1 AND 2097152), + catalog_digest VARCHAR(71) NOT NULL CHECK + (catalog_digest = 'sha256:' || encode(sha256(catalog_bytes), 'hex')), + installed_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE social_runtime_family_catalog_snapshot ( + read_request_id UUID PRIMARY KEY CHECK (read_request_id <> '00000000-0000-0000-0000-000000000000'), + target_namespace VARCHAR(63) NOT NULL CHECK + (target_namespace ~ '^[a-z0-9]([-a-z0-9]*[a-z0-9])?$'), + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) BETWEEN 1 AND 1024), + request_digest VARCHAR(71) NOT NULL CHECK + (request_digest = 'sha256:' || encode(sha256(request_bytes), 'hex')), + snapshot_id UUID NOT NULL UNIQUE CHECK (snapshot_id <> '00000000-0000-0000-0000-000000000000'), + catalog_epoch BIGINT NOT NULL REFERENCES social_runtime_family_catalog_epoch(catalog_epoch), + catalog_digest VARCHAR(71) NOT NULL, + evidence_bytes BYTEA NOT NULL CHECK (octet_length(evidence_bytes) BETWEEN 1 AND 2101248), + evidence_digest VARCHAR(71) NOT NULL CHECK + (evidence_digest = 'sha256:' || encode(sha256(evidence_bytes), 'hex')), + retained_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +-- Every installed Social-family table receives one owner-local role/disposition. Specialized +-- column families make Account UUID carriers and the chat-only effect replay key visible without +-- pretending those columns prove a row-level FRESH manifest or initialized empty target. +-- [jooq ignore start] +INSERT INTO social_runtime_family_classification + (family_id, relation_name, component_name, family_role, fresh_disposition, target_owner) +VALUES + ('guilds','guilds','','GUILD_DEFINITION_ACL','GUILD_SUBJECT_TYPE_UNSUPPORTED','NONE'), + ('guilds.owner_account_id','guilds','owner_account_id','ACCOUNT_IDENTITY_CARRIER','ACCOUNT_IDENTITY_CARRIER_ONLY','ACCOUNT_SERVICE'), + ('guild_members','guild_members','','GUILD_MEMBERSHIP_ACL','GUILD_SUBJECT_TYPE_UNSUPPORTED','NONE'), + ('guild_members.account_id','guild_members','account_id','ACCOUNT_IDENTITY_CARRIER','ACCOUNT_IDENTITY_CARRIER_ONLY','ACCOUNT_SERVICE'), + ('guild_alliances','guild_alliances','','SOCIAL_RELATIONSHIP','GUILD_CHILD_TENANT_IDENTITY_UNPROVEN','NONE'), + ('friend_links','friend_links','','SOCIAL_RELATIONSHIP','RELATIONSHIP_BLOCK_LIFECYCLE_UNIMPLEMENTED','NONE'), + ('friend_links.account_id','friend_links','account_id','ACCOUNT_IDENTITY_CARRIER','ACCOUNT_IDENTITY_CARRIER_ONLY','ACCOUNT_SERVICE'), + ('friend_links.friend_account_id','friend_links','friend_account_id','ACCOUNT_IDENTITY_CARRIER','ACCOUNT_IDENTITY_CARRIER_ONLY','ACCOUNT_SERVICE'), + ('account_friend_links','account_friend_links','','SOCIAL_RELATIONSHIP','ACCOUNT_PAIR_SCOPE_DRIFT','NONE'), + ('account_friend_links.account_id','account_friend_links','account_id','ACCOUNT_IDENTITY_CARRIER','ACCOUNT_IDENTITY_CARRIER_ONLY','ACCOUNT_SERVICE'), + ('account_friend_links.friend_account_id','account_friend_links','friend_account_id','ACCOUNT_IDENTITY_CARRIER','ACCOUNT_IDENTITY_CARRIER_ONLY','ACCOUNT_SERVICE'), + ('guild_storage_items','guild_storage_items','','OWNERSHIP_DRIFT','ENTITY_VALUE_OWNERSHIP_DRIFT_BLOCKING','ENTITY_MANAGEMENT_SERVICE'), + ('chat_messages','chat_messages','','PLAYER_HISTORY','CHAT_HISTORY_RETENTION_VIEW_AND_WHISPER_SCOPE_UNPROVEN','NONE'), + ('chat_messages.sender_account_id','chat_messages','sender_account_id','ACCOUNT_IDENTITY_CARRIER','ACCOUNT_IDENTITY_CARRIER_ONLY','ACCOUNT_SERVICE'), + ('chat_messages.recipient_account_id','chat_messages','recipient_account_id','ACCOUNT_IDENTITY_CARRIER','ACCOUNT_IDENTITY_CARRIER_ONLY','ACCOUNT_SERVICE'), + ('chat_messages.effect_id','chat_messages','effect_id','EFFECT_REPLAY','CHAT_EFFECT_REPLAY_DIGEST_AND_HORIZON_UNPROVEN','NONE'), + ('mail_messages','mail_messages','','PLAYER_HISTORY','MAIL_HISTORY_RETENTION_AND_ACKNOWLEDGEMENT_UNPROVEN','NONE'), + ('mail_messages.sender_account_id','mail_messages','sender_account_id','ACCOUNT_IDENTITY_CARRIER','ACCOUNT_IDENTITY_CARRIER_ONLY','ACCOUNT_SERVICE'), + ('mail_messages.recipient_account_id','mail_messages','recipient_account_id','ACCOUNT_IDENTITY_CARRIER','ACCOUNT_IDENTITY_CARRIER_ONLY','ACCOUNT_SERVICE'), + ('saga_instance','saga_instance','','OPERATIONAL_EVIDENCE','SAGA_ADOPTER_UNRESOLVED','NONE'), + ('saga_step','saga_step','','OPERATIONAL_EVIDENCE','SAGA_ADOPTER_UNRESOLVED','NONE'), + ('social_runtime_family_classification','social_runtime_family_classification','','CATALOG','CATALOG_ONLY','NONE'), + ('social_runtime_family_catalog_epoch','social_runtime_family_catalog_epoch','','CATALOG','CATALOG_ONLY','NONE'), + ('social_runtime_family_catalog_snapshot','social_runtime_family_catalog_snapshot','','CATALOG','CATALOG_ONLY','NONE'), + ('${flyway:table}','${flyway:table}','','MIGRATION_HISTORY','MIGRATION_HISTORY_ONLY','NONE'); + +-- This function deliberately uses Flyway 13.12's actual configured history-table placeholder. +-- The own V1004 history row is post-transaction, represented by the stable installation marker; +-- the installed-row check below separately requires its exact successful script identity. +CREATE FUNCTION social_runtime_family_catalog_installed() RETURNS BOOLEAN +LANGUAGE SQL STABLE +SET search_path = "${serviceSchema}", pg_catalog +AS $$ + SELECT EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1004' + AND script='V1004__social_owner_runtime_family_catalog.sql' + AND success); +$$; + +CREATE FUNCTION social_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE +SET search_path = "${serviceSchema}", pg_catalog +AS $$ +DECLARE + v_families JSONB; + v_facts JSONB; +BEGIN + IF p_epoch IS NULL OR p_epoch <= 0 THEN + RAISE EXCEPTION 'Positive Social catalog epoch required' USING ERRCODE='23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM social_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM social_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed Social schema family' USING ERRCODE='23514'; + END IF; + + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name, + 'component',component_name,'role',family_role,'freshDisposition',fresh_disposition, + 'targetOwner',target_owner) ORDER BY family_id COLLATE "C") + INTO v_families FROM social_runtime_family_classification; + + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname, + jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,pg_get_viewdef(c.oid,true) + FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1004' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1004','V1004__social_owner_runtime_family_catalog.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + + IF jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 THEN + RAISE EXCEPTION 'Complete Social catalog exceeds source bounds' USING ERRCODE='23514'; + END IF; + RETURN convert_to(jsonb_build_object('schema','social-runtime-family-catalog/v1', + 'owner','social-groups-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts, + 'unimplementedContracts',jsonb_build_array( + 'CHAT_RESTRICTION_AND_REVISION', + 'DIRECTIONAL_BLOCK_LIFECYCLE', + 'ENTITY_ESCROW_REFERENCE_FAMILIES', + 'GAMEPLAY_WHISPER_NAMESPACE_SCOPE', + 'SAFETY_EVIDENCE_AND_CONTENT_FREE_RECEIPTS', + 'SOCIAL_PLAYER_STANDING_OWNER', + 'SOCIAL_SAGA_ADOPTER_CLASSIFICATION'))::TEXT,'UTF8'); +END; +$$; + +CREATE FUNCTION social_runtime_family_catalog_immutable() RETURNS TRIGGER +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Social runtime catalog evidence is immutable' USING ERRCODE='23514'; +END; +$$; + +CREATE TRIGGER social_runtime_family_classification_retained +BEFORE UPDATE OR DELETE OR TRUNCATE ON social_runtime_family_classification +FOR EACH STATEMENT EXECUTE FUNCTION social_runtime_family_catalog_immutable(); +CREATE TRIGGER social_runtime_family_epoch_retained +BEFORE UPDATE OR DELETE OR TRUNCATE ON social_runtime_family_catalog_epoch +FOR EACH STATEMENT EXECUTE FUNCTION social_runtime_family_catalog_immutable(); +CREATE TRIGGER social_runtime_family_snapshot_retained +BEFORE UPDATE OR DELETE OR TRUNCATE ON social_runtime_family_catalog_snapshot +FOR EACH STATEMENT EXECUTE FUNCTION social_runtime_family_catalog_immutable(); + +CREATE FUNCTION social_runtime_family_catalog_epoch_guard() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = "${serviceSchema}", pg_catalog AS $$ +BEGIN + IF NEW.catalog_epoch<>coalesce((SELECT max(catalog_epoch) FROM social_runtime_family_catalog_epoch),0)+1 + OR NEW.catalog_bytes<>social_runtime_family_catalog_bytes(NEW.catalog_epoch) THEN + RAISE EXCEPTION 'Social epoch must bind the exact classified installed schema' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER social_runtime_family_epoch_exact BEFORE INSERT ON social_runtime_family_catalog_epoch +FOR EACH ROW EXECUTE FUNCTION social_runtime_family_catalog_epoch_guard(); + +CREATE FUNCTION social_runtime_family_catalog_snapshot_guard() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE v_epoch social_runtime_family_catalog_epoch%ROWTYPE; +BEGIN + SELECT * INTO STRICT v_epoch FROM social_runtime_family_catalog_epoch ORDER BY catalog_epoch DESC LIMIT 1; + IF NEW.catalog_epoch<>v_epoch.catalog_epoch OR NEW.catalog_digest<>v_epoch.catalog_digest + OR social_runtime_family_catalog_bytes(v_epoch.catalog_epoch)<>v_epoch.catalog_bytes + OR NOT social_runtime_family_catalog_installed() THEN + RAISE EXCEPTION 'Social schema/classification changed; new owner epoch required' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER social_runtime_family_snapshot_current BEFORE INSERT ON social_runtime_family_catalog_snapshot +FOR EACH ROW EXECUTE FUNCTION social_runtime_family_catalog_snapshot_guard(); +-- [jooq ignore stop] + +-- The current-owner seed is PostgreSQL-only because it invokes a pg_catalog census function. +-- Ordinary table/column DDL above remains visible to generated jOOQ schema access. +-- [jooq ignore start] +INSERT INTO social_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT 1,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM (SELECT social_runtime_family_catalog_bytes(1) AS bytes) seal; +-- [jooq ignore stop] diff --git a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java new file mode 100644 index 0000000000..ecd0186d3b --- /dev/null +++ b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -0,0 +1,599 @@ +package integration.net.firedevops.firemud.socialgroups.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.FactKind; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.FreshDisposition; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.socialgroups.runtimecatalog.SocialRuntimeFamilyCatalogReadGrpcService; +import net.firedevops.firemud.socialgroups.runtimecatalog.SocialRuntimeFamilyCatalogRepository; +import net.firedevops.firemud.socialgroups.v1.ReadSocialRuntimeFamilyCatalogResponse; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual installed Social/Saga PostgreSQL proof; caller identity is controlled, not physical mTLS. + */ +@Testcontainers +@SuppressWarnings("resource") +class SocialRuntimeFamilyCatalogPostgresIntegrationTest { + private static final List RETAINED_TABLES = + List.of( + "guilds", + "guild_members", + "guild_storage_items", + "guild_alliances", + "chat_messages", + "friend_links", + "account_friend_links", + "mail_messages", + "saga_instance", + "saga_step"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void configuredFlywayHistoryNameIsTheInstalledHistoryFamilyAndExactHistorySource() + throws Exception { + for (String history : + List.of( + "flyway_schema_history_social_groups_service", "flyway_schema_history_custom_social")) { + try (Fixture f = fixture(null, history)) { + var evidence = f.owner().read(request()); + assertThat(evidence.catalog().families()) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo(history); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.MIGRATION_HISTORY_ONLY); + }); + assertThat(evidence.catalog().schemaFacts()) + .anySatisfy( + fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.TABLE); + assertThat(fact.identity()).isEqualTo(history); + }) + .anySatisfy( + fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); + assertThat(fact.identity()).isEqualTo("catalog-installation:1004"); + }); + assertThat(f.owner().readExact(evidence.request())).isEqualTo(evidence); + assertThat( + f.dsl + .fetchSingle("SELECT to_regclass(?) IS NULL", f.schema + "." + defaultHistory()) + .get(0, Boolean.class)) + .isEqualTo(!history.equals(defaultHistory())); + assertThat( + f.dsl + .fetchSingle( + "SELECT " + f.schema + ".social_runtime_family_catalog_installed()") + .get(0, Boolean.class)) + .isTrue(); + } + } + } + + @Test + void actualCombinedSocialSagaCensusClassifiesEveryInstalledTableWithoutRowInference() + throws Exception { + try (Fixture f = fixture(null)) { + var catalog = f.owner().read(request()).catalog(); + assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat( + catalog.schemaFacts().stream() + .filter(fact -> fact.kind() == FactKind.TABLE) + .map(SocialRuntimeFamilyCatalog.SchemaFact::identity) + .toList()) + .containsExactlyInAnyOrderElementsOf( + f.dsl + .fetch( + "SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace" + + " WHERE n.nspname=? AND c.relkind IN ('r','p','f')", + f.schema) + .getValues(0, String.class)); + assertThat(catalog.families().stream().filter(family -> family.component().isEmpty()).count()) + .isEqualTo( + catalog.schemaFacts().stream().filter(fact -> fact.kind() == FactKind.TABLE).count()); + assertThat(catalog.families()) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo("account_friend_links"); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.ACCOUNT_PAIR_SCOPE_DRIFT); + }) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo("guild_storage_items"); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.ENTITY_VALUE_OWNERSHIP_DRIFT_BLOCKING); + assertThat(family.targetOwner()) + .isEqualTo(SocialRuntimeFamilyCatalog.TargetOwner.ENTITY_MANAGEMENT_SERVICE); + }) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo("saga_instance"); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.SAGA_ADOPTER_UNRESOLVED); + }) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo("chat_messages.effect_id"); + assertThat(family.role()).isEqualTo(SocialRuntimeFamilyCatalog.Role.EFFECT_REPLAY); + }); + assertThat(catalog.families()) + .noneMatch( + family -> + family.familyId().equals("guild_storage_items.item_name") + || family.familyId().equals("guild_storage_items.quantity")); + assertThat(catalog.unimplementedContracts()) + .containsExactly( + SocialRuntimeFamilyCatalog.ContractGap.CHAT_RESTRICTION_AND_REVISION, + SocialRuntimeFamilyCatalog.ContractGap.DIRECTIONAL_BLOCK_LIFECYCLE, + SocialRuntimeFamilyCatalog.ContractGap.ENTITY_ESCROW_REFERENCE_FAMILIES, + SocialRuntimeFamilyCatalog.ContractGap.GAMEPLAY_WHISPER_NAMESPACE_SCOPE, + SocialRuntimeFamilyCatalog.ContractGap.SAFETY_EVIDENCE_AND_CONTENT_FREE_RECEIPTS, + SocialRuntimeFamilyCatalog.ContractGap.SOCIAL_PLAYER_STANDING_OWNER, + SocialRuntimeFamilyCatalog.ContractGap.SOCIAL_SAGA_ADOPTER_CLASSIFICATION); + assertThat(catalog.schemaFacts()) + .anyMatch(fact -> fact.kind() == FactKind.MIGRATION) + .anyMatch(fact -> fact.kind() == FactKind.ROUTINE) + .anyMatch(fact -> fact.kind() == FactKind.COLUMN); + assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); + assertThat( + f.dsl + .fetchSingle( + "SELECT catalog_bytes = social_runtime_family_catalog_bytes(catalog_epoch)" + + " FROM social_runtime_family_catalog_epoch") + .get(0, Boolean.class)) + .isTrue(); + } + } + + @Test + void exactRetriesIndependentReadbackAndConcurrentReplaysRetainOneSnapshot() throws Exception { + try (Fixture f = fixture(null); + var workers = Executors.newFixedThreadPool(2)) { + Request read = request(); + var first = workers.submit(() -> f.owner().read(read)); + var second = workers.submit(() -> f.owner().read(read)); + var original = first.get(30, TimeUnit.SECONDS); + assertThat(second.get(30, TimeUnit.SECONDS)).isEqualTo(original); + assertThat(f.owner().read(read)).isEqualTo(original); + assertThat(f.owner().readExact(read)).isEqualTo(original); + assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); + var next = f.owner().read(request()); + assertThat(next.snapshotId()).isNotEqualTo(original.snapshotId()); + assertThat(next.catalog().exactBytes()).isEqualTo(original.catalog().exactBytes()); + assertThat(next.digest()).isNotEqualTo(original.digest()); + assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(2); + var wrongNamespace = + new SocialRuntimeFamilyCatalogRepository(f.dsl, f.manager, f.schema, "other"); + assertThatThrownBy(() -> wrongNamespace.read(new Request(read.readRequestId(), "other"))) + .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().readExact(request())) + .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); + var transaction = new TransactionTemplate(f.manager); + assertThatThrownBy(() -> transaction.execute(status -> f.owner().read(request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent"); + assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(2); + } + } + + @Test + void forwardMigrationRetainsPopulatedSocialSagaRowsAndEveryPriorHistoryRow() throws Exception { + try (Fixture f = fixture("1003")) { + long guild = + f.dsl + .fetchSingle( + "INSERT INTO guilds(tenant_id,name,owner_account_id) VALUES (7,'retained',?::uuid) RETURNING id", + "10000000-0000-4000-8000-000000000001") + .get(0, Long.class); + f.dsl.execute( + "INSERT INTO guild_members(tenant_id,guild_id,account_id,role) VALUES (7,?,?::uuid,'owner')", + guild, + "10000000-0000-4000-8000-000000000001"); + f.dsl.execute( + "INSERT INTO guild_storage_items(tenant_id,guild_id,item_name,quantity) VALUES (7,?,'legacy-value',4)", + guild); + f.dsl.execute( + "INSERT INTO guild_alliances(tenant_id,guild_id,ally_guild_id,created_at) VALUES (7,?,9,TIMESTAMP '2026-10-01 00:00:00')", + guild); + f.dsl.execute( + "INSERT INTO chat_messages(tenant_id,sender_account_id,recipient_account_id,content,effect_id)" + + " VALUES (7,?::uuid,?::uuid,'retained chat','retained-effect')", + "10000000-0000-4000-8000-000000000001", + "10000000-0000-4000-8000-000000000002"); + f.dsl.execute( + "INSERT INTO friend_links(tenant_id,account_id,friend_account_id,status) VALUES (7,?::uuid,?::uuid,'active')", + "10000000-0000-4000-8000-000000000001", + "10000000-0000-4000-8000-000000000002"); + f.dsl.execute( + "INSERT INTO account_friend_links(tenant_id,account_id,friend_account_id,status) VALUES (7,?::uuid,?::uuid,'active')", + "10000000-0000-4000-8000-000000000001", + "10000000-0000-4000-8000-000000000002"); + f.dsl.execute( + "INSERT INTO mail_messages(tenant_id,sender_account_id,recipient_account_id,subject,content)" + + " VALUES (7,?::uuid,?::uuid,'retained','retained mail')", + "10000000-0000-4000-8000-000000000001", + "10000000-0000-4000-8000-000000000002"); + long saga = + f.dsl + .fetchSingle( + "INSERT INTO saga_instance(saga_name,state) VALUES ('retained-saga','RUNNING') RETURNING id") + .get(0, Long.class); + f.dsl.execute( + "INSERT INTO saga_step(instance_id,name,status) VALUES (?, 'retained-step','PENDING')", + saga); + + Map rowsBefore = f.retainedRows(); + List historyBefore = f.historyRows(); + migrate(f, null); + assertThat(f.retainedRows()).isEqualTo(rowsBefore); + assertThat(f.historyRowsExcluding("1004")).isEqualTo(historyBefore); + var catalog = f.owner().read(request()).catalog(); + assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat(catalog.families()) + .anySatisfy( + family -> + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.ENTITY_VALUE_OWNERSHIP_DRIFT_BLOCKING)); + assertThat(f.retainedRows()).isEqualTo(rowsBefore); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(1); + assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); + } + } + + @Test + void emptyUnclassifiedNewTableInvalidatesExactAndNewReadsWithoutResampling() throws Exception { + try (Fixture f = fixture(null)) { + Request retained = request(); + f.owner().read(retained); + f.dsl.execute("CREATE TABLE unknown_runtime_family (id BIGINT PRIMARY KEY)"); + assertThat(f.count("unknown_runtime_family")).isZero(); + assertThatThrownBy(() -> f.owner().readExact(retained)).hasMessageContaining("Unclassified"); + assertThatThrownBy(() -> f.owner().read(request())).hasMessageContaining("Unclassified"); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(1); + assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); + } + } + + @Test + void migrationRefusesPreexistingUnclassifiedFamilyAtomicallyAndKeepsParentHistory() + throws Exception { + try (Fixture f = fixture("1003")) { + f.dsl.execute("CREATE TABLE unknown_runtime_family (id BIGINT PRIMARY KEY)"); + List historyBefore = f.historyRows(); + assertThatThrownBy(() -> migrate(f, null)).hasMessageContaining("Unclassified or changed"); + assertThat(f.tableAbsent("social_runtime_family_catalog_epoch")).isTrue(); + assertThat(f.tableAbsent("social_runtime_family_classification")).isTrue(); + assertThat(f.historyRows()).isEqualTo(historyBefore); + assertThat(f.tableAbsent("unknown_runtime_family")).isFalse(); + } + } + + @Test + void schemaColumnConstraintTriggerRoutineAndRemovalChangesCannotResampleUnderSameEpoch() + throws Exception { + for (String change : + List.of( + "ALTER TABLE chat_messages ADD COLUMN future_state TEXT", + "ALTER TABLE chat_messages RENAME COLUMN effect_id TO renamed_effect_id", + "ALTER TABLE chat_messages ADD CONSTRAINT catalog_probe CHECK (id > 0)", + "CREATE TRIGGER catalog_probe BEFORE INSERT ON guilds FOR EACH ROW EXECUTE FUNCTION social_runtime_family_immutable_probe()", + "CREATE FUNCTION social_runtime_family_immutable_probe() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RETURN NEW; END $$", + "CREATE FUNCTION future_social_writer() RETURNS INTEGER LANGUAGE SQL AS 'SELECT 1'")) { + try (Fixture f = fixture(null)) { + Request retained = request(); + f.owner().read(retained); + if (change.startsWith("CREATE TRIGGER")) { + f.dsl.execute( + "CREATE FUNCTION social_runtime_family_immutable_probe() RETURNS trigger" + + " LANGUAGE plpgsql AS $$ BEGIN RETURN NEW; END $$"); + } + f.dsl.execute(change); + assertThatThrownBy(() -> f.owner().readExact(retained)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> f.owner().read(request())).isInstanceOf(RuntimeException.class); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(1); + assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); + } + } + try (Fixture f = fixture(null)) { + Request retained = request(); + f.owner().read(retained); + f.dsl.execute("DROP TABLE guild_storage_items"); + assertThatThrownBy(() -> f.owner().readExact(retained)) + .hasMessageContaining("Unclassified or changed"); + } + } + + @Test + void changedClassificationMigrationHistoryOrUnsuccessfulInstallationRefusesOldSource() + throws Exception { + try (Fixture f = fixture(null)) { + Request retained = request(); + f.owner().read(retained); + f.dsl.execute( + "INSERT INTO social_runtime_family_classification" + + " (family_id,relation_name,component_name,family_role,fresh_disposition,target_owner)" + + " VALUES ('guilds.name','guilds','name','GUILD_DEFINITION_ACL','GUILD_SUBJECT_TYPE_UNSUPPORTED','NONE')"); + assertThatThrownBy(() -> f.owner().readExact(retained)) + .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(request())) + .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(1); + assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); + } + try (Fixture f = fixture(null)) { + Request retained = request(); + f.owner().read(retained); + f.dsl.execute("UPDATE " + f.history + " SET checksum=checksum+1 WHERE version='1'"); + assertThatThrownBy(() -> f.owner().readExact(retained)) + .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); + } + try (Fixture f = fixture(null)) { + var retained = f.owner().read(request()); + Request proposalRequest = request(); + var proposal = new Evidence(proposalRequest, UUID.randomUUID(), retained.catalog()); + byte[] requestBytes = SocialRuntimeFamilyCatalogCodec.requestBytes(proposalRequest); + byte[] evidenceBytes = SocialRuntimeFamilyCatalogCodec.evidenceBytes(proposal); + f.dsl.execute("UPDATE " + f.history + " SET success=false WHERE version='1004'"); + assertThatThrownBy(() -> f.owner().read(request())) + .hasMessageContaining("No durable Social catalog epoch"); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO social_runtime_family_catalog_snapshot" + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," + + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest)" + + " VALUES (?,?,?,?,?,?,?,?,?)", + proposalRequest.readRequestId(), + proposalRequest.targetNamespace(), + requestBytes, + SocialRuntimeFamilyCatalog.sha256(requestBytes), + proposal.snapshotId(), + proposal.catalog().catalogEpoch(), + proposal.catalog().digest(), + evidenceBytes, + proposal.digest())) + .hasMessageContaining("Social schema/classification changed"); + assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); + } + } + + @Test + void immutableMetadataAndSnapshotsRefuseMutationAndIncorrectEpochSeals() throws Exception { + try (Fixture f = fixture(null)) { + f.owner().read(request()); + for (String table : + List.of( + "social_runtime_family_catalog_epoch", + "social_runtime_family_classification", + "social_runtime_family_catalog_snapshot")) { + assertThatThrownBy(() -> f.dsl.execute("DELETE FROM " + table)) + .hasMessageContaining("immutable"); + assertThatThrownBy(() -> f.dsl.execute("TRUNCATE " + table + " CASCADE")) + .hasMessageContaining("immutable"); + } + assertThatThrownBy( + () -> f.dsl.execute("UPDATE social_runtime_family_catalog_epoch SET catalog_epoch=2")) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE social_runtime_family_classification SET fresh_disposition='CATALOG_ONLY'" + + " WHERE family_id='account_friend_links'")) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO social_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" + + " SELECT 2,catalog_bytes,catalog_digest FROM social_runtime_family_catalog_epoch WHERE catalog_epoch=1")) + .hasMessageContaining("exact classified installed schema"); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(1); + } + } + + @Test + void actualProducerReturnsCompleteCorrelatedEvidenceWithoutCallerContextOrRuntimeRows() + throws Exception { + try (Fixture f = fixture(null)) { + Request read = request(); + var service = new SocialRuntimeFamilyCatalogReadGrpcService(f.owner(), "test"); + var collector = new Collector(); + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") + .orElseThrow(); + SessionContext.clear(); + try { + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> + service.readSocialRuntimeFamilyCatalog( + SocialRuntimeFamilyCatalogCodec.toRequest(read), collector)); + } finally { + SessionContext.clear(); + } + assertThat(collector.error).isNull(); + assertThat(collector.completed).isTrue(); + var evidence = SocialRuntimeFamilyCatalogCodec.fromResponse(read, collector.value); + assertThat(f.owner().readExact(read)).isEqualTo(evidence); + assertThat(f.count("guilds")).isZero(); + assertThat(f.count("chat_messages")).isZero(); + assertThat(f.count("mail_messages")).isZero(); + var transaction = new TransactionTemplate(f.manager); + assertThatThrownBy(() -> transaction.execute(status -> f.owner().read(request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent"); + } + } + + private static Request request() { + return new Request(UUID.randomUUID(), "test"); + } + + private static String defaultHistory() { + return "flyway_schema_history_social_groups_service"; + } + + private static Fixture fixture(String target) { + return fixture(target, defaultHistory()); + } + + private static Fixture fixture(String target, String history) { + String schema = "social_catalog_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + try { + Flyway flyway = flyway(source, schema, history, target); + flyway.migrate(); + return new Fixture(schema, history, source, dsl, new DataSourceTransactionManager(source)); + } catch (RuntimeException failed) { + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + throw failed; + } + } + + private static Flyway flyway( + DriverManagerDataSource source, String schema, String history, String target) { + Path root = repositoryRoot(); + var configuration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .table(history) + .locations( + "filesystem:" + + root.resolve( + "services/social-groups-service/src/main/resources/db/migration"), + "filesystem:" + + root.resolve("services/common-saga/src/main/resources/db/migration/saga")) + .placeholders(Map.of("serviceSchema", schema)); + if (target != null) configuration.target(target); + return configuration.load(); + } + + private static Path repositoryRoot() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + if (Files.exists(current.resolve("settings.gradle.kts"))) return current; + current = current.getParent(); + } + throw new IllegalStateException("Unable to locate repository filesystem migrations"); + } + + private static void migrate(Fixture f, String target) { + flyway(f.source, f.schema, f.history, target).migrate(); + } + + private record Fixture( + String schema, + String history, + DriverManagerDataSource source, + DSLContext dsl, + DataSourceTransactionManager manager) + implements AutoCloseable { + SocialRuntimeFamilyCatalogRepository owner() { + return new SocialRuntimeFamilyCatalogRepository(dsl, manager, schema, "test"); + } + + long count(String table) { + return dsl.fetchSingle("SELECT count(*) FROM " + table).get(0, Long.class); + } + + boolean tableAbsent(String table) { + return dsl.fetchSingle("SELECT to_regclass(?) IS NULL", schema + "." + table) + .get(0, Boolean.class); + } + + Map retainedRows() { + return RETAINED_TABLES.stream() + .collect(java.util.stream.Collectors.toUnmodifiableMap(table -> table, this::jsonRows)); + } + + String jsonRows(String table) { + return dsl.fetchSingle( + "SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY id),'[]'::jsonb)::text FROM " + + table + + " t") + .get(0, String.class); + } + + List historyRows() { + return dsl.fetch("SELECT to_jsonb(h)::text FROM " + history + " h ORDER BY installed_rank") + .getValues(0, String.class); + } + + List historyRowsExcluding(String version) { + return dsl.fetch( + "SELECT to_jsonb(h)::text FROM " + + history + + " h WHERE version IS DISTINCT FROM ? ORDER BY installed_rank", + version) + .getValues(0, String.class); + } + + @Override + public void close() { + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + private static final class Collector + implements StreamObserver { + private ReadSocialRuntimeFamilyCatalogResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadSocialRuntimeFamilyCatalogResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcServiceTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcServiceTest.java new file mode 100644 index 0000000000..1ae7191f06 --- /dev/null +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcServiceTest.java @@ -0,0 +1,226 @@ +package unit.net.firedevops.firemud.socialgroups.runtimecatalog; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.socialgroups.runtimecatalog.SocialRuntimeFamilyCatalogReadGrpcService; +import net.firedevops.firemud.socialgroups.runtimecatalog.SocialRuntimeFamilyCatalogRepository; +import net.firedevops.firemud.socialgroups.v1.ReadSocialRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.socialgroups.v1.ReadSocialRuntimeFamilyCatalogResponse; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Controlled peer identity tests do not qualify physical mTLS; the GS test proves that boundary. + */ +class SocialRuntimeFamilyCatalogReadGrpcServiceTest { + @Test + void workloadRefusalPrecedesMalformedDecodeAndOwnerSql() { + var repository = mock(SocialRuntimeFamilyCatalogRepository.class); + var service = new SocialRuntimeFamilyCatalogReadGrpcService(repository, "test"); + var malformed = + ReadSocialRuntimeFamilyCatalogRequest.newBuilder() + .addCanonicalRequestBytes(ByteString.copyFromUtf8("bad frame")) + .build(); + assertThat(call(service, malformed, null).error).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(call(service, malformed, peer("account-service", "test")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(call(service, malformed, peer("game-session-service", "other")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext(UUID.randomUUID().toString(), List.of(), Map.of()); + try { + assertThat(call(service, malformed, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-session-service", "controlled"); + try { + assertThat(call(service, malformed, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(repository); + } + + @Test + void ambientTransactionOrSynchronizationRefusesBeforeDecodeAndSql() { + var repository = mock(SocialRuntimeFamilyCatalogRepository.class); + var service = new SocialRuntimeFamilyCatalogReadGrpcService(repository, "test"); + var malformed = ReadSocialRuntimeFamilyCatalogRequest.getDefaultInstance(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThat(call(service, malformed, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThat(call(service, malformed, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(repository); + } + + @Test + void authenticatedMalformedOversizedAndWrongNamespaceRequestsRefuseBeforeSql() { + var repository = mock(SocialRuntimeFamilyCatalogRepository.class); + var service = new SocialRuntimeFamilyCatalogReadGrpcService(repository, "test"); + var peer = peer("game-session-service", "test"); + assertThat( + call(service, ReadSocialRuntimeFamilyCatalogRequest.getDefaultInstance(), peer).error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + call( + service, + SocialRuntimeFamilyCatalogCodec.toRequest( + new Request(UUID.randomUUID(), "other")), + peer) + .error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + call( + service, + ReadSocialRuntimeFamilyCatalogRequest.newBuilder() + .addCanonicalRequestBytes(ByteString.copyFrom(new byte[1025])) + .build(), + peer) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void exactAuthenticatedRequestReturnsCompleteEvidenceAndDriftOrOutageNeverBecomesEmptySuccess() { + var repository = mock(SocialRuntimeFamilyCatalogRepository.class); + var service = new SocialRuntimeFamilyCatalogReadGrpcService(repository, "test"); + var request = new Request(UUID.randomUUID(), "test"); + var wire = SocialRuntimeFamilyCatalogCodec.toRequest(request); + var expected = evidence(request); + when(repository.read(request)).thenReturn(expected); + Collector success = call(service, wire, peer("game-session-service", "test")); + assertThat(success.error).isNull(); + assertThat(success.completed).isTrue(); + assertThat(SocialRuntimeFamilyCatalogCodec.fromResponse(request, success.value)) + .isEqualTo(expected); + verify(repository).read(request); + + doThrow(new SocialRuntimeFamilyCatalogRepository.CatalogConflictException("private details")) + .when(repository) + .read(request); + Collector drift = call(service, wire, peer("game-session-service", "test")); + assertThat(drift.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(drift.value).isNull(); + assertThat(drift.description).doesNotContain("private details"); + + doThrow( + new org.jooq.exception.DataAccessException( + "private schema drift", new SQLException("private schema drift", "23514"))) + .when(repository) + .read(request); + Collector schemaDrift = call(service, wire, peer("game-session-service", "test")); + assertThat(schemaDrift.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(schemaDrift.value).isNull(); + assertThat(schemaDrift.description).doesNotContain("private schema drift"); + + doThrow( + new org.jooq.exception.DataAccessException( + "private SQL", new SQLException("private SQL", "08006"))) + .when(repository) + .read(request); + Collector outage = call(service, wire, peer("game-session-service", "test")); + assertThat(outage.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(outage.value).isNull(); + assertThat(outage.description).doesNotContain("private SQL"); + } + + private static Evidence evidence(Request request) { + String json = + """ + {"schema":"social-runtime-family-catalog/v1","owner":"social-groups-service","catalogEpoch":"1", + "families":[{"familyId":"account_friend_links","relation":"account_friend_links","component":"", + "role":"SOCIAL_RELATIONSHIP","freshDisposition":"ACCOUNT_PAIR_SCOPE_DRIFT","targetOwner":"NONE"}, + {"familyId":"account_friend_links.account_id","relation":"account_friend_links","component":"account_id", + "role":"ACCOUNT_IDENTITY_CARRIER","freshDisposition":"ACCOUNT_IDENTITY_CARRIER_ONLY","targetOwner":"ACCOUNT_SERVICE"}, + {"familyId":"account_friend_links.friend_account_id","relation":"account_friend_links","component":"friend_account_id", + "role":"ACCOUNT_IDENTITY_CARRIER","freshDisposition":"ACCOUNT_IDENTITY_CARRIER_ONLY","targetOwner":"ACCOUNT_SERVICE"}], + "schemaFacts":[{"kind":"COLUMN","identity":"account_friend_links.account_id","definitionDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, + {"kind":"COLUMN","identity":"account_friend_links.friend_account_id","definitionDigest":"sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}, + {"kind":"TABLE","identity":"account_friend_links","definitionDigest":"sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"}], + "unimplementedContracts":["CHAT_RESTRICTION_AND_REVISION","DIRECTIONAL_BLOCK_LIFECYCLE", + "ENTITY_ESCROW_REFERENCE_FAMILIES","GAMEPLAY_WHISPER_NAMESPACE_SCOPE", + "SAFETY_EVIDENCE_AND_CONTENT_FREE_RECEIPTS","SOCIAL_PLAYER_STANDING_OWNER", + "SOCIAL_SAGA_ADOPTER_CLASSIFICATION"]} + """; + return new Evidence( + request, + UUID.randomUUID(), + SocialRuntimeFamilyCatalog.fromStored(json.getBytes(StandardCharsets.UTF_8))); + } + + private static Collector call( + SocialRuntimeFamilyCatalogReadGrpcService service, + ReadSocialRuntimeFamilyCatalogRequest wire, + GrpcPeerIdentity peer) { + var result = new Collector(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run(() -> service.readSocialRuntimeFamilyCatalog(wire, result)); + return result; + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static final class Collector + implements StreamObserver { + private Status.Code error; + private String description; + private ReadSocialRuntimeFamilyCatalogResponse value; + private boolean completed; + + @Override + public void onNext(ReadSocialRuntimeFamilyCatalogResponse next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + assertThat(value).isNull(); + error = Status.fromThrowable(failure).getCode(); + description = Status.fromThrowable(failure).getDescription(); + } + + @Override + public void onCompleted() { + assertThat(value).isNotNull(); + completed = true; + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java new file mode 100644 index 0000000000..38ed5142f9 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldRuntimeFamilyCatalogResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldRuntimeFamilyCatalogReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Manual, unregistered, exact Game Session workload read. Authentication precedes decode and SQL. + */ +public final class WorldRuntimeFamilyCatalogReadGrpcService + extends WorldRuntimeFamilyCatalogReadServiceGrpc.WorldRuntimeFamilyCatalogReadServiceImplBase { + private final WorldRuntimeFamilyCatalogRepository repository; + private final String namespace; + + public WorldRuntimeFamilyCatalogReadGrpcService( + WorldRuntimeFamilyCatalogRepository repository, String namespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Fixed workload namespace required"); + this.namespace = namespace; + } + + @Override + public void readWorldRuntimeFamilyCatalog( + ReadWorldRuntimeFamilyCatalogRequest wire, + StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + refuse(observer, Status.UNAUTHENTICATED, "Authenticated workload required"); + return; + } + if (!peer.isService("game-session-service") + || !peer.isInNamespace(namespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + refuse( + observer, + Status.PERMISSION_DENIED, + "Exact same-namespace Game Session workload required without caller context"); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + refuse(observer, Status.FAILED_PRECONDITION, "Independent World owner operation required"); + return; + } + Request request; + try { + request = WorldRuntimeFamilyCatalogCodec.fromRequest(wire); + } catch (IllegalArgumentException invalid) { + refuse(observer, Status.INVALID_ARGUMENT, "Complete bounded catalog request required"); + return; + } + if (!namespace.equals(request.targetNamespace())) { + refuse( + observer, + Status.PERMISSION_DENIED, + "Request namespace differs from authenticated workload"); + return; + } + ReadWorldRuntimeFamilyCatalogResponse response; + try { + response = WorldRuntimeFamilyCatalogCodec.toResponse(request, repository.read(request)); + } catch (WorldRuntimeFamilyCatalogRepository.CatalogConflictException + | IllegalArgumentException invalid) { + refuse( + observer, + Status.FAILED_PRECONDITION, + "World catalog is changed, unsupported or inconsistent"); + return; + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException failure) { + refuse( + observer, + Status.fromCode(WorldPreparationStorageFailureStatus.from(failure)), + "World catalog storage read failed"); + return; + } catch (org.springframework.transaction.CannotCreateTransactionException unavailable) { + refuse(observer, Status.UNAVAILABLE, "World catalog storage unavailable"); + return; + } catch (RuntimeException failure) { + refuse(observer, Status.INTERNAL, "World catalog read failed"); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static void refuse(StreamObserver observer, Status status, String message) { + observer.onError(status.withDescription(message).asRuntimeException()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogRepository.java new file mode 100644 index 0000000000..ae5166b6de --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogRepository.java @@ -0,0 +1,162 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Evidence; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalogCodec; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Manual owner-local catalog capture and independent exact committed readback; never a manifest. + */ +public final class WorldRuntimeFamilyCatalogRepository { + private final DSLContext dsl; + private final String schema; + private final String namespace; + private final TransactionTemplate capture; + private final TransactionTemplate readback; + + public WorldRuntimeFamilyCatalogRepository( + DSLContext dsl, PlatformTransactionManager transactions, String schema, String namespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (schema == null + || !schema.matches("[a-z][a-z0-9_]{0,62}") + || !GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixed owner schema and workload namespace required"); + } + this.schema = schema; + this.namespace = namespace; + capture = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + capture.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + capture.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + readback = new TransactionTemplate(transactions); + readback.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readback.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readback.setReadOnly(true); + } + + /** + * Each request identity retains one immutable exact as-of snapshot, including response identity. + */ + public Evidence read(Request request) { + requireIndependent(request); + byte[] committed = + capture.execute( + status -> { + WorldRuntimeFamilyCatalog catalog = currentCatalog(); + byte[] requestBytes = WorldRuntimeFamilyCatalogCodec.requestBytes(request); + var proposed = new Evidence(request, UUID.randomUUID(), catalog); + byte[] evidenceBytes = WorldRuntimeFamilyCatalogCodec.evidenceBytes(proposed); + dsl.execute( + "INSERT INTO " + + table("world_runtime_family_catalog_snapshot") + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," + + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" + + " ON CONFLICT (read_request_id) DO NOTHING", + request.readRequestId(), + request.targetNamespace(), + requestBytes, + WorldRuntimeFamilyCatalog.sha256(requestBytes), + proposed.snapshotId(), + catalog.catalogEpoch(), + catalog.digest(), + evidenceBytes, + proposed.digest()); + return retained(request, catalog); + }); + Evidence result = readExact(request); + if (!Arrays.equals(committed, WorldRuntimeFamilyCatalogCodec.evidenceBytes(result))) { + throw new CatalogConflictException("Committed catalog readback changed"); + } + return result; + } + + /** + * Reads an existing exact snapshot only; missing or invalidated evidence is never empty success. + */ + public Evidence readExact(Request request) { + requireIndependent(request); + return readback.execute( + status -> + WorldRuntimeFamilyCatalogCodec.evidenceFromStored(retained(request, currentCatalog()))); + } + + private WorldRuntimeFamilyCatalog currentCatalog() { + Record row = + dsl.fetchOne( + "SELECT catalog_epoch,catalog_bytes,catalog_digest," + + schema + + ".world_runtime_family_catalog_bytes(catalog_epoch) AS current_bytes FROM " + + table("world_runtime_family_catalog_epoch") + + " WHERE " + + schema + + ".world_runtime_family_catalog_installed()" + + " ORDER BY catalog_epoch DESC LIMIT 1"); + if (row == null) throw new CatalogConflictException("No durable World catalog epoch"); + byte[] sealed = row.get("catalog_bytes", byte[].class); + if (!Arrays.equals(sealed, row.get("current_bytes", byte[].class))) { + throw new CatalogConflictException("World schema/classification drift invalidates its epoch"); + } + WorldRuntimeFamilyCatalog catalog = WorldRuntimeFamilyCatalog.fromStored(sealed); + if (catalog.catalogEpoch() != row.get("catalog_epoch", Long.class) + || !catalog.digest().equals(row.get("catalog_digest", String.class))) { + throw new CatalogConflictException("World catalog epoch/digest binding is inconsistent"); + } + return catalog; + } + + private byte[] retained(Request request, WorldRuntimeFamilyCatalog current) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + table("world_runtime_family_catalog_snapshot") + + " WHERE read_request_id=?", + request.readRequestId()); + if (row == null) throw new CatalogConflictException("Exact World catalog snapshot is absent"); + byte[] bytes = row.get("evidence_bytes", byte[].class); + Evidence result = WorldRuntimeFamilyCatalogCodec.evidenceFromStored(bytes); + byte[] requestBytes = WorldRuntimeFamilyCatalogCodec.requestBytes(request); + if (!request.equals(result.request()) + || !request.targetNamespace().equals(row.get("target_namespace", String.class)) + || !Arrays.equals(requestBytes, row.get("request_bytes", byte[].class)) + || !WorldRuntimeFamilyCatalog.sha256(requestBytes) + .equals(row.get("request_digest", String.class)) + || !result.snapshotId().equals(row.get("snapshot_id", UUID.class)) + || result.catalog().catalogEpoch() != row.get("catalog_epoch", Long.class) + || !result.catalog().digest().equals(row.get("catalog_digest", String.class)) + || !result.digest().equals(row.get("evidence_digest", String.class)) + || !Arrays.equals(current.exactBytes(), result.catalog().exactBytes())) { + throw new CatalogConflictException("Changed request or invalidated World catalog snapshot"); + } + return bytes; + } + + private String table(String name) { + return schema + "." + name; + } + + private void requireIndependent(Request request) { + Objects.requireNonNull(request, "request"); + if (!namespace.equals(request.targetNamespace())) + throw new CatalogConflictException("Wrong workload namespace"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Catalog evidence requires independent owner transactions"); + } + } + + public static final class CatalogConflictException extends IllegalStateException { + public CatalogConflictException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql b/services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql new file mode 100644 index 0000000000..330567e2b7 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql @@ -0,0 +1,274 @@ +-- Additive source only: never reads or changes gameplay payload rows or lifecycle authority. +CREATE TABLE world_runtime_family_classification ( + family_id VARCHAR(127) PRIMARY KEY, + relation_name VARCHAR(63) NOT NULL, + component_name VARCHAR(63) NOT NULL DEFAULT '', + family_role VARCHAR(32) NOT NULL CHECK (family_role IN + ('RUNTIME_PAYLOAD','LIFECYCLE','SOURCE','CONTROL','AUDIT','PROVENANCE','EXCLUDED','CATALOG')), + state_class VARCHAR(16) NOT NULL CHECK (state_class IN ('S3','NOT_PAYLOAD')), + fresh_disposition VARCHAR(48) NOT NULL CHECK (fresh_disposition IN + ('REQUIRED_TOPOLOGY','REQUIRED_LIFECYCLE','NOT_INITIALIZED_ACTOR_LOCATION', + 'UNSUPPORTED_WEATHER','OWNER_EVENT_PROOF_REQUIRED','LEGACY_EXCLUDED', + 'SOURCE_ONLY','CONTROL_ONLY','AUDIT_ONLY','PROVENANCE_ONLY','CATALOG_ONLY')), + UNIQUE (relation_name, component_name), + CHECK (relation_name ~ '^[a-z][a-z0-9_]{0,62}$'), + CHECK (component_name = '' OR component_name ~ '^[a-z][a-z0-9_]{0,62}$'), + CHECK (family_id = relation_name || CASE WHEN component_name = '' THEN '' ELSE '.' || component_name END), + CHECK ((family_role IN ('RUNTIME_PAYLOAD','LIFECYCLE','EXCLUDED')) = (state_class = 'S3')), + CHECK (family_role = CASE fresh_disposition + WHEN 'REQUIRED_TOPOLOGY' THEN 'RUNTIME_PAYLOAD' + WHEN 'NOT_INITIALIZED_ACTOR_LOCATION' THEN 'RUNTIME_PAYLOAD' + WHEN 'UNSUPPORTED_WEATHER' THEN 'RUNTIME_PAYLOAD' + WHEN 'OWNER_EVENT_PROOF_REQUIRED' THEN 'RUNTIME_PAYLOAD' + WHEN 'REQUIRED_LIFECYCLE' THEN 'LIFECYCLE' + WHEN 'LEGACY_EXCLUDED' THEN 'EXCLUDED' + WHEN 'SOURCE_ONLY' THEN 'SOURCE' WHEN 'CONTROL_ONLY' THEN 'CONTROL' + WHEN 'AUDIT_ONLY' THEN 'AUDIT' WHEN 'PROVENANCE_ONLY' THEN 'PROVENANCE' + WHEN 'CATALOG_ONLY' THEN 'CATALOG' END) +); + +CREATE TABLE world_runtime_family_catalog_epoch ( + catalog_epoch BIGINT PRIMARY KEY CHECK (catalog_epoch > 0), + catalog_bytes BYTEA NOT NULL CHECK (octet_length(catalog_bytes) BETWEEN 1 AND 2097152), + catalog_digest VARCHAR(71) NOT NULL CHECK (catalog_digest = 'sha256:' || encode(sha256(catalog_bytes), 'hex')), + installed_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE world_runtime_family_catalog_snapshot ( + read_request_id UUID PRIMARY KEY CHECK (read_request_id <> '00000000-0000-0000-0000-000000000000'), + target_namespace VARCHAR(63) NOT NULL CHECK (target_namespace ~ '^[a-z0-9]([-a-z0-9]*[a-z0-9])?$'), + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) BETWEEN 1 AND 1024), + request_digest VARCHAR(71) NOT NULL CHECK (request_digest = 'sha256:' || encode(sha256(request_bytes), 'hex')), + snapshot_id UUID NOT NULL UNIQUE CHECK (snapshot_id <> '00000000-0000-0000-0000-000000000000'), + catalog_epoch BIGINT NOT NULL REFERENCES world_runtime_family_catalog_epoch(catalog_epoch), + catalog_digest VARCHAR(71) NOT NULL, + evidence_bytes BYTEA NOT NULL CHECK (octet_length(evidence_bytes) BETWEEN 1 AND 2101248), + evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest = 'sha256:' || encode(sha256(evidence_bytes), 'hex')), + retained_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +-- Explicit current owner metadata, not a name-prefix or absent-row inference. Future tables +-- have no default disposition. Source/control/provenance records are never clone payload. +INSERT INTO world_runtime_family_classification + (family_id, relation_name, component_name, family_role, state_class, fresh_disposition) +VALUES + ('world_instance','world_instance','','LIFECYCLE','S3','REQUIRED_LIFECYCLE'), + ('region_instance','region_instance','','RUNTIME_PAYLOAD','S3','REQUIRED_TOPOLOGY'), + ('zone_instance','zone_instance','','RUNTIME_PAYLOAD','S3','REQUIRED_TOPOLOGY'), + ('room_instance','room_instance','','RUNTIME_PAYLOAD','S3','REQUIRED_TOPOLOGY'), + ('room_instance_exit','room_instance_exit','','RUNTIME_PAYLOAD','S3','REQUIRED_TOPOLOGY'), + ('region_instance.weather','region_instance','weather','RUNTIME_PAYLOAD','S3','UNSUPPORTED_WEATHER'), + ('world_event','world_event','','RUNTIME_PAYLOAD','S3','OWNER_EVENT_PROOF_REQUIRED'), + ('character_location','character_location','','RUNTIME_PAYLOAD','S3','NOT_INITIALIZED_ACTOR_LOCATION'), + ('instance','instance','','EXCLUDED','S3','LEGACY_EXCLUDED'); + +INSERT INTO world_runtime_family_classification + (family_id, relation_name, family_role, state_class, fresh_disposition) +SELECT name, name, 'SOURCE', 'NOT_PAYLOAD', 'SOURCE_ONLY' FROM (VALUES + ('region'),('zone'),('room'),('room_exit'),('generation_rule'),('world_entity_spawn_binding'), + ('world_authored_graph_snapshot'),('world_authored_source_intake'), + ('world_authored_topology_identity'),('world_authored_version_identity'), + ('world_canonical_frozen_topology'),('world_complete_launch_binding'), + ('world_draft_start_location_receipt'),('world_selected_publication_artifact_inventory') +) AS source(name); + +INSERT INTO world_runtime_family_classification + (family_id, relation_name, family_role, state_class, fresh_disposition) +SELECT name, name, 'CONTROL', 'NOT_PAYLOAD', 'CONTROL_ONLY' FROM (VALUES + ('initial_admission_bind_hold'),('world_authored_source_tenant_association'), + ('world_authored_source_tenant_key_reservation'),('world_canonical_activation_execution_manifest'), + ('world_canonical_initial_admission_hold_finalization_manifest'), + ('world_canonical_instance_activation_fence'),('world_canonical_instance_activation_operation'), + ('world_canonical_instance_preparation_execution_manifest'),('world_canonical_player_admission_hold'), + ('world_design_aggregate_epoch'),('world_design_scope_epoch'), + ('world_design_publication_account_binding'),('world_design_publication_fence_attempt'), + ('world_design_publication_fence_owner'),('world_region_draft_execution_manifest'), + ('saga_instance'),('saga_step') +) AS control(name); + +INSERT INTO world_runtime_family_classification + (family_id, relation_name, family_role, state_class, fresh_disposition) +SELECT name, name, 'AUDIT', 'NOT_PAYLOAD', 'AUDIT_ONLY' FROM (VALUES + ('world_design_revision_ledger'),('world_design_publication_terminal'), + ('world_draft_graph_application'),('world_draft_graph_terminal_identity'), + ('world_draft_terminal_outcome'),('world_region_draft_commit'),('world_topology_draft_commit') +) AS audit(name); + +INSERT INTO world_runtime_family_classification + (family_id, relation_name, family_role, state_class, fresh_disposition) +SELECT name, name, 'PROVENANCE', 'NOT_PAYLOAD', 'PROVENANCE_ONLY' FROM (VALUES + ('world_canonical_initial_player_location_operation'),('world_canonical_instance_association'), + ('world_canonical_instance_execution'),('world_canonical_instance_preparation'), + ('world_canonical_instance_topology_identity'),('world_canonical_preparation_start_location') +) AS provenance(name); + +INSERT INTO world_runtime_family_classification + (family_id, relation_name, family_role, state_class, fresh_disposition) +SELECT name, name, 'CATALOG', 'NOT_PAYLOAD', 'CATALOG_ONLY' FROM (VALUES + ('world_runtime_family_classification'),('world_runtime_family_catalog_epoch'), + ('world_runtime_family_catalog_snapshot') +) AS catalog(name); + +-- The parser-independent seal is generated from live pg_catalog and installed migration facts. +-- Definition hashes omit row data, sequence positions, OIDs, statistics and installation times. +-- This migration's own Flyway row is written AFTER this transaction. Its stable installation +-- marker is included instead; all prior and subsequent migration rows bind script/checksum/success. +-- [jooq ignore start] +-- Flyway supplies the actual configured history identifier; never assume a deployment schema. +INSERT INTO world_runtime_family_classification + (family_id, relation_name, family_role, state_class, fresh_disposition) +VALUES ('${flyway:table}', '${flyway:table}', 'CONTROL', 'NOT_PAYLOAD', 'CONTROL_ONLY'); + +CREATE FUNCTION world_runtime_family_catalog_installed() RETURNS BOOLEAN +LANGUAGE SQL STABLE +SET search_path = "${serviceSchema}", pg_catalog +AS $$ + SELECT EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1046' AND script='V1046__world_owner_runtime_family_catalog.sql' AND success); +$$; + +CREATE FUNCTION world_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE +SET search_path = "${serviceSchema}", pg_catalog +AS $$ +DECLARE + v_families JSONB; + v_facts JSONB; +BEGIN + IF p_epoch IS NULL OR p_epoch <= 0 THEN + RAISE EXCEPTION 'Positive World catalog epoch required' USING ERRCODE = '23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM world_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM world_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed World schema family' USING ERRCODE = '23514'; + END IF; + + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name, + 'component',component_name,'role',family_role,'stateClass',state_class, + 'freshDisposition',fresh_disposition) ORDER BY family_id COLLATE "C") + INTO v_families FROM world_runtime_family_classification; + + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname, + jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,pg_get_viewdef(c.oid,true) FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1046' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1046','V1046__world_owner_runtime_family_catalog.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + + IF jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 THEN + RAISE EXCEPTION 'Complete World catalog exceeds source bounds' USING ERRCODE = '23514'; + END IF; + RETURN convert_to(jsonb_build_object('schema','world-runtime-family-catalog/v1', + 'owner','world-management-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts)::TEXT,'UTF8'); +END; +$$; + +CREATE FUNCTION world_runtime_catalog_immutable() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'World runtime catalog evidence is immutable' USING ERRCODE='23514'; +END; +$$; + +CREATE TRIGGER world_runtime_classification_retained BEFORE UPDATE OR DELETE OR TRUNCATE +ON world_runtime_family_classification FOR EACH STATEMENT EXECUTE FUNCTION world_runtime_catalog_immutable(); +CREATE TRIGGER world_runtime_epoch_retained BEFORE UPDATE OR DELETE OR TRUNCATE +ON world_runtime_family_catalog_epoch FOR EACH STATEMENT EXECUTE FUNCTION world_runtime_catalog_immutable(); +CREATE TRIGGER world_runtime_snapshot_retained BEFORE UPDATE OR DELETE OR TRUNCATE +ON world_runtime_family_catalog_snapshot FOR EACH STATEMENT EXECUTE FUNCTION world_runtime_catalog_immutable(); + +CREATE FUNCTION world_runtime_catalog_epoch_guard() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = "${serviceSchema}", pg_catalog AS $$ +BEGIN + IF NEW.catalog_epoch<>coalesce((SELECT max(catalog_epoch) FROM world_runtime_family_catalog_epoch),0)+1 + OR NEW.catalog_bytes<>world_runtime_family_catalog_bytes(NEW.catalog_epoch) THEN + RAISE EXCEPTION 'World epoch must bind the exact classified installed schema' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER world_runtime_epoch_exact BEFORE INSERT ON world_runtime_family_catalog_epoch +FOR EACH ROW EXECUTE FUNCTION world_runtime_catalog_epoch_guard(); + +CREATE FUNCTION world_runtime_catalog_snapshot_guard() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE v_epoch world_runtime_family_catalog_epoch%ROWTYPE; +BEGIN + SELECT * INTO STRICT v_epoch FROM world_runtime_family_catalog_epoch ORDER BY catalog_epoch DESC LIMIT 1; + IF NEW.catalog_epoch<>v_epoch.catalog_epoch OR NEW.catalog_digest<>v_epoch.catalog_digest + OR world_runtime_family_catalog_bytes(v_epoch.catalog_epoch)<>v_epoch.catalog_bytes THEN + RAISE EXCEPTION 'World runtime catalog changed; new owner epoch required' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER world_runtime_snapshot_current BEFORE INSERT ON world_runtime_family_catalog_snapshot +FOR EACH ROW EXECUTE FUNCTION world_runtime_catalog_snapshot_guard(); +-- [jooq ignore stop] + +-- PostgreSQL-only bootstrap invokes the pg_catalog census function above; H2 cannot simulate it. +-- [jooq ignore start] +INSERT INTO world_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT 1,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM (SELECT world_runtime_family_catalog_bytes(1) AS bytes) seal; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java new file mode 100644 index 0000000000..89966f1b2f --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -0,0 +1,496 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.migration; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.FactKind; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.FreshDisposition; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldRuntimeFamilyCatalogResponse; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual installed World/Saga PostgreSQL source proof. SQL fixtures control legacy identity and the + * RPC identity context; these cases do not prove live PKI, FRESH authorization or materialization. + * No positive case is disabled when Docker is unavailable: Gameplay must obtain physical results. + */ +@Testcontainers +@SuppressWarnings("resource") +class WorldRuntimeFamilyCatalogPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void configuredFlywayHistoryNameBindsTheActualInstallationAndReadback() throws Exception { + for (String history : + List.of("flyway_schema_history_public", "flyway_schema_history_custom_world")) { + try (Fixture f = fixture(null, history)) { + var original = f.owner().read(request()); + assertThat(original.catalog().families()) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo(history); + assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.CONTROL_ONLY); + }); + assertThat(f.owner().readExact(original.request())).isEqualTo(original); + assertThat( + f.dsl + .fetchSingle( + "SELECT to_regclass(?) IS NULL", + f.schema + ".flyway_schema_history_world_management_service") + .get(0, Boolean.class)) + .isTrue(); + } + } + } + + @Test + void actualCompleteCurrentCensusIncludesEmptyRuntimeAndNonPayloadFamilies() throws Exception { + try (Fixture f = fixture(null)) { + var evidence = f.owner().read(request()); + var catalog = evidence.catalog(); + assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat( + catalog.schemaFacts().stream() + .filter(fact -> fact.kind() == FactKind.TABLE) + .map(WorldRuntimeFamilyCatalog.SchemaFact::identity) + .toList()) + .containsExactlyInAnyOrderElementsOf( + f.dsl + .fetch( + "SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace" + + " WHERE n.nspname=? AND c.relkind IN ('r','p','f')", + f.schema) + .getValues(0, String.class)); + assertThat(catalog.families().stream().filter(family -> family.component().isEmpty()).count()) + .isEqualTo( + catalog.schemaFacts().stream().filter(fact -> fact.kind() == FactKind.TABLE).count()); + assertThat(catalog.families()) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo("region_instance.weather"); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.UNSUPPORTED_WEATHER); + }) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo("instance"); + assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.LEGACY_EXCLUDED); + }) + .anySatisfy( + family -> { + assertThat(family.familyId()).isEqualTo("character_location"); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.NOT_INITIALIZED_ACTOR_LOCATION); + }) + .anySatisfy( + family -> { + assertThat(family.familyId()) + .isEqualTo("world_canonical_initial_player_location_operation"); + assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.PROVENANCE_ONLY); + }); + assertThat(f.count("region_instance")).isZero(); + assertThat(f.count("character_location")).isZero(); + assertThat(f.count("world_event")).isZero(); + assertThat(catalog.families()) + .noneMatch( + family -> + family.familyId().equals("npc_location") + || family.familyId().equals("population_schedule_instance") + || family.familyId().equals("generation_run")); + assertThat(catalog.schemaFacts()) + .anyMatch(fact -> fact.kind() == FactKind.MIGRATION) + .anyMatch(fact -> fact.kind() == FactKind.ROUTINE) + .anyMatch(fact -> fact.kind() == FactKind.COLUMN); + assertThat( + f.dsl + .fetchSingle( + "SELECT catalog_bytes = world_runtime_family_catalog_bytes(catalog_epoch)" + + " FROM world_runtime_family_catalog_epoch") + .get(0, Boolean.class)) + .isTrue(); + } + } + + @Test + void exactReplayRestartAndIndependentReadbackRetainBytesDigestsAndSnapshotIdentity() + throws Exception { + try (Fixture f = fixture(null)) { + Request read = request(); + var original = f.owner().read(read); + assertThat(f.owner().read(read)).isEqualTo(original); + assertThat(f.owner().readExact(read)).isEqualTo(original); + assertThat(f.count("world_runtime_family_catalog_snapshot")).isEqualTo(1); + var freshRead = f.owner().read(request()); + assertThat(freshRead.snapshotId()).isNotEqualTo(original.snapshotId()); + assertThat(freshRead.catalog().exactBytes()).isEqualTo(original.catalog().exactBytes()); + assertThat(freshRead.catalog().digest()).isEqualTo(original.catalog().digest()); + var otherNamespaceOwner = + new WorldRuntimeFamilyCatalogRepository(f.dsl, f.manager, f.schema, "other"); + assertThatThrownBy(() -> otherNamespaceOwner.read(new Request(read.readRequestId(), "other"))) + .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.count("world_runtime_family_catalog_snapshot")).isEqualTo(2); + assertThatThrownBy(() -> f.owner().readExact(request())) + .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); + } + } + + @Test + void concurrentExactRetriesConvergeOnOneRetainedSnapshot() throws Exception { + try (Fixture f = fixture(null); + var workers = Executors.newFixedThreadPool(2)) { + Request read = request(); + var first = workers.submit(() -> f.owner().read(read)); + var second = workers.submit(() -> f.owner().read(read)); + assertThat(first.get(30, TimeUnit.SECONDS)).isEqualTo(second.get(30, TimeUnit.SECONDS)); + assertThat(f.count("world_runtime_family_catalog_snapshot")).isEqualTo(1); + } + } + + @Test + void additiveForwardMigrationRetainsLegacyPayloadAndPriorMigrationHistoryExactly() + throws Exception { + try (Fixture f = fixture("1045")) { + f.dsl.execute( + "INSERT INTO world_authored_source_tenant_key_reservation(tenant_key,claim_kind) VALUES(7001,'LEGACY_NUMERIC')"); + long region = + f.dsl + .fetchSingle( + "INSERT INTO region(name,tenant_id,version_id) VALUES ('retained',7001,1) RETURNING id") + .get(0, Long.class); + long zone = + f.dsl + .fetchSingle( + "INSERT INTO zone(region_id,name,tenant_id,version_id) VALUES (?,'retained',7001,1) RETURNING id", + region) + .get(0, Long.class); + f.dsl.execute( + "INSERT INTO instance(zone_id,tenant_id,owner_account_id) VALUES (?,7001,89)", zone); + String regionBefore = f.jsonRows("region"); + String zoneBefore = f.jsonRows("zone"); + String instanceBefore = f.jsonRows("instance"); + List historyBefore = + f.dsl + .fetch( + "SELECT to_jsonb(h)::text FROM flyway_schema_history_world_management_service h ORDER BY installed_rank") + .getValues(0, String.class); + migration(f.source, f.schema, null).migrate(); + assertThat(f.jsonRows("region")).isEqualTo(regionBefore); + assertThat(f.jsonRows("zone")).isEqualTo(zoneBefore); + assertThat(f.jsonRows("instance")).isEqualTo(instanceBefore); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(h)::text FROM flyway_schema_history_world_management_service h WHERE version IS DISTINCT FROM '1046' ORDER BY installed_rank") + .getValues(0, String.class)) + .isEqualTo(historyBefore); + f.owner().read(request()); + assertThat(f.jsonRows("region")).isEqualTo(regionBefore); + assertThat(f.count("world_instance")).isZero(); + assertThat(f.count("world_canonical_instance_preparation")).isZero(); + assertThat(f.count("world_canonical_instance_association")).isZero(); + migration(f.source, f.schema, null).validate(); + } + } + + @Test + void emptyUnclassifiedNewTableInvalidatesOldSnapshotAndRefusesNewSampling() throws Exception { + try (Fixture f = fixture(null)) { + Request read = request(); + f.owner().read(read); + f.dsl.execute("CREATE TABLE unknown_runtime_family (id BIGINT PRIMARY KEY)"); + assertThat(f.count("unknown_runtime_family")).isZero(); + assertThatThrownBy(() -> f.owner().readExact(read)).hasMessageContaining("Unclassified"); + assertThatThrownBy(() -> f.owner().read(request())).hasMessageContaining("Unclassified"); + assertThat(f.count("world_runtime_family_catalog_snapshot")).isEqualTo(1); + } + } + + @Test + void forwardInstallationRefusesAnAlreadyPresentUnclassifiedFamilyAtomically() throws Exception { + try (Fixture f = fixture("1045")) { + f.dsl.execute("CREATE TABLE unknown_runtime_family (id BIGINT PRIMARY KEY)"); + List history = + f.dsl + .fetch( + "SELECT to_jsonb(h)::text FROM flyway_schema_history_world_management_service h ORDER BY installed_rank") + .getValues(0, String.class); + assertThatThrownBy(() -> migration(f.source, f.schema, null).migrate()) + .hasMessageContaining("Unclassified or changed"); + assertThat( + f.dsl + .fetchSingle( + "SELECT to_regclass(?) IS NULL", + f.schema + ".world_runtime_family_catalog_epoch") + .get(0, Boolean.class)) + .isTrue(); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(h)::text FROM flyway_schema_history_world_management_service h ORDER BY installed_rank") + .getValues(0, String.class)) + .isEqualTo(history); + assertThat(f.count("unknown_runtime_family")).isZero(); + } + } + + @Test + void schemaColumnRenameConstraintAndRoutineChangesCannotResampleUnderSameEpoch() + throws Exception { + for (String change : + List.of( + "ALTER TABLE world_event ADD COLUMN future_state TEXT", + "ALTER TABLE world_event RENAME COLUMN processed TO processed_later", + "ALTER TABLE world_event ADD CONSTRAINT catalog_probe CHECK (id>0)", + "ALTER TABLE world_event RENAME TO renamed_world_event", + "CREATE FUNCTION future_runtime_writer() RETURNS INTEGER LANGUAGE SQL AS 'SELECT 1'")) { + try (Fixture f = fixture(null)) { + Request read = request(); + f.owner().read(read); + f.dsl.execute(change); + assertThatThrownBy(() -> f.owner().readExact(read)).isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> f.owner().read(request())).isInstanceOf(RuntimeException.class); + assertThat(f.count("world_runtime_family_catalog_snapshot")).isEqualTo(1); + } + } + } + + @Test + void removalAndClassificationChangeAreExplicitlyInvalidating() throws Exception { + try (Fixture f = fixture(null)) { + Request read = request(); + f.owner().read(read); + f.dsl.execute("DROP TABLE world_event"); + assertThatThrownBy(() -> f.owner().readExact(read)) + .hasMessageContaining("Unclassified or changed"); + } + try (Fixture f = fixture(null)) { + Request read = request(); + f.owner().read(read); + // Add a declared component without removing metadata guards: changed classification must + // invalidate the existing epoch even though its table/column really exists and is empty. + f.dsl.execute( + "INSERT INTO world_runtime_family_classification VALUES" + + " ('region_instance.name','region_instance','name','RUNTIME_PAYLOAD','S3','REQUIRED_TOPOLOGY')"); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(request())) + .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(1); + } + } + + @Test + void oldMigrationFactChangeInvalidatesTheSealAndMissingOwnerEpochNeverMeansComplete() + throws Exception { + try (Fixture f = fixture(null)) { + Request read = request(); + f.owner().read(read); + f.dsl.execute( + "UPDATE flyway_schema_history_world_management_service SET checksum=checksum+1 WHERE version='1'"); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); + } + try (Fixture f = fixture(null)) { + f.dsl.execute( + "UPDATE flyway_schema_history_world_management_service SET success=false WHERE version='1046'"); + assertThatThrownBy(() -> f.owner().read(request())) + .hasMessageContaining("No durable World catalog epoch"); + assertThat(f.count("world_runtime_family_catalog_snapshot")).isZero(); + } + } + + @Test + void explicitOwnerEpochAdvanceInvalidatesOldRequestsWithoutRewritingTheirEvidence() + throws Exception { + try (Fixture f = fixture(null)) { + Request read = request(); + var original = f.owner().read(read); + // Controlled owner-local revision installation, not a runtime catalog mutation API. + f.dsl.execute( + "INSERT INTO world_runtime_family_classification VALUES" + + " ('region_instance.name','region_instance','name','RUNTIME_PAYLOAD','S3','REQUIRED_TOPOLOGY')"); + f.dsl.execute( + "INSERT INTO world_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" + + " SELECT 2,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM" + + " (SELECT world_runtime_family_catalog_bytes(2) AS bytes) revised"); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(read)) + .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat( + f.dsl + .fetchSingle( + "SELECT evidence_bytes FROM world_runtime_family_catalog_snapshot WHERE read_request_id=?", + read.readRequestId()) + .get(0, byte[].class)) + .isEqualTo(WorldRuntimeFamilyCatalogCodec.evidenceBytes(original)); + var revised = f.owner().read(request()); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(2); + assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); + assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(2); + } + } + + @Test + void epochMetadataAndSnapshotsAreRetainedAndWrongSealsCannotBeInserted() throws Exception { + try (Fixture f = fixture(null)) { + f.owner().read(request()); + for (String table : + List.of( + "world_runtime_family_catalog_epoch", + "world_runtime_family_classification", + "world_runtime_family_catalog_snapshot")) { + assertThatThrownBy(() -> f.dsl.execute("DELETE FROM " + table)) + .hasMessageContaining("immutable"); + assertThatThrownBy(() -> f.dsl.execute("TRUNCATE " + table + " CASCADE")) + .hasMessageContaining("immutable"); + } + assertThatThrownBy( + () -> f.dsl.execute("UPDATE world_runtime_family_catalog_epoch SET catalog_epoch=2")) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE world_runtime_family_classification SET fresh_disposition='LEGACY_EXCLUDED' WHERE family_id='instance'")) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO world_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" + + " SELECT 2,catalog_bytes,catalog_digest FROM world_runtime_family_catalog_epoch WHERE catalog_epoch=1")) + .hasMessageContaining("exact classified installed schema"); + } + } + + @Test + void actualProducerReturnsCompleteCorrelatedEvidenceWithoutMaterializingRuntime() + throws Exception { + try (Fixture f = fixture(null)) { + Request read = request(); + var service = new WorldRuntimeFamilyCatalogReadGrpcService(f.owner(), "test"); + var collector = new Collector(); + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") + .orElseThrow(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> + service.readWorldRuntimeFamilyCatalog( + WorldRuntimeFamilyCatalogCodec.toRequest(read), collector)); + assertThat(collector.error).isNull(); + assertThat(collector.completed).isTrue(); + var evidence = WorldRuntimeFamilyCatalogCodec.fromResponse(read, collector.value); + assertThat(f.owner().readExact(read)).isEqualTo(evidence); + assertThat(f.count("world_instance")).isZero(); + assertThat(f.count("character_location")).isZero(); + var transaction = new TransactionTemplate(f.manager); + assertThatThrownBy(() -> transaction.execute(status -> f.owner().read(request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent"); + } + } + + private static Request request() { + return new Request(UUID.randomUUID(), "test"); + } + + private static Fixture fixture(String target) { + return fixture(target, "flyway_schema_history_world_management_service"); + } + + private static Fixture fixture(String target, String history) { + String schema = "world_catalog_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + try { + Flyway.configure() + .configuration(migration(source, schema, target).getConfiguration()) + .table(history) + .load() + .migrate(); + return new Fixture(schema, source, dsl, new DataSourceTransactionManager(source)); + } catch (RuntimeException failed) { + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + throw failed; + } + } + + private record Fixture( + String schema, + DriverManagerDataSource source, + DSLContext dsl, + DataSourceTransactionManager manager) + implements AutoCloseable { + WorldRuntimeFamilyCatalogRepository owner() { + return new WorldRuntimeFamilyCatalogRepository(dsl, manager, schema, "test"); + } + + long count(String table) { + return dsl.fetchSingle("SELECT count(*) FROM " + table).get(0, Long.class); + } + + String jsonRows(String table) { + return dsl.fetchSingle( + "SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY id),'[]'::jsonb)::text FROM " + + table + + " t") + .get(0, String.class); + } + + @Override + public void close() { + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + private static final class Collector + implements StreamObserver { + private ReadWorldRuntimeFamilyCatalogResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadWorldRuntimeFamilyCatalogResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcServiceTest.java new file mode 100644 index 0000000000..debf955834 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcServiceTest.java @@ -0,0 +1,186 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalogCodec; +import net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeFamilyCatalogReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeFamilyCatalogRepository; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldRuntimeFamilyCatalogRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldRuntimeFamilyCatalogResponse; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Identity context is controlled here; physical certificate qualification is a separate fixture. + */ +class WorldRuntimeFamilyCatalogReadGrpcServiceTest { + @Test + void workloadRefusalPrecedesMalformedDecodeAndAllSql() { + var repository = mock(WorldRuntimeFamilyCatalogRepository.class); + var service = new WorldRuntimeFamilyCatalogReadGrpcService(repository, "test"); + var malformed = + ReadWorldRuntimeFamilyCatalogRequest.newBuilder() + .addCanonicalRequestBytes(ByteString.copyFromUtf8("bad frame")) + .build(); + assertThat(call(service, malformed, null).error).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(call(service, malformed, peer("account-service", "test")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(call(service, malformed, peer("game-session-service", "other")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext(UUID.randomUUID().toString(), List.of(), Map.of()); + try { + assertThat(call(service, malformed, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-session-service", "controlled"); + try { + assertThat(call(service, malformed, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(repository); + } + + @Test + void ambientSqlAndSynchronizationRefuseBeforeDecode() { + var repository = mock(WorldRuntimeFamilyCatalogRepository.class); + var service = new WorldRuntimeFamilyCatalogReadGrpcService(repository, "test"); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThat( + call( + service, + ReadWorldRuntimeFamilyCatalogRequest.getDefaultInstance(), + peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThat( + call( + service, + ReadWorldRuntimeFamilyCatalogRequest.getDefaultInstance(), + peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(repository); + } + + @Test + void authenticatedWrongNamespaceMalformedAndOversizedRequestsRefuseBeforeSql() { + var repository = mock(WorldRuntimeFamilyCatalogRepository.class); + var service = new WorldRuntimeFamilyCatalogReadGrpcService(repository, "test"); + var peer = peer("game-session-service", "test"); + assertThat(call(service, ReadWorldRuntimeFamilyCatalogRequest.getDefaultInstance(), peer).error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + call( + service, + WorldRuntimeFamilyCatalogCodec.toRequest( + new Request(UUID.randomUUID(), "other")), + peer) + .error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + call( + service, + ReadWorldRuntimeFamilyCatalogRequest.newBuilder() + .addCanonicalRequestBytes(ByteString.copyFrom(new byte[1025])) + .build(), + peer) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void exactAuthenticatedRequestReachesOwnerAndDriftOrOutageNeverBecomesEmptySuccess() { + var repository = mock(WorldRuntimeFamilyCatalogRepository.class); + var service = new WorldRuntimeFamilyCatalogReadGrpcService(repository, "test"); + var read = new Request(UUID.randomUUID(), "test"); + var wire = WorldRuntimeFamilyCatalogCodec.toRequest(read); + when(repository.read(read)) + .thenThrow( + new WorldRuntimeFamilyCatalogRepository.CatalogConflictException("private details")); + Collector drift = call(service, wire, peer("game-session-service", "test")); + assertThat(drift.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(drift.value).isNull(); + assertThat(drift.description).doesNotContain("private details"); + verify(repository).read(read); + doThrow( + new org.jooq.exception.DataAccessException( + "private SQL", new SQLException("private SQL", "08006"))) + .when(repository) + .read(read); + Collector outage = call(service, wire, peer("game-session-service", "test")); + assertThat(outage.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(outage.value).isNull(); + assertThat(outage.description).doesNotContain("private SQL"); + } + + private static Collector call( + WorldRuntimeFamilyCatalogReadGrpcService service, + ReadWorldRuntimeFamilyCatalogRequest request, + GrpcPeerIdentity peer) { + var result = new Collector(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run(() -> service.readWorldRuntimeFamilyCatalog(request, result)); + return result; + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static final class Collector + implements StreamObserver { + private Status.Code error; + private String description; + private ReadWorldRuntimeFamilyCatalogResponse value; + + @Override + public void onNext(ReadWorldRuntimeFamilyCatalogResponse next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + assertThat(value).isNull(); + error = Status.fromThrowable(failure).getCode(); + description = Status.fromThrowable(failure).getDescription(); + } + + @Override + public void onCompleted() { + assertThat(value).isNotNull(); + } + } +} From 3f72a18036abbe7442172978dcf544110d6e8e85 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:02:26 +1300 Subject: [PATCH 02/11] test: align complete foreign-owner migration fixture dependencies --- .../realm-routing-and-playable-state.md | 2 +- ...rUuidEntityCompositionIntegrationTest.java | 8 +++++- ...ldSourceCommitPostgresIntegrationTest.java | 26 ++++++++++++------- ...ameLogicIntakePostgresIntegrationTest.java | 7 ++++- ...nerPublicationPostgresIntegrationTest.java | 2 +- ...ationOwnerCompositionCrossServiceTest.java | 2 +- ...uthoredVersionIdentityIntegrationTest.java | 2 +- ...dCompleteLaunchBindingIntegrationTest.java | 2 +- 8 files changed, 35 insertions(+), 16 deletions(-) diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 9586e92b54..b028b8b64e 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -27,7 +27,7 @@ Current-selection CAS is implemented by [`GameSessionCurrentPrivatePlaytestRepos The private FRESH prerequisite batch now has a concrete World-local catalog producer and Game Session consumer in working source: forward [V1046](../../../services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql), [World persistence/readback owner](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogRepository.java), [authenticated World read](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java), [shared exact value](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java), [closed codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java) and [Game Session client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClient.java). The normative census/classification/retention detail stays with [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#owner-local-runtime-family-catalog), and wire/authentication/bounds with [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). This is an actual database-derived World schema/family source and durable epoch/snapshot prerequisite, not a static expected-table list, global runtime registry, complete owner-epoch set or FRESH manifest. -Receiving proof243/244 passes six World [value/codec cases](../../../services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogTest.java), four [workload-guard cases](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcServiceTest.java), thirteen [actual PostgreSQL cases](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java) and four [physical client mTLS cases](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClientMtlsTest.java), with zero failures, errors or skips. The four-owner receiving batch totals 107 focused cases; proof245 separately passes 129 affected existing Entity/Automation migration-fixture cases and selected owner/Common main-unit-integration static analysis, formatting and documentation checks. Owning generation passes242/243. Earlier retained proof238 reproduces the configured-history refusal corrected before239; it is not a passing aggregate. Proof243 retains its missing Social client-import compilation failure;244 runs the corrected eighteen client cases and reuses unchanged passing codec/guard/SQL results. Exact XML and logs retain those scopes. Game Session main SpotBugs remains unqualified under the separate JVM investigation. PostgreSQL identity/legacy inputs and guard peer contexts are controlled; mTLS uses local test PKI and catalog responses rather than a live database producer. No coupled database-plus-mTLS owner chain, fresh-image/runtime or whole-FRESH proof is claimed. +Receiving proof243/244 passes six World [value/codec cases](../../../services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogTest.java), four [workload-guard cases](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcServiceTest.java), thirteen [actual PostgreSQL cases](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java) and four [physical client mTLS cases](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClientMtlsTest.java), with zero failures, errors or skips. The four-owner receiving batch totals 107 focused cases; proof245 separately passes 129 affected existing Entity/Automation migration-fixture cases and selected owner/Common main-unit-integration static analysis, formatting and documentation checks. Owning generation passes242/243. Earlier retained proof238 reproduces the configured-history refusal corrected before239; it is not a passing aggregate. Proof243 retains its missing Social client-import compilation failure;244 runs the corrected eighteen client cases and reuses unchanged passing codec/guard/SQL results. Exact XML and logs retain those scopes. The complete foreign-catalog fixture dependency pass aligns seven additional sites without changing historical targets or assertions. Proof262 passes the actual Entity/World cross-owner case after the Entity setup discovers Saga;263 passes twenty-four cases across the affected Account, World and Game Design suites, plus selected analysis/formatting/docs (3m25). Account’s V1023 predecessor discovers Saga before its later Entity upgrade; World targets25/26 remain unchanged. These controlled source compositions do not establish genuine private initialization. Game Session main SpotBugs remains unqualified under the separate JVM investigation. PostgreSQL identity/legacy inputs and guard peer contexts are controlled; mTLS uses local test PKI and catalog responses rather than a live database producer. No coupled database-plus-mTLS owner chain, fresh-image/runtime or whole-FRESH proof is claimed. Remaining batch obligations are the genuine World-owned global enrollment/required-owner-set source, remaining actual owner catalogs/epochs, complete build/lifecycle/namespace/generation-bound FRESH manifest production and immutable authenticated readback, genuine protected private authorization/runtime/materialization, and complete-set aggregation into the existing canonical CLOSED pointer/audit/outcome owner. Current World canonical materialization is still public `SHARED` and original-`StartSession`-only; no private FRESH relabelling is valid. The existing unregistered [canonical CLOSED owner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java) supplies public initial CLOSED persistence, not the missing private aggregate; the registered legacy routing model described elsewhere remains narrower. No second private pointer authority is added. CLOSED-to-OPEN, private first admission, issuer/custody/PKI qualification, runtime/default registration, operational activation, reset and Unit1B remain held. Capability ratings are unchanged; this source batch does not complete FRESH capability. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java index 42e9179213..1f5d79c7b6 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -562,7 +562,13 @@ private static FluentConfiguration entityMigrationConfiguration( FluentConfiguration configuration = Flyway.configure() .dataSource(dataSource) - .locations("filesystem:" + migrationDirectory) + .locations( + "filesystem:" + migrationDirectory, + "filesystem:" + + migrationDirectory + .resolve( + "../../../../../../common-saga/src/main/resources/db/migration/saga") + .normalize()) .placeholders(Map.of("serviceSchema", "public")); configuration .getConfigurationExtension(PostgreSQLConfigurationExtension.class) diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java index ebc14ad78c..7b261deb8a 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java @@ -691,15 +691,23 @@ private static Store store(PostgreSQLContainer postgres, String service) { new DriverManagerDataSource( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); data.setSchema(schema); - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .placeholders(Map.of("serviceSchema", schema)) - .locations(migrations(service)) - .load() - .migrate(); + var flyway = + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .placeholders(Map.of("serviceSchema", schema)) + .locations(migrations(service)); + if ("world-management".equals(service)) { + flyway.locations( + migrations(service), + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize()); + } + flyway.load().migrate(); return new Store( DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES), new DataSourceTransactionManager(data)); diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java index d00edadd7b..0dd54dee76 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java @@ -838,7 +838,12 @@ private WorldStore worldStore() { .defaultSchema(schema) .table("flyway_schema_history_world_management") .placeholders(Map.of("serviceSchema", schema)) - .locations(migrationLocation("world-management")) + .locations( + migrationLocation("world-management"), + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize()) .load() .migrate(); var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index bc956259e1..21c96348e1 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -232,7 +232,7 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema diagnostics.logPostgres("game-logic", GAME_LOGIC_POSTGRES); diagnostics.logPostgres("account", ACCOUNT_POSTGRES); Store gds = store("game-design", "selected_full_gds", GDS_POSTGRES, false); - Store world = store("world-management", "selected_full_world", WORLD_POSTGRES, false); + Store world = store("world-management", "selected_full_world", WORLD_POSTGRES, true); Store entity = store("entity-management", "selected_full_entity", ENTITY_POSTGRES, true); Store automation = store("automation-scripting", "selected_full_automation", AUTOMATION_POSTGRES, true); diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index 30d178b774..01975f26b4 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -3161,7 +3161,7 @@ private static void composeActualEntityWorldRegionPrerequisite( return currentEntityTarget; }; - try (var entityDatabase = database(GS, "entity-management-service", false)) { + try (var entityDatabase = database(GS, "entity-management-service", true)) { var characterRepository = transactionalCharacterRepository( new CharacterRepository(entityDatabase.dsl()), entityDatabase.manager()); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java index cb9576c36a..5c5d3d0d1e 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java @@ -893,7 +893,7 @@ private static void migrateFixture(String schema, MigrationVersion target) { .schemas(schema) .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration"); + .locations("classpath:db/migration", "classpath:db/migration/saga"); if (target != null) { configuration.target(target); } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java index 055babdd4e..37023df234 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java @@ -1092,7 +1092,7 @@ private static void migrateFixture(String schema, MigrationVersion target) { .schemas(schema) .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration"); + .locations("classpath:db/migration", "classpath:db/migration/saga"); if (target != null) { configuration.target(target); } From bcee42f70678d110b4a08dc20a023497a57ac311 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:10:44 +1300 Subject: [PATCH 03/11] Fix catalog seals and immutable snapshot bindings --- .../runtime-and-data.md | 2 +- .../runtime-and-data.md | 4 +- .../social-groups-service/runtime-and-data.md | 2 +- .../runtime-and-data.md | 8 +- .../gameplay-rules-entities-and-effects.md | 4 +- .../realm-routing-and-playable-state.md | 4 +- ...V1005__automation_catalog_view_options.sql | 119 +++++++++ ...edSourceIntakePostgresIntegrationTest.java | 2 +- ...eFamilyCatalogPostgresIntegrationTest.java | 171 ++++++++++++- .../AutomationRuntimeFamilyCatalogCodec.java | 128 +++------- .../EntityRuntimeFamilyCatalogCodec.java | 128 +++------- .../RuntimeFamilyCatalogFraming.java | 163 ++++++++++++ .../SocialRuntimeFamilyCatalogCodec.java | 133 +++------- .../world/WorldRuntimeFamilyCatalogCodec.java | 131 +++------- ...__entity_catalog_snapshot_exact_frames.sql | 133 ++++++++++ ...eseededActorAssignmentIntegrationTest.java | 5 +- .../RetainedActorIdentityIntegrationTest.java | 14 +- ...haracterCreatePostgresIntegrationTest.java | 6 +- ...ntakeMigrationPostgresIntegrationTest.java | 2 +- ...eFamilyCatalogPostgresIntegrationTest.java | 136 +++++++++- ...ldSourceCommitPostgresIntegrationTest.java | 12 +- ...ameLogicIntakePostgresIntegrationTest.java | 8 +- .../V1005__social_catalog_view_options.sql | 128 ++++++++++ ...eFamilyCatalogPostgresIntegrationTest.java | 177 +++++++++++-- ...7__world_catalog_snapshot_exact_frames.sql | 146 +++++++++++ ...resetResourcesPostgresIntegrationTest.java | 21 ++ ...nReceiptDigestPostgresIntegrationTest.java | 23 +- ...eFamilyCatalogPostgresIntegrationTest.java | 237 +++++++++++++++++- 28 files changed, 1607 insertions(+), 440 deletions(-) create mode 100644 services/automation-scripting-service/src/main/resources/db/migration/V1005__automation_catalog_view_options.sql create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogFraming.java create mode 100644 services/entity-management-service/src/main/resources/db/migration/V1026__entity_catalog_snapshot_exact_frames.sql create mode 100644 services/social-groups-service/src/main/resources/db/migration/V1005__social_catalog_view_options.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V1047__world_catalog_snapshot_exact_frames.sql diff --git a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md index abc1b4c815..d33e6fa2a3 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -51,7 +51,7 @@ The owner derives a complete ordered census from the installed combined Automati The catalog retains exact PostgreSQL-produced UTF-8 bytes with a positive monotonic owner-local epoch and SHA-256 digest. Its closed root fields are `schema`, `owner`, decimal-string `catalogEpoch`, `families`, `schemaFacts`, and `nonSqlGaps`. Ordered, nonduplicate family entries bind exact relation/component, role, state class, FRESH disposition, retention disposition, and a bounded explicit owner consequence. Schema facts bind kind, identity, and definition digest. Limits are 512 families, 16,384 schema facts, 32 known non-SQL gaps, and 2 MiB of complete catalog bytes; exceeding a bound refuses, never returns a partial source. Roles distinguish `RUNTIME_PAYLOAD`, `SOURCE`, `CONTROL`, `AUDIT`, `PROVENANCE`, and `CATALOG`. `UNKNOWN`, `UNRESOLVED`, and `NOT_PAYLOAD` are classification/disposition evidence, not new runtime replacement classes; no S3 classification is inferred from this source. -The additive V1004 storage consists of explicit classification and known non-SQL-gap declarations, retained catalog epochs, and immutable request-bound snapshots. It preserves prior Automation/Saga rows, source-intake guards, sequences, and migration history; it does not adopt old numeric identities or rewrite prior migrations. Flyway 13.12's built-in `${flyway:table}` binds the actual configured history table, including custom history names. Because the owner migration's successful history row is written after its transaction, the seal uses its exact installed definitions plus a stable installation marker and separately requires the successful exact V1004 script on later reads. It does not fabricate an own-migration checksum or treat a missing successful installation as current. +The additive V1004 storage consists of explicit classification and known non-SQL-gap declarations, retained catalog epochs, and immutable request-bound snapshots. It preserves prior Automation/Saga rows, source-intake guards, sequences, and migration history; it does not adopt old numeric identities or rewrite prior migrations. Flyway 13.12's built-in `${flyway:table}` binds the actual configured history table, including custom history names. View and materialized-view facts bind both `pg_get_viewdef` and `pg_class.reloptions`, including view security options; changing either invalidates the sealed epoch. The V1005 forward migration replaces the census routines and appends the next exact owner-local epoch without rewriting prior epochs, snapshots, payload rows, or history. Because catalog migrations' successful history rows are written after their transactions, the current seal uses distinct `catalog-installation:1004` and `catalog-installation:1005` markers in place of those rows and separately requires both successful exact scripts on later reads. These markers do not attest to post-transaction checksums; normal Flyway validation remains required. An old request cannot be resampled under the new epoch. Capture uses an independent owner transaction and complete retained readback in a separate read-only repeatable-read transaction. SQL guards bind the complete request/evidence frames to the latest exact sealed epoch; Java additionally compares every retained identity, byte array, and digest. Exact concurrent retries converge on one immutable snapshot. UPDATE, DELETE, and TRUNCATE of catalog declarations, epochs, or snapshots refuse; a later explicit owner revision cannot overwrite the old evidence, and an invalidated old request cannot be silently resampled. Catalog rows have no automatic expiry. These catalog retention guards neither replace existing runtime cleanup/hold rules nor grant new cleanup, clone, reset, resume, or deployment authority. 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 b1dd3300f7..3ef2440b85 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -39,9 +39,9 @@ The Entity-local catalog is a schema/classification source prerequisite, not the The census comes from actual PostgreSQL `pg_catalog` in the configured Entity schema, not a Java expected-table list, a name-prefix rule or runtime row absence. Every installed ordinary/partitioned/foreign table needs one explicit base disposition, including the shared Saga tables, actual configured Flyway history and all three catalog tables. Mixed components have additional explicit declarations. The current ordered source stream has 56 Entity tables before this additive migration; Saga, history and new infrastructure are additional installed census members. No historical table/column removal or rename is inferred, and logical `character` maps only to physical/wire `characters`; illustrative `entity_tick_state` is not an installed table. -The seal binds exact family metadata and sorted definition hashes for tables, columns/defaults, constraints/validation, indexes, triggers, policies, rules, routines, sequences, views, types and installed migrations. Definition hashes exclude payload rows, OIDs, statistics, sequence positions and installation timestamps. The first durable epoch is sealed during V1025 against the actual installation; it is not a claim to repair a previously drifted database or certify uninspected pre-installation definitions. Missing declared tables/components or unknown tables refuse even that initial installation. Thereafter any added, removed, renamed, changed or unclassified table/column/routine/migration/classification changes the census or refuses it and invalidates the existing seal. Neither new requests nor retries can resample under an unchanged epoch. A subsequent owner-controlled forward installation must explicitly retain a new monotonic epoch; there is no catalog-mutation RPC. +The seal binds exact family metadata and sorted definition hashes for tables, columns/defaults, constraints/validation, indexes, triggers, policies, rules, routines, sequences, views (including authorization and materialized-view options), types and installed migrations. Definition hashes exclude payload rows, OIDs, statistics, sequence positions and installation timestamps. The first durable epoch is sealed during V1025 against the actual installation; it is not a claim to repair a previously drifted database or certify uninspected pre-installation definitions. Missing declared tables/components or unknown tables refuse even that initial installation. Thereafter any added, removed, renamed, changed or unclassified table/column/routine/migration/classification changes the census or refuses it and invalidates the existing seal. Neither new requests nor retries can resample under an unchanged epoch. A subsequent owner-controlled forward installation must explicitly retain a new monotonic epoch; there is no catalog-mutation RPC. -Flyway's built-in `${flyway:table}` placeholder binds the actual configured history identifier, including custom fixture/deployment names; there is no hardcoded deployment-history fallback. All other installed migration facts bind actual script, version, type, checksum and success. V1025's own successful history row is written after its migration transaction, so its seal contains an explicit `catalog-installation:1025` script marker instead of pretending to include that future row's checksum/timing. Every read and snapshot insert separately requires the successful exact V1025 script row. This marker/installed-row boundary is not full attestation of V1025's post-transaction checksum; normal Flyway checksum validation remains required. Entity's combined Entity/Saga locations and PostgreSQL `transactional-lock=false` remain unchanged, as does V1004's `executeInTransaction=false` concurrent-index configuration. Only PostgreSQL census/functions/triggers/seed are bracketed out of jOOQ DDL simulation; ordinary catalog table/column DDL remains visible to generation. +Flyway's built-in `${flyway:table}` placeholder binds the actual configured history identifier, including custom fixture/deployment names; there is no hardcoded deployment-history fallback. All other installed migration facts bind actual script, version, type, checksum and success. V1025's own successful history row is written after its migration transaction, so its seal contains an explicit `catalog-installation:1025` script marker instead of pretending to include that future row's checksum/timing. [V1026](../../../../services/entity-management-service/src/main/resources/db/migration/V1026__entity_catalog_snapshot_exact_frames.sql) tightens snapshot insertion to reconstruct and compare the complete exact `ECR1` request and `ECE1` evidence frames, including request UUID, namespace, snapshot UUID and sealed catalog. It retains V1025 and every historical epoch/snapshot unchanged and seals the next monotonic owner epoch because the routine definitions change. Its own history row uses a distinct `catalog-installation:1026` marker under the same post-transaction boundary. Every read and snapshot insert separately requires both successful exact installation script rows; V1026 does not certify its future checksum. Old request identities remain retained and conflict after epoch advancement; fresh identities read the newly sealed catalog. This marker/installed-row boundary is not full attestation of either installation's post-transaction checksum; normal Flyway checksum validation remains required. Entity's combined Entity/Saga locations and PostgreSQL `transactional-lock=false` remain unchanged, as does V1004's `executeInTransaction=false` concurrent-index configuration. Only PostgreSQL census/functions/triggers/seed are bracketed out of jOOQ DDL simulation; ordinary catalog table/column DDL remains visible to generation. The explicit metadata preserves these distinct consequences: diff --git a/design/architecture/microservices/social-groups-service/runtime-and-data.md b/design/architecture/microservices/social-groups-service/runtime-and-data.md index 5c41d2e5dc..ce0ae3ae02 100644 --- a/design/architecture/microservices/social-groups-service/runtime-and-data.md +++ b/design/architecture/microservices/social-groups-service/runtime-and-data.md @@ -61,7 +61,7 @@ The additive V1004 owner-local catalog is schema-derived source evidence. It ass An unclassified table refuses catalog installation even when it has no rows. After installation, changed, removed, renamed, or newly added schema objects, classifications, or prior migration facts invalidate the stored epoch and refuse both retained and new reads. No runtime path resamples drift or accepts an epoch; future schema/classification evolution requires an explicit owning forward migration. The immutable classification, epoch, and snapshot records preserve the installed source and exact request-bound evidence. -Flyway 13.12's built-in `${flyway:table}` placeholder binds the configured history table, including a custom name; the catalog never assumes a public-schema history name. Flyway writes V1004's successful history row after the migration transaction, so the seal uses a stable `catalog-installation:1004` marker in place of that not-yet-existing row and the separate installed check requires the exact successful V1004 script. The marker does not attest to the post-transaction checksum; normal Flyway validation remains required. +Flyway 13.12's built-in `${flyway:table}` placeholder binds the configured history table, including a custom name; the catalog never assumes a public-schema history name. View and materialized-view facts bind both `pg_get_viewdef` and `pg_class.reloptions`, including view security options; changing either invalidates the sealed epoch. The V1005 forward migration replaces the census routines and appends the next exact owner-local epoch without rewriting prior epochs, snapshots, payload rows, or history. Flyway writes catalog migrations' successful history rows after their transactions, so the current seal uses distinct `catalog-installation:1004` and `catalog-installation:1005` markers in place of those rows and the separate installed check requires both exact successful scripts. These markers do not attest to post-transaction checksums; normal Flyway validation remains required. An old request cannot be resampled under the new epoch. The separate `ReadSocialRuntimeFamilyCatalog` contract in [API Contracts](./api-contracts.md#owner-local-runtime-family-catalog-read) retains one complete request-bound evidence frame and refuses drift or storage failure. The handler and Game Session mTLS client are manual source only; the Social handler is not registered with the application's gRPC server, and neither side is connected to player/API flows. This catalog is not row-level evidence, owner enrollment, target initialization, a global FRESH manifest, runtime authority, or admission; its explicit blockers—including tenant-bound account friendships, Social guild value storage, unresolved Saga adoption, and missing communication, safety, and standing contracts—do not qualify for readiness. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 2feeb5c6e5..19f8fd5b41 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -168,13 +168,13 @@ Redis caches hot rooms for active sessions to speed up lookups. Target Class A c ## Owner-local Runtime-family Catalog -The manually composed World runtime-family catalog persists owner-local source evidence under forward [V1046](../../../../services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql). It adds only `world_runtime_family_classification`, `world_runtime_family_catalog_epoch` and `world_runtime_family_catalog_snapshot` plus their source functions/guards. Existing World data, authority, lifecycle rows and earlier migrations are not rewritten. Its authenticated read and exact value/transport contract are owned by [World API Contracts](./api-contracts.md#owner-local-runtime-family-catalog-read); implementation and focused proof status are tracked in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#world-owner-local-runtime-family-catalog-prerequisite). +The manually composed World runtime-family catalog persists owner-local source evidence under forward [V1046](../../../../services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql) and [V1047](../../../../services/world-management-service/src/main/resources/db/migration/V1047__world_catalog_snapshot_exact_frames.sql). The catalog adds only `world_runtime_family_classification`, `world_runtime_family_catalog_epoch` and `world_runtime_family_catalog_snapshot` plus their source functions/guards. Existing World data, authority, lifecycle rows and earlier migrations are not rewritten. Its authenticated read and exact value/transport contract are owned by [World API Contracts](./api-contracts.md#owner-local-runtime-family-catalog-read); implementation and focused proof status are tracked in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#world-owner-local-runtime-family-catalog-prerequisite). -The migration installs explicit owner metadata for every current World/Saga/history/catalog table, plus the distinct `region_instance.weather` component. `world_runtime_family_catalog_bytes` actually reads the installed service schema through PostgreSQL catalogs and the owning Flyway history. Each table must have a declared table-level disposition, each declared table must exist, and each declared component must resolve to an installed non-dropped column. It also enumerates columns with type/default/nullability/identity/generated/collation facts, constraints, indexes, triggers, routines, sequences, views/rules, types and policies with definition digests. Routine and trigger facts include the installed owner guards, including this catalog's own functions. Migration evidence binds installed rank, version, script, checksum and success, excluding installation user/time. Sequence positions, OIDs, statistics and gameplay row contents are not schema facts. The resulting ordered census and classifications are sealed together as exact bytes with a positive durable epoch, initially `1`, and an actual-byte SHA-256 digest; no Java constructor or empty payload query declares the installed inventory complete. +The migration installs explicit owner metadata for every current World/Saga/history/catalog table, plus the distinct `region_instance.weather` component. `world_runtime_family_catalog_bytes` actually reads the installed service schema through PostgreSQL catalogs and the owning Flyway history. Each table must have a declared table-level disposition, each declared table must exist, and each declared component must resolve to an installed non-dropped column. It also enumerates columns with type/default/nullability/identity/generated/collation facts, constraints, indexes, triggers, routines, sequences, views/rules, types and policies with definition digests. View and materialized-view facts bind both the query definition and installed relation options, including security and storage options; changing an option invalidates the sealed census. Routine and trigger facts include the installed owner guards, including this catalog's own functions. Migration evidence binds installed rank, version, script, checksum and success, excluding installation user/time. Sequence positions, OIDs, statistics and gameplay row contents are not schema facts. The resulting ordered census and classifications are sealed together as exact bytes with a positive durable epoch, initially `1`, and an actual-byte SHA-256 digest; no Java constructor or empty payload query declares the installed inventory complete. -Flyway records V1046's own history row after its migration transaction. The initial seal therefore includes a stable `catalog-installation:1046` marker and the actual installed object definitions, rather than the not-yet-existing self-history checksum. Flyway's built-in `flyway:table` placeholder binds the actual configured history relation into the census, its explicit classification and the installed-row check; the service's default `public` schema and explicitly configured history names do not require a separate hardcoded table. The read owner separately requires V1046's successful exact script row through that installed owner function. Every other installed migration row participates in the seal; adding a later migration, changing a prior migration fact, or adding/removing/renaming/changing a schema object or classification invalidates this epoch. A new table with zero rows is still an unclassified family and refuses. Subsequent catalog/schema evolution needs an explicit owning forward migration to install its supported classifications and next exact epoch, including updating the installation-marker/history boundary for that migration. There is no runtime resampling, epoch-advance endpoint or automatic acceptance of a changed census. This seal is owner-local installed-schema evidence, not an external deployment attestation or a substitute for Flyway validation. +Flyway records each catalog migration's own history row after its migration transaction. The seal therefore includes distinct stable `catalog-installation:1046` and `catalog-installation:1047` markers and the actual installed object definitions, rather than inventing self-history checksums or successful rows inside either transaction. The original V1046 epoch retains its original single-marker census; V1047 replaces the catalog routines and explicitly appends the next monotonic epoch after all routine replacements, preserving every old epoch, snapshot and migration row byte-for-byte. A fresh installation consequently retains epoch `1` and seals current epoch `2`; an upgrade appends the next epoch after its retained history, and old request identities conflict rather than resampling. Flyway's built-in `flyway:table` placeholder binds the actual configured history relation into the census, its explicit classification and the installed-row check; the service's default `public` schema and explicitly configured history names do not require a separate hardcoded table. Both the read owner and the snapshot insertion guard separately require the successful exact V1046 and V1047 script rows through that installed owner function, because their markers cannot establish actual installation success. Every other installed migration row participates in the seal; adding a later migration, changing a prior migration fact, or adding/removing/renaming/changing a schema object or classification invalidates this epoch. A new table with zero rows is still an unclassified family and refuses. Subsequent catalog/schema evolution needs an explicit owning forward migration to install its supported classifications and next exact epoch, including updating the installation-marker/history boundary for that migration. There is no runtime resampling, epoch-advance endpoint or automatic acceptance of a changed census. This seal is owner-local installed-schema evidence, not an external deployment attestation or a substitute for Flyway validation. -Epoch rows, classification rows and request snapshots reject UPDATE, DELETE and TRUNCATE. A new epoch insertion must be the next positive epoch and bind the exact current census bytes; a source snapshot insertion must bind the current epoch/digest and unchanged installed census. The request UUID is unique across namespaces. A retained snapshot binds exact request bytes/digest, workload namespace, World snapshot UUID, epoch/catalog digest and complete response bytes/digest. Exact retry and independent committed readback compare all of them; changed requests, missing snapshots and old snapshots under a changed catalog refuse rather than returning absence or updated evidence. Evidence is retained without a new deletion/expiry policy or cleanup job. A caller-visible refusal after capture commit does not erase retained evidence. These source records do not mutate a realm, runtime, canonical pointer or player state. +Epoch rows, classification rows and request snapshots reject UPDATE, DELETE and TRUNCATE. A new epoch insertion must be the next positive epoch and bind the exact current census bytes; a source snapshot insertion must bind the current epoch/digest, unchanged installed census and successful exact catalog installation. The PostgreSQL guard reconstructs the complete canonical `WCR1` request frame from the row's request UUID and namespace and the complete `WCE1` evidence frame from that request, snapshot UUID and sealed catalog digest/bytes. Both stored frames must match those exact bytes, independently of their per-column digest CHECKs, so valid digests over mismatched or arbitrary frames cannot consume a request identity. The request UUID is unique across namespaces. A retained snapshot binds exact request bytes/digest, workload namespace, World snapshot UUID, epoch/catalog digest and complete response bytes/digest. Exact retry and independent committed readback compare all of them; changed requests, missing snapshots and old snapshots under a changed catalog refuse rather than returning absence or updated evidence. Evidence is retained without a new deletion/expiry policy or cleanup job. A caller-visible refusal after capture commit does not erase retained evidence. These source records do not mutate a realm, runtime, canonical pointer or player state. Current catalog dispositions are intentionally not FRESH outcomes: diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 331c7403f6..7a373cb6b2 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -10,9 +10,9 @@ This is a non-normative implementation tracker for gameplay rules, entities, and Working source adds the bounded Entity-local catalog prerequisite within the existing private FRESH batch: forward [V1025](../../../services/entity-management-service/src/main/resources/db/migration/V1025__entity_owner_runtime_family_catalog.sql), [capture and independent readback repository](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogRepository.java), [authenticated read handler](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java), [immutable Common value](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java), [closed codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogCodec.java), [purpose-specific proto](../../../protos/entity-management/v1/entity_runtime_family_catalog_read.proto) and [Game Session consumer](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClient.java). Normative semantics belong only to [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md#owner-local-runtime-family-catalog) and [Entity API Contracts](../../architecture/microservices/entity-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). These components remain manually composed/unregistered, with no FRESH coordinator or pointer integration and no capability-rating upgrade. -Focused executable sources are added for [Common value/codec/digest/bounds](../../../services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogTest.java), [workload-before-decode/SQL and positive handler behavior](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcServiceTest.java), [actual combined-migration PostgreSQL census, conditional/unresolved facts, populated retained source, epoch/readback/reconstruction, concurrent exact replay, history names and drift](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java), and [peer-qualified Game Session mTLS identity, correlation, refusals and actual deadline](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClientMtlsTest.java). Existing Entity migration-frontier fixture assertions advance to V1025 without removing their positive cases or changing old migrations. The new PostgreSQL fixture retains the real Entity Testcontainers/Flyway pattern, combined Saga locations, custom history and V1004's nontransactional concurrent-index behavior; it has no unavailable-Docker skip or substitute database. +Focused executable sources are added for [Common value/codec/digest/bounds](../../../services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogTest.java), [workload-before-decode/SQL and positive handler behavior](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcServiceTest.java), [actual combined-migration PostgreSQL census, conditional/unresolved facts, populated retained source, epoch/readback/reconstruction, concurrent exact replay, history names and drift](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java), and [peer-qualified Game Session mTLS identity, correlation, refusals and actual deadline](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClientMtlsTest.java). Existing Entity migration-frontier fixture assertions advance to V1026 without removing their positive cases or changing old migrations. The new PostgreSQL fixture retains the real Entity Testcontainers/Flyway pattern, combined Saga locations, custom history and V1004's nontransactional concurrent-index behavior; it has no unavailable-Docker skip or substitute database. -Receiving proof243/244 passes seven Common value/codec cases, four workload-guard cases, twelve actual PostgreSQL cases and five physical client mTLS cases, with zero failures, errors or skips. Proof242 passes owning generation/formatting. Proof245 passes all 53 cases across the four affected existing Entity migration-fixture suites, affected main/unit/integration static analysis, formatting and documentation checks. Game Session main SpotBugs remains unqualified under the separate JVM investigation. SQL/RPC peer contexts and retained upstream identities are controlled; separate physical mTLS source uses controlled local PKI and catalog bytes, not a coupled SQL-to-mTLS owner chain or genuine issuer/custody evidence. Reconstruction is not process-death proof. The V1025 installed-row marker has the explicit post-transaction checksum limit documented at its owner. +Receiving proof243/244 passes seven Common value/codec cases, four workload-guard cases, twelve actual PostgreSQL cases and five physical client mTLS cases, with zero failures, errors or skips. Proof242 passes owning generation/formatting. Proof245 passes all 53 cases across the four affected existing Entity migration-fixture suites, affected main/unit/integration static analysis, formatting and documentation checks. Game Session main SpotBugs remains unqualified under the separate JVM investigation. SQL/RPC peer contexts and retained upstream identities are controlled; separate physical mTLS source uses controlled local PKI and catalog bytes, not a coupled SQL-to-mTLS owner chain or genuine issuer/custody evidence. Reconstruction is not process-death proof. The catalog installation markers have the explicit post-transaction checksum limit documented at their owner. Review fixes add forward V1026 and preserve the earlier migration and retained epochs/snapshots; proof271 passes owning generation and fourteen actual catalog PostgreSQL cases, including six direct-SQL poison-frame vectors and genuine V1025 upgrade retention. The four existing latest-frontier suites retain their historical parent targets and advance only their current-version/script assertions. After the view-options correction, proof275 passes fifteen catalog PostgreSQL cases and all fifty-three cases in those existing suites with no failures, errors or skips, including real view-security and materialized-view option drift. Applied predecessors remain unchanged, and the mandatory-Docker contract is explicit; no unavailable-Docker skip is added. Remaining semantic obligations include namespace qualification for provisional character/friend and S2 inventory/equipment; resource/condition namespace, frozen-definition and remap proof; complete row-level holder closure; unresolved NPC mixed state and visible-ref allocator S-class; owner manifests/materialization and complete owner-set aggregation into the existing canonical CLOSED owner. No catalog proves empty target state, approved/applied remaps, complete FRESH, other-owner commit currentness, registration, actor promotion/backfill, cleanup/retirement, admission/activation, seeded/snapshot/reset, production PKI or Unit1B. Main Gameplay owns integration, consolidated validation, aggregated realm-routing status and any publication. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index b028b8b64e..b9d4418530 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -27,7 +27,9 @@ Current-selection CAS is implemented by [`GameSessionCurrentPrivatePlaytestRepos The private FRESH prerequisite batch now has a concrete World-local catalog producer and Game Session consumer in working source: forward [V1046](../../../services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql), [World persistence/readback owner](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogRepository.java), [authenticated World read](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java), [shared exact value](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java), [closed codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java) and [Game Session client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClient.java). The normative census/classification/retention detail stays with [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#owner-local-runtime-family-catalog), and wire/authentication/bounds with [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). This is an actual database-derived World schema/family source and durable epoch/snapshot prerequisite, not a static expected-table list, global runtime registry, complete owner-epoch set or FRESH manifest. -Receiving proof243/244 passes six World [value/codec cases](../../../services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogTest.java), four [workload-guard cases](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcServiceTest.java), thirteen [actual PostgreSQL cases](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java) and four [physical client mTLS cases](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClientMtlsTest.java), with zero failures, errors or skips. The four-owner receiving batch totals 107 focused cases; proof245 separately passes 129 affected existing Entity/Automation migration-fixture cases and selected owner/Common main-unit-integration static analysis, formatting and documentation checks. Owning generation passes242/243. Earlier retained proof238 reproduces the configured-history refusal corrected before239; it is not a passing aggregate. Proof243 retains its missing Social client-import compilation failure;244 runs the corrected eighteen client cases and reuses unchanged passing codec/guard/SQL results. Exact XML and logs retain those scopes. The complete foreign-catalog fixture dependency pass aligns seven additional sites without changing historical targets or assertions. Proof262 passes the actual Entity/World cross-owner case after the Entity setup discovers Saga;263 passes twenty-four cases across the affected Account, World and Game Design suites, plus selected analysis/formatting/docs (3m25). Account’s V1023 predecessor discovers Saga before its later Entity upgrade; World targets25/26 remain unchanged. These controlled source compositions do not establish genuine private initialization. Game Session main SpotBugs remains unqualified under the separate JVM investigation. PostgreSQL identity/legacy inputs and guard peer contexts are controlled; mTLS uses local test PKI and catalog responses rather than a live database producer. No coupled database-plus-mTLS owner chain, fresh-image/runtime or whole-FRESH proof is claimed. +Receiving proof243/244 passes six World [value/codec cases](../../../services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogTest.java), four [workload-guard cases](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcServiceTest.java), thirteen [actual PostgreSQL cases](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java) and four [physical client mTLS cases](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClientMtlsTest.java), with zero failures, errors or skips. The four-owner receiving batch totals 107 focused cases; proof245 separately passes 129 affected existing Entity/Automation migration-fixture cases and selected owner/Common main-unit-integration static analysis, formatting and documentation checks. Owning generation passes in proof242/243. Earlier retained proof238 reproduces the configured-history refusal corrected before proof239; it is not a passing aggregate. Proof243 retains its missing Social client-import compilation failure; proof244 runs the corrected eighteen client cases and reuses unchanged passing codec/guard/SQL results. Exact XML and logs retain those scopes. The complete foreign-catalog fixture dependency pass aligns seven additional sites without changing historical targets or assertions. Proof262 passes the actual Entity/World cross-owner case after the Entity setup discovers Saga; proof263 passes twenty-four cases across the affected Account, World and Game Design suites, plus selected analysis/formatting/docs (3m25). Account’s V1023 predecessor discovers Saga before its later Entity upgrade; World targets 25/26 remain unchanged. These controlled source compositions do not establish genuine private initialization. Game Session main SpotBugs remains unqualified under the separate JVM investigation. PostgreSQL identity/legacy inputs and guard peer contexts are controlled; mTLS uses local test PKI and catalog responses rather than a live database producer. No coupled database-plus-mTLS owner chain, fresh-image/runtime or whole-FRESH proof is claimed. + +Review corrections retain the published catalog migrations and add forward owner seals for view definitions and options. Proof275/276 passes 252 actual PostgreSQL cases across the affected Entity, World, Automation and Social suites, including seventeen World catalog cases, the receipt-digest migration composition and thirteen fixed-preset upgrade cases. World's controlled receipt probe now installs every source World/Saga table before reaching the full census; its predicate-only clone is not production authority. The fixed-preset retention case compares all original row values and `xmin` while separately asserting the three new catalog tables, two retained epochs and empty request snapshots. Proof275 retains that comparison failure; proof276 passes the corrected thirty-one World cases and selected integration static, formatting and documentation checks. The four mandatory-Docker catalog fixtures and combined forward-version checks pass their canonical contracts. Proof273 separately passes twenty-five Common codec cases, five Game Design compositions and eighteen physical mTLS client cases after the shared framing helper adds defensive copies; proof272's earlier mutable-array analysis failure remains recorded. These component proofs do not expand the source or runtime authority boundary. Remaining batch obligations are the genuine World-owned global enrollment/required-owner-set source, remaining actual owner catalogs/epochs, complete build/lifecycle/namespace/generation-bound FRESH manifest production and immutable authenticated readback, genuine protected private authorization/runtime/materialization, and complete-set aggregation into the existing canonical CLOSED pointer/audit/outcome owner. Current World canonical materialization is still public `SHARED` and original-`StartSession`-only; no private FRESH relabelling is valid. The existing unregistered [canonical CLOSED owner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java) supplies public initial CLOSED persistence, not the missing private aggregate; the registered legacy routing model described elsewhere remains narrower. No second private pointer authority is added. CLOSED-to-OPEN, private first admission, issuer/custody/PKI qualification, runtime/default registration, operational activation, reset and Unit1B remain held. Capability ratings are unchanged; this source batch does not complete FRESH capability. diff --git a/services/automation-scripting-service/src/main/resources/db/migration/V1005__automation_catalog_view_options.sql b/services/automation-scripting-service/src/main/resources/db/migration/V1005__automation_catalog_view_options.sql new file mode 100644 index 0000000000..efb92d08c6 --- /dev/null +++ b/services/automation-scripting-service/src/main/resources/db/migration/V1005__automation_catalog_view_options.sql @@ -0,0 +1,119 @@ +-- Retain V1004 and all historical epochs, snapshots and migration rows byte-for-byte. +-- View and materialized-view options are part of the installed definition seal. +-- Flyway records each migration's own row after its transaction; distinct stable markers +-- bind the catalog installations without fabricating checksums or successful history rows. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION automation_runtime_family_catalog_installed() RETURNS BOOLEAN +LANGUAGE SQL STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ + SELECT EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1004' AND script='V1004__automation_owner_runtime_family_catalog.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1005' AND script='V1005__automation_catalog_view_options.sql' AND success); +$$; + +CREATE OR REPLACE FUNCTION automation_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE v_families JSONB; v_facts JSONB; v_gaps JSONB; +BEGIN + IF p_epoch IS NULL OR p_epoch<=0 THEN + RAISE EXCEPTION 'Positive Automation catalog epoch required' USING ERRCODE='23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM automation_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM automation_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed Automation schema family' USING ERRCODE='23514'; + END IF; + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name,'component',component_name, + 'role',family_role,'stateClass',state_class,'freshDisposition',fresh_disposition, + 'retentionDisposition',retention_disposition,'ownerConsequence',owner_consequence) + ORDER BY family_id COLLATE "C") INTO v_families FROM automation_runtime_family_classification; + SELECT jsonb_agg(jsonb_build_object('id',gap_id,'disposition',disposition,'ownerConsequence',owner_consequence) + ORDER BY gap_id COLLATE "C") INTO v_gaps FROM automation_runtime_catalog_non_sql_gap; + + -- Live definitions, never payload rows, OIDs, sequence positions, statistics or installation times. + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname,jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::TEXT FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1004' AND version IS DISTINCT FROM '1005' + UNION ALL + -- Catalog history rows are post-transaction. Distinct stable installation markers bind + -- those scripts; installed() separately requires both successful exact script identities. + -- These markers do not fabricate post-transaction Flyway checksums. + SELECT 'MIGRATION','catalog-installation:1004','V1004__automation_owner_runtime_family_catalog.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1005','V1005__automation_catalog_view_options.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + IF v_families IS NULL OR v_facts IS NULL OR v_gaps IS NULL + OR jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 + OR jsonb_array_length(v_gaps)>32 THEN + RAISE EXCEPTION 'Complete Automation catalog exceeds source bounds' USING ERRCODE='23514'; + END IF; + RETURN convert_to(jsonb_build_object('schema','automation-runtime-family-catalog/v1', + 'owner','automation-scripting-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts,'nonSqlGaps',v_gaps)::TEXT,'UTF8'); +END; +$$; + +-- Replace every affected routine before sealing the next exact owner-local epoch. +INSERT INTO automation_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT next_epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM (SELECT coalesce(max(catalog_epoch),0)+1 AS next_epoch FROM automation_runtime_family_catalog_epoch) next +CROSS JOIN LATERAL (SELECT automation_runtime_family_catalog_bytes(next.next_epoch) AS bytes) seal; +-- [jooq ignore stop] diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java index a3758eb256..cc9ff1c293 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java @@ -98,7 +98,7 @@ void migrateWithRetainedLegacyAuthoredRows() { dsl.fetchSingle( "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") .get(0, String.class)) - .isEqualTo("1003"); + .isEqualTo("1005"); } /** Synthetic retained SQL state only; no genuine script or runtime admission authority. */ diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java index d9142e9fa9..53daf7fa01 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -46,7 +46,7 @@ * live private authority producer or mTLS/PKI proof. Positive cases are not disabled without * Docker. */ -@Testcontainers +@Testcontainers(disabledWithoutDocker = false) @SuppressWarnings("resource") class AutomationRuntimeFamilyCatalogPostgresIntegrationTest { private static final String MIGRATIONS = @@ -84,7 +84,7 @@ void completeLiveCensusIncludesEveryEmptyTableAndExplicitBlockingFamiliesAndNonS throws Exception { try (Fixture f = fixture(null)) { var catalog = f.owner().read(request()).catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat(catalog.catalogEpoch()).isEqualTo(2); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -155,7 +155,7 @@ void completeLiveCensusIncludesEveryEmptyTableAndExplicitBlockingFamiliesAndNonS f.dsl .fetchSingle( "SELECT catalog_bytes=automation_runtime_family_catalog_bytes(catalog_epoch)" - + " FROM automation_runtime_family_catalog_epoch") + + " FROM automation_runtime_family_catalog_epoch ORDER BY catalog_epoch DESC LIMIT 1") .get(0, Boolean.class)) .isTrue(); assertThat(f.count("script_work_items")).isZero(); @@ -346,7 +346,7 @@ void priorMigrationFactsAndOwnSuccessfulScriptAreRequiredNotFabricatedOwnChecksu "INSERT INTO " + f.history + " (installed_rank,version,description,type,script,checksum,installed_by,execution_time,success)" - + " VALUES (10000,'1005','controlled later migration','SQL','V1005__probe.sql',1,current_user,0,true)"); + + " VALUES (10000,'1006','controlled later migration','SQL','V1006__probe.sql',1,current_user,0,true)"); assertThatThrownBy(() -> f.owner().read(request())) .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); } @@ -361,8 +361,8 @@ void explicitOwnerEpochAdvanceInvalidatesOldRequestButRetainsOriginalSnapshot() // Controlled owner revision installation only; no runtime mutation/registration API exists. f.dsl.execute( "INSERT INTO automation_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 2,bytes,'sha256:'||encode(sha256(bytes),'hex')" - + " FROM (SELECT automation_runtime_family_catalog_bytes(2) AS bytes) revised"); + + " SELECT 3,bytes,'sha256:'||encode(sha256(bytes),'hex')" + + " FROM (SELECT automation_runtime_family_catalog_bytes(3) AS bytes) revised"); assertThatThrownBy(() -> f.owner().readExact(read)) .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().read(read)) @@ -375,9 +375,9 @@ void explicitOwnerEpochAdvanceInvalidatesOldRequestButRetainsOriginalSnapshot() .get(0, byte[].class)) .isEqualTo(AutomationRuntimeFamilyCatalogCodec.evidenceBytes(original)); var revised = f.owner().read(request()); - assertThat(revised.catalog().catalogEpoch()).isEqualTo(2); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(3); assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); - assertThat(f.count("automation_runtime_family_catalog_epoch")).isEqualTo(2); + assertThat(f.count("automation_runtime_family_catalog_epoch")).isEqualTo(3); } } @@ -422,7 +422,7 @@ void metadataEpochSnapshotRetentionAndCompleteSqlFrameBindingCannotBeBypassed() () -> f.dsl.execute( "INSERT INTO automation_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 2,catalog_bytes,catalog_digest FROM automation_runtime_family_catalog_epoch WHERE catalog_epoch=1")) + + " SELECT 3,catalog_bytes,catalog_digest FROM automation_runtime_family_catalog_epoch WHERE catalog_epoch=2")) .hasMessageContaining("exact classified installed schema"); assertThatThrownBy( () -> @@ -475,6 +475,146 @@ void realProducerReturnsCompleteCorrelatedEvidenceWithoutRuntimeWritesAndRejects } } + @Test + void viewSecurityOptionsInvalidateReadRetryAndFreshCaptureWithoutChangingRetainedEvidence() + throws Exception { + for (String option : List.of("security_invoker", "security_barrier")) { + try (Fixture f = fixture("1003")) { + // Install the real view before either catalog migration so its initial options are sealed. + f.dsl.execute("CREATE VIEW catalog_security_probe AS SELECT 1 AS id"); + migration(f.source, f.schema, f.history, null).migrate(); + Request read = request(); + var original = f.owner().read(read); + assertThat(original.catalog().catalogEpoch()).isEqualTo(2); + assertThat(original.catalog().schemaFacts()) + .anySatisfy( + fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.VIEW); + assertThat(fact.identity()).isEqualTo("catalog_security_probe"); + assertThat(fact.definitionDigest()) + .isEqualTo( + f.dsl + .fetchSingle( + "SELECT 'sha256:'||encode(sha256(convert_to(" + + "jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::text,'UTF8')),'hex')" + + " FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace" + + " WHERE n.nspname=? AND c.relname='catalog_security_probe'", + f.schema) + .get(0, String.class)); + }); + assertThat(f.owner().read(read)).isEqualTo(original); + assertThat(f.owner().readExact(read)).isEqualTo(original); + String definition = + f.dsl + .fetchSingle("SELECT pg_get_viewdef('catalog_security_probe'::regclass,true)") + .get(0, String.class); + String epochs = f.catalogRows("automation_runtime_family_catalog_epoch"); + String snapshots = f.catalogRows("automation_runtime_family_catalog_snapshot"); + f.dsl.execute("ALTER VIEW catalog_security_probe SET (" + option + "=true)"); + assertThat( + f.dsl + .fetchSingle("SELECT pg_get_viewdef('catalog_security_probe'::regclass,true)") + .get(0, String.class)) + .isEqualTo(definition); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(read)) + .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(request())) + .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.catalogRows("automation_runtime_family_catalog_epoch")).isEqualTo(epochs); + assertThat(f.catalogRows("automation_runtime_family_catalog_snapshot")) + .isEqualTo(snapshots); + } + } + } + + @Test + void catalogViewOptionsUpgradeRetainsV1004DataHistoryEpochAndSnapshot() throws Exception { + try (Fixture f = fixture("1004")) { + f.populatePredecessor(); + Map rows = f.rows(); + rows.remove("automation_runtime_family_catalog_epoch"); + rows.remove("automation_runtime_family_catalog_snapshot"); + Request read = request(); + var original = f.owner().read(read); + assertThat(original.catalog().catalogEpoch()).isEqualTo(1); + List history = f.historyRows(false); + String epoch = f.catalogRows("automation_runtime_family_catalog_epoch"); + String snapshots = f.catalogRows("automation_runtime_family_catalog_snapshot"); + migration(f.source, f.schema, f.history, null).migrate(); + for (var retained : rows.entrySet()) + assertThat(f.jsonRows(retained.getKey())).isEqualTo(retained.getValue()); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(h)::text FROM " + + f.history + + " h WHERE version IS DISTINCT FROM '1005' ORDER BY installed_rank") + .getValues(0, String.class)) + .isEqualTo(history); + assertThat(f.catalogRows("automation_runtime_family_catalog_epoch WHERE catalog_epoch=1")) + .isEqualTo(epoch); + assertThat(f.catalogRows("automation_runtime_family_catalog_snapshot")).isEqualTo(snapshots); + assertThat(f.count("automation_runtime_family_catalog_epoch")).isEqualTo(2); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(read)) + .isInstanceOf(AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.catalogRows("automation_runtime_family_catalog_snapshot")).isEqualTo(snapshots); + var current = f.owner().read(request()); + assertThat(current.catalog().catalogEpoch()).isEqualTo(2); + assertThat(current.catalog().digest()).isNotEqualTo(original.catalog().digest()); + assertThat(f.owner().readExact(current.request())).isEqualTo(current); + assertThat( + current.catalog().schemaFacts().stream() + .filter(fact -> fact.kind() == FactKind.MIGRATION) + .map(AutomationRuntimeFamilyCatalog.SchemaFact::identity) + .toList()) + .contains("catalog-installation:1004", "catalog-installation:1005") + .noneMatch(identity -> identity.contains(":1004:") || identity.contains(":1005:")); + for (String version : List.of("1004", "1005")) { + String script = + version.equals("1004") + ? "V1004__automation_owner_runtime_family_catalog.sql" + : "V1005__automation_catalog_view_options.sql"; + assertThat(current.catalog().schemaFacts()) + .anySatisfy( + fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); + assertThat(fact.identity()).isEqualTo("catalog-installation:" + version); + assertThat(fact.definitionDigest()) + .isEqualTo( + AutomationRuntimeFamilyCatalog.sha256( + script.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + }); + } + migration(f.source, f.schema, f.history, null).validate(); + } + } + + @Test + void bothExactSuccessfulCatalogInstallationsAreRequired() throws Exception { + for (String version : List.of("1004", "1005")) { + for (String change : List.of("success=false", "script='wrong_catalog_installation.sql'")) { + try (Fixture f = fixture(null)) { + Request read = request(); + f.owner().read(read); + String snapshots = f.catalogRows("automation_runtime_family_catalog_snapshot"); + f.dsl.execute("UPDATE " + f.history + " SET " + change + " WHERE version=?", version); + assertThatThrownBy(() -> f.owner().readExact(read)) + .hasMessageContaining("No durable Automation catalog epoch"); + assertThatThrownBy(() -> f.owner().read(read)) + .hasMessageContaining("No durable Automation catalog epoch"); + assertThatThrownBy(() -> f.owner().read(request())) + .hasMessageContaining("No durable Automation catalog epoch"); + assertThat(f.catalogRows("automation_runtime_family_catalog_snapshot")) + .isEqualTo(snapshots); + } + } + } + } + private static Request request() { return new Request(UUID.randomUUID(), "test"); } @@ -524,6 +664,15 @@ AutomationRuntimeFamilyCatalogRepository owner() { return new AutomationRuntimeFamilyCatalogRepository(dsl, manager, schema, "test"); } + String catalogRows(String source) { + return dsl.fetchSingle( + "SELECT coalesce(jsonb_agg(row_json ORDER BY row_json::text),'[]'::jsonb)::text" + + " FROM (SELECT to_jsonb(t) AS row_json FROM (SELECT * FROM " + + source + + ") t) retained_rows") + .get(0, String.class); + } + long count(String table) { return dsl.fetchSingle("SELECT count(*) FROM " + table).get(0, Long.class); } @@ -555,7 +704,9 @@ List historyRows(boolean excludeNew) { "SELECT to_jsonb(h)::text FROM " + history + " h" - + (excludeNew ? " WHERE version IS DISTINCT FROM '1004'" : "") + + (excludeNew + ? " WHERE version IS DISTINCT FROM '1004' AND version IS DISTINCT FROM '1005'" + : "") + " ORDER BY installed_rank") .getValues(0, String.class); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogCodec.java index a371cab369..b217f2f327 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogCodec.java @@ -1,18 +1,12 @@ package net.firedevops.firemud.common.automation; import com.google.protobuf.ByteString; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.UUID; import net.firedevops.firemud.automationscripting.v1.ReadAutomationRuntimeFamilyCatalogRequest; import net.firedevops.firemud.automationscripting.v1.ReadAutomationRuntimeFamilyCatalogResponse; import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Evidence; import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogFraming; /** Purpose-specific closed framing; no compatibility, generic parser or numeric fallback. */ public final class AutomationRuntimeFamilyCatalogCodec { @@ -22,24 +16,31 @@ public final class AutomationRuntimeFamilyCatalogCodec { private static final int REQUEST_V1 = 0x41435231; private static final int EVIDENCE_V1 = 0x41434531; + private static final RuntimeFamilyCatalogFraming FRAMING = + new RuntimeFamilyCatalogFraming( + MAX_REQUEST_BYTES, + MAX_RESPONSE_BYTES, + AutomationRuntimeFamilyCatalog.MAX_CATALOG_BYTES, + "Frame bound exceeded", + "Invalid field bound"); + private AutomationRuntimeFamilyCatalogCodec() {} public static byte[] requestBytes(Request request) { - return encode( - out -> { - out.writeInt(REQUEST_V1); - uuid(out, request.readRequestId()); - bytes(out, request.targetNamespace().getBytes(StandardCharsets.US_ASCII)); - }); + return FRAMING.requestBytes(REQUEST_V1, request.readRequestId(), request.targetNamespace()); } public static Request requestFromStored(byte[] bytes) { - try (var in = input(bytes, MAX_REQUEST_BYTES)) { - if (in.readInt() != REQUEST_V1) throw new IllegalArgumentException("Unsupported read schema"); - Request result = new Request(uuid(in), new String(bytes(in, 63), StandardCharsets.US_ASCII)); - if (in.available() != 0 || !Arrays.equals(bytes, requestBytes(result))) { - throw new IllegalArgumentException("Noncanonical Automation catalog request"); - } + try { + var frame = + FRAMING.readRequest( + bytes, + REQUEST_V1, + AutomationRuntimeFamilyCatalog::requireUuid, + "Noncanonical Automation catalog request"); + Request result = new Request(frame.requestId(), frame.namespace()); + RuntimeFamilyCatalogFraming.requireCanonical( + bytes, requestBytes(result), "Noncanonical Automation catalog request"); return result; } catch (IOException invalid) { throw new IllegalArgumentException("Incomplete Automation catalog request", invalid); @@ -47,36 +48,31 @@ public static Request requestFromStored(byte[] bytes) { } public static byte[] evidenceBytes(Evidence evidence) { - byte[] result = - encode( - out -> { - out.writeInt(EVIDENCE_V1); - bytes(out, requestBytes(evidence.request())); - uuid(out, evidence.snapshotId()); - bytes(out, evidence.catalog().digest().getBytes(StandardCharsets.US_ASCII)); - bytes(out, evidence.catalog().exactBytes()); - }); - if (result.length > MAX_RESPONSE_BYTES) - throw new IllegalArgumentException("Oversized complete catalog evidence"); - return result; + return FRAMING.evidenceBytes( + EVIDENCE_V1, + requestBytes(evidence.request()), + evidence.snapshotId(), + evidence.catalog().digest(), + evidence.catalog().exactBytes(), + "Oversized complete catalog evidence"); } public static Evidence evidenceFromStored(byte[] bytes) { - try (var in = input(bytes, MAX_RESPONSE_BYTES)) { - if (in.readInt() != EVIDENCE_V1) - throw new IllegalArgumentException("Unsupported evidence schema"); - Request request = requestFromStored(bytes(in, MAX_REQUEST_BYTES)); - UUID snapshotId = uuid(in); - String digest = new String(bytes(in, 71), StandardCharsets.US_ASCII); - AutomationRuntimeFamilyCatalog catalog = - AutomationRuntimeFamilyCatalog.fromStored( - bytes(in, AutomationRuntimeFamilyCatalog.MAX_CATALOG_BYTES)); - Evidence result = new Evidence(request, snapshotId, catalog); - if (in.available() != 0 - || !digest.equals(catalog.digest()) - || !Arrays.equals(bytes, evidenceBytes(result))) { + try { + var frame = + FRAMING.readEvidence( + bytes, + EVIDENCE_V1, + AutomationRuntimeFamilyCatalog::requireUuid, + "Changed/noncanonical catalog evidence"); + Request request = requestFromStored(frame.request()); + var catalog = AutomationRuntimeFamilyCatalog.fromStored(frame.catalog()); + Evidence result = new Evidence(request, frame.snapshotId(), catalog); + if (!frame.digest().equals(catalog.digest())) { throw new IllegalArgumentException("Changed/noncanonical catalog evidence"); } + RuntimeFamilyCatalogFraming.requireCanonical( + bytes, evidenceBytes(result), "Changed/noncanonical catalog evidence"); return result; } catch (IOException invalid) { throw new IllegalArgumentException("Incomplete Automation catalog evidence", invalid); @@ -126,48 +122,4 @@ public static Evidence fromResponse( throw new IllegalArgumentException("Changed catalog read correlation"); return result; } - - private static DataInputStream input(byte[] value, int maximum) { - if (value == null || value.length == 0 || value.length > maximum) - throw new IllegalArgumentException("Frame bound exceeded"); - return new DataInputStream(new ByteArrayInputStream(value)); - } - - private static byte[] bytes(DataInputStream in, int maximum) throws IOException { - int length = in.readInt(); - if (length < 0 || length > maximum || length > in.available()) - throw new IllegalArgumentException("Invalid field bound"); - return in.readNBytes(length); - } - - private static void bytes(DataOutputStream out, byte[] value) throws IOException { - out.writeInt(value.length); - out.write(value); - } - - private static UUID uuid(DataInputStream in) throws IOException { - UUID result = new UUID(in.readLong(), in.readLong()); - AutomationRuntimeFamilyCatalog.requireUuid(result); - return result; - } - - private static void uuid(DataOutputStream out, UUID value) throws IOException { - out.writeLong(value.getMostSignificantBits()); - out.writeLong(value.getLeastSignificantBits()); - } - - private interface Encoder { - void write(DataOutputStream out) throws IOException; - } - - private static byte[] encode(Encoder encoder) { - try (var buffer = new ByteArrayOutputStream(); - var out = new DataOutputStream(buffer)) { - encoder.write(out); - out.flush(); - return buffer.toByteArray(); - } catch (IOException impossible) { - throw new IllegalStateException("Memory frame encoding failed", impossible); - } - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogCodec.java index e5468ec88f..a8106a8c04 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogCodec.java @@ -1,16 +1,10 @@ package net.firedevops.firemud.common.entity; import com.google.protobuf.ByteString; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.UUID; import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Evidence; import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogFraming; import net.firedevops.firemud.entitymanagement.v1.ReadEntityRuntimeFamilyCatalogRequest; import net.firedevops.firemud.entitymanagement.v1.ReadEntityRuntimeFamilyCatalogResponse; @@ -21,23 +15,31 @@ public final class EntityRuntimeFamilyCatalogCodec { private static final int REQUEST_V1 = 0x45435231; private static final int EVIDENCE_V1 = 0x45434531; + private static final RuntimeFamilyCatalogFraming FRAMING = + new RuntimeFamilyCatalogFraming( + MAX_REQUEST_BYTES, + MAX_RESPONSE_BYTES, + EntityRuntimeFamilyCatalog.MAX_CATALOG_BYTES, + "Frame bound exceeded", + "Invalid field bound"); + private EntityRuntimeFamilyCatalogCodec() {} public static byte[] requestBytes(Request request) { - return encode( - out -> { - out.writeInt(REQUEST_V1); - uuid(out, request.readRequestId()); - bytes(out, request.targetNamespace().getBytes(StandardCharsets.US_ASCII)); - }); + return FRAMING.requestBytes(REQUEST_V1, request.readRequestId(), request.targetNamespace()); } public static Request requestFromStored(byte[] bytes) { - try (var in = input(bytes, MAX_REQUEST_BYTES)) { - if (in.readInt() != REQUEST_V1) throw new IllegalArgumentException("Unsupported read schema"); - Request result = new Request(uuid(in), new String(bytes(in, 63), StandardCharsets.US_ASCII)); - if (in.available() != 0 || !Arrays.equals(bytes, requestBytes(result))) - throw new IllegalArgumentException("Noncanonical Entity catalog request"); + try { + var frame = + FRAMING.readRequest( + bytes, + REQUEST_V1, + EntityRuntimeFamilyCatalog::requireUuid, + "Noncanonical Entity catalog request"); + Request result = new Request(frame.requestId(), frame.namespace()); + RuntimeFamilyCatalogFraming.requireCanonical( + bytes, requestBytes(result), "Noncanonical Entity catalog request"); return result; } catch (IOException invalid) { throw new IllegalArgumentException("Incomplete Entity catalog request", invalid); @@ -45,35 +47,31 @@ public static Request requestFromStored(byte[] bytes) { } public static byte[] evidenceBytes(Evidence evidence) { - byte[] result = - encode( - out -> { - out.writeInt(EVIDENCE_V1); - bytes(out, requestBytes(evidence.request())); - uuid(out, evidence.snapshotId()); - bytes(out, evidence.catalog().digest().getBytes(StandardCharsets.US_ASCII)); - bytes(out, evidence.catalog().exactBytes()); - }); - if (result.length > MAX_RESPONSE_BYTES) - throw new IllegalArgumentException("Oversized complete catalog evidence"); - return result; + return FRAMING.evidenceBytes( + EVIDENCE_V1, + requestBytes(evidence.request()), + evidence.snapshotId(), + evidence.catalog().digest(), + evidence.catalog().exactBytes(), + "Oversized complete catalog evidence"); } public static Evidence evidenceFromStored(byte[] bytes) { - try (var in = input(bytes, MAX_RESPONSE_BYTES)) { - if (in.readInt() != EVIDENCE_V1) - throw new IllegalArgumentException("Unsupported evidence schema"); - Request request = requestFromStored(bytes(in, MAX_REQUEST_BYTES)); - UUID snapshotId = uuid(in); - String digest = new String(bytes(in, 71), StandardCharsets.US_ASCII); - var catalog = - EntityRuntimeFamilyCatalog.fromStored( - bytes(in, EntityRuntimeFamilyCatalog.MAX_CATALOG_BYTES)); - Evidence result = new Evidence(request, snapshotId, catalog); - if (in.available() != 0 - || !digest.equals(catalog.digest()) - || !Arrays.equals(bytes, evidenceBytes(result))) + try { + var frame = + FRAMING.readEvidence( + bytes, + EVIDENCE_V1, + EntityRuntimeFamilyCatalog::requireUuid, + "Changed/noncanonical catalog evidence"); + Request request = requestFromStored(frame.request()); + var catalog = EntityRuntimeFamilyCatalog.fromStored(frame.catalog()); + Evidence result = new Evidence(request, frame.snapshotId(), catalog); + if (!frame.digest().equals(catalog.digest())) { throw new IllegalArgumentException("Changed/noncanonical catalog evidence"); + } + RuntimeFamilyCatalogFraming.requireCanonical( + bytes, evidenceBytes(result), "Changed/noncanonical catalog evidence"); return result; } catch (IOException invalid) { throw new IllegalArgumentException("Incomplete Entity catalog evidence", invalid); @@ -121,48 +119,4 @@ public static Evidence fromResponse( throw new IllegalArgumentException("Changed catalog read correlation"); return result; } - - private static DataInputStream input(byte[] value, int maximum) { - if (value == null || value.length == 0 || value.length > maximum) - throw new IllegalArgumentException("Frame bound exceeded"); - return new DataInputStream(new ByteArrayInputStream(value)); - } - - private static byte[] bytes(DataInputStream in, int maximum) throws IOException { - int length = in.readInt(); - if (length < 0 || length > maximum || length > in.available()) - throw new IllegalArgumentException("Invalid field bound"); - return in.readNBytes(length); - } - - private static void bytes(DataOutputStream out, byte[] value) throws IOException { - out.writeInt(value.length); - out.write(value); - } - - private static UUID uuid(DataInputStream in) throws IOException { - UUID result = new UUID(in.readLong(), in.readLong()); - EntityRuntimeFamilyCatalog.requireUuid(result); - return result; - } - - private static void uuid(DataOutputStream out, UUID value) throws IOException { - out.writeLong(value.getMostSignificantBits()); - out.writeLong(value.getLeastSignificantBits()); - } - - private interface Encoder { - void write(DataOutputStream out) throws IOException; - } - - private static byte[] encode(Encoder encoder) { - try (var buffer = new ByteArrayOutputStream(); - var out = new DataOutputStream(buffer)) { - encoder.write(out); - out.flush(); - return buffer.toByteArray(); - } catch (IOException impossible) { - throw new IllegalStateException("Memory frame encoding failed", impossible); - } - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogFraming.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogFraming.java new file mode 100644 index 0000000000..60846530b4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogFraming.java @@ -0,0 +1,163 @@ +package net.firedevops.firemud.common.runtimecatalog; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.UUID; +import java.util.function.Consumer; + +/** + * Internal framing shared only by the four foreign-owner runtime-family catalog codecs. Public for + * those separate packages; it defines no new wire format, domain schema or compatibility parser. + * Owner codecs retain their magic values, domain parsing, digest and correlation checks. + */ +public final class RuntimeFamilyCatalogFraming { + private final int maximumRequestBytes; + private final int maximumResponseBytes; + private final int maximumCatalogBytes; + private final String frameBoundMessage; + private final String fieldBoundMessage; + + public RuntimeFamilyCatalogFraming( + int maximumRequestBytes, + int maximumResponseBytes, + int maximumCatalogBytes, + String frameBoundMessage, + String fieldBoundMessage) { + this.maximumRequestBytes = maximumRequestBytes; + this.maximumResponseBytes = maximumResponseBytes; + this.maximumCatalogBytes = maximumCatalogBytes; + this.frameBoundMessage = frameBoundMessage; + this.fieldBoundMessage = fieldBoundMessage; + } + + public byte[] requestBytes(int magic, UUID requestId, String namespace) { + return encode( + out -> { + out.writeInt(magic); + uuid(out, requestId); + bytes(out, namespace.getBytes(StandardCharsets.US_ASCII)); + }); + } + + public RequestFrame readRequest( + byte[] value, int magic, Consumer validateUuid, String noncanonicalMessage) + throws IOException { + try (var in = input(value, maximumRequestBytes)) { + if (in.readInt() != magic) throw new IllegalArgumentException("Unsupported read schema"); + UUID requestId = uuid(in, validateUuid); + String namespace = new String(bytes(in, 63), StandardCharsets.US_ASCII); + requireEnd(in, noncanonicalMessage); + return new RequestFrame(requestId, namespace); + } + } + + public byte[] evidenceBytes( + int magic, + byte[] request, + UUID snapshotId, + String digest, + byte[] catalog, + String oversizedMessage) { + byte[] result = + encode( + out -> { + out.writeInt(magic); + bytes(out, request); + uuid(out, snapshotId); + bytes(out, digest.getBytes(StandardCharsets.US_ASCII)); + bytes(out, catalog); + }); + if (result.length > maximumResponseBytes) throw new IllegalArgumentException(oversizedMessage); + return result; + } + + public EvidenceFrame readEvidence( + byte[] value, int magic, Consumer validateUuid, String noncanonicalMessage) + throws IOException { + try (var in = input(value, maximumResponseBytes)) { + if (in.readInt() != magic) throw new IllegalArgumentException("Unsupported evidence schema"); + byte[] request = bytes(in, maximumRequestBytes); + UUID snapshotId = uuid(in, validateUuid); + String digest = new String(bytes(in, 71), StandardCharsets.US_ASCII); + byte[] catalog = bytes(in, maximumCatalogBytes); + requireEnd(in, noncanonicalMessage); + return new EvidenceFrame(request, snapshotId, digest, catalog); + } + } + + public static void requireCanonical(byte[] original, byte[] reencoded, String message) { + if (!Arrays.equals(original, reencoded)) throw new IllegalArgumentException(message); + } + + public record RequestFrame(UUID requestId, String namespace) {} + + public record EvidenceFrame(byte[] request, UUID snapshotId, String digest, byte[] catalog) { + public EvidenceFrame { + request = request.clone(); + catalog = catalog.clone(); + } + + @Override + public byte[] request() { + return request.clone(); + } + + @Override + public byte[] catalog() { + return catalog.clone(); + } + } + + private DataInputStream input(byte[] value, int maximum) { + if (value == null || value.length == 0 || value.length > maximum) + throw new IllegalArgumentException(frameBoundMessage); + return new DataInputStream(new ByteArrayInputStream(value)); + } + + private byte[] bytes(DataInputStream in, int maximum) throws IOException { + int length = in.readInt(); + if (length < 0 || length > maximum || length > in.available()) + throw new IllegalArgumentException(fieldBoundMessage); + return in.readNBytes(length); + } + + private static void bytes(DataOutputStream out, byte[] value) throws IOException { + out.writeInt(value.length); + out.write(value); + } + + private static UUID uuid(DataInputStream in, Consumer validateUuid) throws IOException { + UUID result = new UUID(in.readLong(), in.readLong()); + validateUuid.accept(result); + return result; + } + + private static void uuid(DataOutputStream out, UUID value) throws IOException { + out.writeLong(value.getMostSignificantBits()); + out.writeLong(value.getLeastSignificantBits()); + } + + private static void requireEnd(DataInputStream in, String message) throws IOException { + if (in.available() != 0) throw new IllegalArgumentException(message); + } + + private interface Encoder { + void write(DataOutputStream out) throws IOException; + } + + private static byte[] encode(Encoder encoder) { + try (var buffer = new ByteArrayOutputStream(); + var out = new DataOutputStream(buffer)) { + encoder.write(out); + out.flush(); + return buffer.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException("Memory frame encoding failed", impossible); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogCodec.java index 9e29a09983..5767d65ebc 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogCodec.java @@ -1,14 +1,8 @@ package net.firedevops.firemud.common.social; import com.google.protobuf.ByteString; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.UUID; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogFraming; import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Evidence; import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Request; import net.firedevops.firemud.socialgroups.v1.ReadSocialRuntimeFamilyCatalogRequest; @@ -21,26 +15,31 @@ public final class SocialRuntimeFamilyCatalogCodec { private static final int REQUEST_V1 = 0x53435231; private static final int EVIDENCE_V1 = 0x53434531; + private static final RuntimeFamilyCatalogFraming FRAMING = + new RuntimeFamilyCatalogFraming( + MAX_REQUEST_BYTES, + MAX_RESPONSE_BYTES, + SocialRuntimeFamilyCatalog.MAX_CATALOG_BYTES, + "Social catalog frame bound exceeded", + "Invalid Social catalog field bound"); + private SocialRuntimeFamilyCatalogCodec() {} public static byte[] requestBytes(Request request) { - return encode( - out -> { - out.writeInt(REQUEST_V1); - uuid(out, request.readRequestId()); - bytes(out, request.targetNamespace().getBytes(StandardCharsets.US_ASCII)); - }); + return FRAMING.requestBytes(REQUEST_V1, request.readRequestId(), request.targetNamespace()); } public static Request requestFromStored(byte[] bytes) { - try (var in = input(bytes, MAX_REQUEST_BYTES)) { - if (in.readInt() != REQUEST_V1) throw new IllegalArgumentException("Unsupported read schema"); - UUID id = uuid(in); - String namespace = new String(bytes(in, 63), StandardCharsets.US_ASCII); - Request result = new Request(id, namespace); - if (in.available() != 0 || !Arrays.equals(bytes, requestBytes(result))) { - throw new IllegalArgumentException("Noncanonical Social catalog request"); - } + try { + var frame = + FRAMING.readRequest( + bytes, + REQUEST_V1, + SocialRuntimeFamilyCatalog::requireUuid, + "Noncanonical Social catalog request"); + Request result = new Request(frame.requestId(), frame.namespace()); + RuntimeFamilyCatalogFraming.requireCanonical( + bytes, requestBytes(result), "Noncanonical Social catalog request"); return result; } catch (IOException invalid) { throw new IllegalArgumentException("Incomplete Social catalog request", invalid); @@ -48,37 +47,31 @@ public static Request requestFromStored(byte[] bytes) { } public static byte[] evidenceBytes(Evidence evidence) { - byte[] result = - encode( - out -> { - out.writeInt(EVIDENCE_V1); - bytes(out, requestBytes(evidence.request())); - uuid(out, evidence.snapshotId()); - bytes(out, evidence.catalog().digest().getBytes(StandardCharsets.US_ASCII)); - bytes(out, evidence.catalog().exactBytes()); - }); - if (result.length > MAX_RESPONSE_BYTES) { - throw new IllegalArgumentException("Oversized complete Social catalog evidence"); - } - return result; + return FRAMING.evidenceBytes( + EVIDENCE_V1, + requestBytes(evidence.request()), + evidence.snapshotId(), + evidence.catalog().digest(), + evidence.catalog().exactBytes(), + "Oversized complete Social catalog evidence"); } public static Evidence evidenceFromStored(byte[] bytes) { - try (var in = input(bytes, MAX_RESPONSE_BYTES)) { - if (in.readInt() != EVIDENCE_V1) - throw new IllegalArgumentException("Unsupported evidence schema"); - Request request = requestFromStored(bytes(in, MAX_REQUEST_BYTES)); - UUID snapshotId = uuid(in); - String digest = new String(bytes(in, 71), StandardCharsets.US_ASCII); - SocialRuntimeFamilyCatalog catalog = - SocialRuntimeFamilyCatalog.fromStored( - bytes(in, SocialRuntimeFamilyCatalog.MAX_CATALOG_BYTES)); - Evidence result = new Evidence(request, snapshotId, catalog); - if (in.available() != 0 - || !digest.equals(catalog.digest()) - || !Arrays.equals(bytes, evidenceBytes(result))) { + try { + var frame = + FRAMING.readEvidence( + bytes, + EVIDENCE_V1, + SocialRuntimeFamilyCatalog::requireUuid, + "Changed/noncanonical Social catalog evidence"); + Request request = requestFromStored(frame.request()); + var catalog = SocialRuntimeFamilyCatalog.fromStored(frame.catalog()); + Evidence result = new Evidence(request, frame.snapshotId(), catalog); + if (!frame.digest().equals(catalog.digest())) { throw new IllegalArgumentException("Changed/noncanonical Social catalog evidence"); } + RuntimeFamilyCatalogFraming.requireCanonical( + bytes, evidenceBytes(result), "Changed/noncanonical Social catalog evidence"); return result; } catch (IOException invalid) { throw new IllegalArgumentException("Incomplete Social catalog evidence", invalid); @@ -131,50 +124,4 @@ public static Evidence fromResponse( } return result; } - - private static DataInputStream input(byte[] value, int maximum) { - if (value == null || value.length == 0 || value.length > maximum) { - throw new IllegalArgumentException("Social catalog frame bound exceeded"); - } - return new DataInputStream(new ByteArrayInputStream(value)); - } - - private static byte[] bytes(DataInputStream in, int maximum) throws IOException { - int length = in.readInt(); - if (length < 0 || length > maximum || length > in.available()) { - throw new IllegalArgumentException("Invalid Social catalog field bound"); - } - return in.readNBytes(length); - } - - private static void bytes(DataOutputStream out, byte[] value) throws IOException { - out.writeInt(value.length); - out.write(value); - } - - private static UUID uuid(DataInputStream in) throws IOException { - UUID result = new UUID(in.readLong(), in.readLong()); - SocialRuntimeFamilyCatalog.requireUuid(result); - return result; - } - - private static void uuid(DataOutputStream out, UUID value) throws IOException { - out.writeLong(value.getMostSignificantBits()); - out.writeLong(value.getLeastSignificantBits()); - } - - private interface Encoder { - void write(DataOutputStream out) throws IOException; - } - - private static byte[] encode(Encoder encoder) { - try (var buffer = new ByteArrayOutputStream(); - var out = new DataOutputStream(buffer)) { - encoder.write(out); - out.flush(); - return buffer.toByteArray(); - } catch (IOException impossible) { - throw new IllegalStateException("Memory frame encoding failed", impossible); - } - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java index 7019b99386..1afc14ad89 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java @@ -1,14 +1,8 @@ package net.firedevops.firemud.common.world; import com.google.protobuf.ByteString; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.UUID; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogFraming; import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Evidence; import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Request; import net.firedevops.firemud.worldmanagement.v1.ReadWorldRuntimeFamilyCatalogRequest; @@ -21,27 +15,31 @@ public final class WorldRuntimeFamilyCatalogCodec { private static final int REQUEST_V1 = 0x57435231; private static final int EVIDENCE_V1 = 0x57434531; + private static final RuntimeFamilyCatalogFraming FRAMING = + new RuntimeFamilyCatalogFraming( + MAX_REQUEST_BYTES, + MAX_RESPONSE_BYTES, + WorldRuntimeFamilyCatalog.MAX_CATALOG_BYTES, + "Frame bound exceeded", + "Invalid field bound"); + private WorldRuntimeFamilyCatalogCodec() {} public static byte[] requestBytes(Request request) { - return encode( - out -> { - out.writeInt(REQUEST_V1); - uuid(out, request.readRequestId()); - bytes(out, request.targetNamespace().getBytes(StandardCharsets.US_ASCII)); - }); + return FRAMING.requestBytes(REQUEST_V1, request.readRequestId(), request.targetNamespace()); } public static Request requestFromStored(byte[] bytes) { - try (var in = input(bytes, MAX_REQUEST_BYTES)) { - if (in.readInt() != REQUEST_V1) throw new IllegalArgumentException("Unsupported read schema"); - UUID id = uuid(in); - byte[] namespaceBytes = bytes(in, 63); - String namespace = new String(namespaceBytes, StandardCharsets.US_ASCII); - Request result = new Request(id, namespace); - if (in.available() != 0 || !Arrays.equals(bytes, requestBytes(result))) { - throw new IllegalArgumentException("Noncanonical World catalog request"); - } + try { + var frame = + FRAMING.readRequest( + bytes, + REQUEST_V1, + WorldRuntimeFamilyCatalog::requireUuid, + "Noncanonical World catalog request"); + Request result = new Request(frame.requestId(), frame.namespace()); + RuntimeFamilyCatalogFraming.requireCanonical( + bytes, requestBytes(result), "Noncanonical World catalog request"); return result; } catch (IOException invalid) { throw new IllegalArgumentException("Incomplete World catalog request", invalid); @@ -49,36 +47,31 @@ public static Request requestFromStored(byte[] bytes) { } public static byte[] evidenceBytes(Evidence evidence) { - byte[] result = - encode( - out -> { - out.writeInt(EVIDENCE_V1); - bytes(out, requestBytes(evidence.request())); - uuid(out, evidence.snapshotId()); - bytes(out, evidence.catalog().digest().getBytes(StandardCharsets.US_ASCII)); - bytes(out, evidence.catalog().exactBytes()); - }); - if (result.length > MAX_RESPONSE_BYTES) - throw new IllegalArgumentException("Oversized complete catalog evidence"); - return result; + return FRAMING.evidenceBytes( + EVIDENCE_V1, + requestBytes(evidence.request()), + evidence.snapshotId(), + evidence.catalog().digest(), + evidence.catalog().exactBytes(), + "Oversized complete catalog evidence"); } public static Evidence evidenceFromStored(byte[] bytes) { - try (var in = input(bytes, MAX_RESPONSE_BYTES)) { - if (in.readInt() != EVIDENCE_V1) - throw new IllegalArgumentException("Unsupported evidence schema"); - Request request = requestFromStored(bytes(in, MAX_REQUEST_BYTES)); - UUID snapshotId = uuid(in); - String digest = new String(bytes(in, 71), StandardCharsets.US_ASCII); - WorldRuntimeFamilyCatalog catalog = - WorldRuntimeFamilyCatalog.fromStored( - bytes(in, WorldRuntimeFamilyCatalog.MAX_CATALOG_BYTES)); - Evidence result = new Evidence(request, snapshotId, catalog); - if (in.available() != 0 - || !digest.equals(catalog.digest()) - || !Arrays.equals(bytes, evidenceBytes(result))) { + try { + var frame = + FRAMING.readEvidence( + bytes, + EVIDENCE_V1, + WorldRuntimeFamilyCatalog::requireUuid, + "Changed/noncanonical catalog evidence"); + Request request = requestFromStored(frame.request()); + var catalog = WorldRuntimeFamilyCatalog.fromStored(frame.catalog()); + Evidence result = new Evidence(request, frame.snapshotId(), catalog); + if (!frame.digest().equals(catalog.digest())) { throw new IllegalArgumentException("Changed/noncanonical catalog evidence"); } + RuntimeFamilyCatalogFraming.requireCanonical( + bytes, evidenceBytes(result), "Changed/noncanonical catalog evidence"); return result; } catch (IOException invalid) { throw new IllegalArgumentException("Incomplete World catalog evidence", invalid); @@ -128,48 +121,4 @@ public static Evidence fromResponse( throw new IllegalArgumentException("Changed catalog read correlation"); return result; } - - private static DataInputStream input(byte[] value, int maximum) { - if (value == null || value.length == 0 || value.length > maximum) - throw new IllegalArgumentException("Frame bound exceeded"); - return new DataInputStream(new ByteArrayInputStream(value)); - } - - private static byte[] bytes(DataInputStream in, int maximum) throws IOException { - int length = in.readInt(); - if (length < 0 || length > maximum || length > in.available()) - throw new IllegalArgumentException("Invalid field bound"); - return in.readNBytes(length); - } - - private static void bytes(DataOutputStream out, byte[] value) throws IOException { - out.writeInt(value.length); - out.write(value); - } - - private static UUID uuid(DataInputStream in) throws IOException { - UUID result = new UUID(in.readLong(), in.readLong()); - WorldRuntimeFamilyCatalog.requireUuid(result); - return result; - } - - private static void uuid(DataOutputStream out, UUID value) throws IOException { - out.writeLong(value.getMostSignificantBits()); - out.writeLong(value.getLeastSignificantBits()); - } - - private interface Encoder { - void write(DataOutputStream out) throws IOException; - } - - private static byte[] encode(Encoder encoder) { - try (var buffer = new ByteArrayOutputStream(); - var out = new DataOutputStream(buffer)) { - encoder.write(out); - out.flush(); - return buffer.toByteArray(); - } catch (IOException impossible) { - throw new IllegalStateException("Memory frame encoding failed", impossible); - } - } } diff --git a/services/entity-management-service/src/main/resources/db/migration/V1026__entity_catalog_snapshot_exact_frames.sql b/services/entity-management-service/src/main/resources/db/migration/V1026__entity_catalog_snapshot_exact_frames.sql new file mode 100644 index 0000000000..eef8ed6991 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1026__entity_catalog_snapshot_exact_frames.sql @@ -0,0 +1,133 @@ +-- Retain V1025, every historical epoch and snapshot byte-for-byte. Tightened routines +-- change the schema census, so this forward installation explicitly seals the next epoch. +-- Its own post-transaction Flyway row uses the same honest marker/installed-row boundary +-- as V1025; no checksum or successful installation is invented inside this transaction. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION entity_runtime_family_catalog_installed() RETURNS BOOLEAN LANGUAGE SQL STABLE +SET search_path = "${serviceSchema}", pg_catalog AS $$ + SELECT EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1025' AND script='V1025__entity_owner_runtime_family_catalog.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1026' AND script='V1026__entity_catalog_snapshot_exact_frames.sql' AND success); +$$; + +CREATE OR REPLACE FUNCTION entity_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE v_families JSONB; v_facts JSONB; +BEGIN + IF p_epoch IS NULL OR p_epoch<=0 THEN + RAISE EXCEPTION 'Positive Entity catalog epoch required' USING ERRCODE='23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM entity_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM entity_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed Entity schema family' USING ERRCODE='23514'; + END IF; + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name, + 'component',component_name,'role',family_role,'stateClass',state_class, + 'freshDisposition',fresh_disposition) ORDER BY family_id COLLATE "C") + INTO v_families FROM entity_runtime_family_classification; + + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname,jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::TEXT + FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1025' AND version IS DISTINCT FROM '1026' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1025','V1025__entity_owner_runtime_family_catalog.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1026','V1026__entity_catalog_snapshot_exact_frames.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + IF jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 THEN + RAISE EXCEPTION 'Complete Entity catalog exceeds source bounds' USING ERRCODE='23514'; + END IF; + RETURN convert_to(jsonb_build_object('schema','entity-runtime-family-catalog/v1', + 'owner','entity-management-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts)::TEXT,'UTF8'); +END; +$$; + +CREATE OR REPLACE FUNCTION entity_runtime_catalog_snapshot_guard() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE v_epoch entity_runtime_family_catalog_epoch%ROWTYPE; + v_request BYTEA; v_evidence BYTEA; +BEGIN + SELECT * INTO STRICT v_epoch FROM entity_runtime_family_catalog_epoch ORDER BY catalog_epoch DESC LIMIT 1; + IF NEW.catalog_epoch<>v_epoch.catalog_epoch OR NEW.catalog_digest<>v_epoch.catalog_digest + OR entity_runtime_family_catalog_bytes(v_epoch.catalog_epoch)<>v_epoch.catalog_bytes + OR NOT entity_runtime_family_catalog_installed() THEN + RAISE EXCEPTION 'Entity runtime catalog changed; new owner epoch required' USING ERRCODE='23514'; + END IF; + v_request := decode('45435231','hex') || uuid_send(NEW.read_request_id) + || int4send(octet_length(convert_to(NEW.target_namespace,'UTF8'))) || convert_to(NEW.target_namespace,'UTF8'); + v_evidence := decode('45434531','hex') || int4send(octet_length(v_request)) || v_request + || uuid_send(NEW.snapshot_id) || int4send(octet_length(convert_to(v_epoch.catalog_digest,'UTF8'))) + || convert_to(v_epoch.catalog_digest,'UTF8') || int4send(octet_length(v_epoch.catalog_bytes)) || v_epoch.catalog_bytes; + IF NEW.request_bytes<>v_request OR NEW.evidence_bytes<>v_evidence THEN + RAISE EXCEPTION 'Entity snapshot must bind complete exact request and evidence' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +INSERT INTO entity_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT next_epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM (SELECT coalesce(max(catalog_epoch),0)+1 AS next_epoch FROM entity_runtime_family_catalog_epoch) next +CROSS JOIN LATERAL (SELECT entity_runtime_family_catalog_bytes(next.next_epoch) AS bytes) seal; +-- [jooq ignore stop] diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index 75f0a23473..43d047cf1c 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -505,7 +505,7 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( .extracting(AppliedMigration::version) .containsExactly( "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016", "1017", - "1018", "1019", "1020", "1021", "1022", "1023", "1024", "1025"); + "1018", "1019", "1020", "1021", "1022", "1023", "1024", "1025", "1026"); assertThat(successorHistory) .extracting(AppliedMigration::script) .containsExactly( @@ -527,7 +527,8 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( "V1022__preseeded_runtime_actor_projection.sql", "V1023__player_created_runtime_projection.sql", "V1024__ordinary_account_uuid_owner.sql", - "V1025__entity_owner_runtime_family_catalog.sql"); + "V1025__entity_owner_runtime_family_catalog.sql", + "V1026__entity_catalog_snapshot_exact_frames.sql"); assertThat(successorHistory).extracting(AppliedMigration::checksum).doesNotContainNull(); try (Connection connection = connectToSchema(schema)) { diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index 276f2c49d9..5c8df7ca95 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -642,7 +642,7 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020", "1021", - "1022", "1023", "1024", "1025"); + "1022", "1023", "1024", "1025", "1026"); assertThat(flyway.info().applied()) .filteredOn(migration -> migration.getVersion() != null) .extracting(migration -> migration.getScript()) @@ -672,9 +672,10 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { "V1022__preseeded_runtime_actor_projection.sql", "V1023__player_created_runtime_projection.sql", "V1024__ordinary_account_uuid_owner.sql", - "V1025__entity_owner_runtime_family_catalog.sql"); + "V1025__entity_owner_runtime_family_catalog.sql", + "V1026__entity_catalog_snapshot_exact_frames.sql"); assertThat(flyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1025")); + .isEqualTo(MigrationVersion.fromVersion("1026")); assertThat(flyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); @@ -748,7 +749,7 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020", "1021", - "1022", "1023", "1024", "1025"); + "1022", "1023", "1024", "1025", "1026"); assertThat(upgradedHistory) .extracting(MigrationHistoryEntry::script) .containsExactly( @@ -777,7 +778,8 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro "V1022__preseeded_runtime_actor_projection.sql", "V1023__player_created_runtime_projection.sql", "V1024__ordinary_account_uuid_owner.sql", - "V1025__entity_owner_runtime_family_catalog.sql"); + "V1025__entity_owner_runtime_family_catalog.sql", + "V1026__entity_catalog_snapshot_exact_frames.sql"); assertThat(upgradedHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); try (Connection connection = connectToMigrationSchema(); @@ -1043,7 +1045,7 @@ private void migrateLegacySchemaToLatest() { assertThat(upgradeFlyway.getConfiguration().isOutOfOrder()).isFalse(); upgradeFlyway.migrate(); assertThat(upgradeFlyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1025")); + .isEqualTo(MigrationVersion.fromVersion("1026")); assertThat(upgradeFlyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java index 57808515fb..bde5e9b6cc 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java @@ -137,7 +137,7 @@ void upgradesActualEntity1014ParentWithoutChangingRetainedActorOrRosterRows() { DSLContext upgradedDsl = DSL.using(parentDataSource, SQLDialect.POSTGRES); assertThat(migrationHistory(upgradedDsl).subList(0, parentHistory.size())) .containsExactlyElementsOf(parentHistory); - assertThat(migrationVersions(upgradedDsl)).contains("1017").last().isEqualTo("1025"); + assertThat(migrationVersions(upgradedDsl)).contains("1017").last().isEqualTo("1026"); assertThat(retainedParentRows(upgradedDsl, character, snapshot)) .containsExactlyElementsOf(retainedRows); assertThat( @@ -183,7 +183,7 @@ void binaryGuardUpgradePreservesCreatedRowsHistoryAndTerminalReplay() throws Exc assertThat(migrationHistory(retainedDsl).subList(0, historyBefore.size())) .containsExactlyElementsOf(historyBefore); - assertThat(migrationVersions(retainedDsl)).last().isEqualTo("1025"); + assertThat(migrationVersions(retainedDsl)).last().isEqualTo("1026"); assertThat(retainedDsl.fetch(retainedRowsSql).getValues(0, String.class)) .containsExactlyElementsOf(before); assertThat(retainedRepository.settle(retainedProof, null)).isEqualTo(terminal); @@ -256,7 +256,7 @@ void upgradesRetainedV1016CreatedActorBeforeQuarantineWithoutChangingRows() thro migrate(retainedDataSource, retainedSchema, null); - assertThat(migrationVersions(retainedDsl)).contains("1017").last().isEqualTo("1025"); + assertThat(migrationVersions(retainedDsl)).contains("1017").last().isEqualTo("1026"); assertThat(retainedRow(retainedDsl, "characters", "character_uuid", characterId)) .isEqualTo(actorBefore); assertThat( diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java index 214f5de03d..d52d0043f7 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java @@ -106,7 +106,7 @@ void seedLegacyRowsBeforeV1011() { dsl.fetchSingle( "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") .get(0, String.class)) - .isEqualTo("1025"); + .isEqualTo("1026"); } @AfterEach diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java index b9c0c29a1b..982e797205 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -6,6 +6,7 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.LinkedHashMap; import java.util.List; @@ -14,6 +15,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog; +import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Evidence; import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.FactKind; import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.FreshDisposition; import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Request; @@ -45,7 +47,7 @@ * not genuine upstream custody/PKI, FRESH materialization or cross-owner completeness proof. * Repository reconstruction proves durable readback, not operating-system process-death recovery. */ -@Testcontainers +@Testcontainers(disabledWithoutDocker = false) @Timeout(value = 3, unit = TimeUnit.MINUTES) @SuppressWarnings("resource") class EntityRuntimeFamilyCatalogPostgresIntegrationTest { @@ -59,7 +61,7 @@ class EntityRuntimeFamilyCatalogPostgresIntegrationTest { void actualCombinedMigrationsYieldExactCompleteCensusIncludingOwnInfrastructure() { try (var f = fixture(null, HISTORY)) { var catalog = f.owner().read(request()).catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat(catalog.catalogEpoch()).isEqualTo(2); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -109,7 +111,7 @@ void actualCombinedMigrationsYieldExactCompleteCensusIncludingOwnInfrastructure( assertThat( f.dsl .fetchSingle( - "SELECT catalog_bytes=entity_runtime_family_catalog_bytes(catalog_epoch) FROM entity_runtime_family_catalog_epoch") + "SELECT catalog_bytes=entity_runtime_family_catalog_bytes(catalog_epoch) FROM entity_runtime_family_catalog_epoch ORDER BY catalog_epoch DESC LIMIT 1") .get(0, Boolean.class)) .isTrue(); assertThat( @@ -122,7 +124,7 @@ void actualCombinedMigrationsYieldExactCompleteCensusIncludingOwnInfrastructure( .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020", - "1021", "1022", "1023", "1024", "1025"); + "1021", "1022", "1023", "1024", "1025", "1026"); } } @@ -345,7 +347,7 @@ void additiveUpgradePreservesPopulatedActorHolderAuthoredReplayAuditSagaAndHisto .fetch( "SELECT to_jsonb(t)::text||':'||xmin::text FROM " + HISTORY - + " t WHERE version IS DISTINCT FROM '1025' ORDER BY installed_rank") + + " t WHERE version IS DISTINCT FROM '1025' AND version IS DISTINCT FROM '1026' ORDER BY installed_rank") .getValues(0, String.class)) .containsExactlyInAnyOrderElementsOf(history); f.owner().read(request()); @@ -421,6 +423,8 @@ void missingTableClassificationAndMigrationChangesInvalidateWithoutRewritingEvid "INSERT INTO entity_runtime_family_classification VALUES ('npcs.version_id_extra','npcs','version_id_extra','SOURCE','NOT_PAYLOAD','AUTHORED_SOURCE_ONLY')", "UPDATE " + HISTORY + " SET checksum=checksum+1 WHERE version='1'", "UPDATE " + HISTORY + " SET success=false WHERE version='1025'", + "UPDATE " + HISTORY + " SET success=false WHERE version='1026'", + "UPDATE " + HISTORY + " SET script='other.sql' WHERE version='1026'", "UPDATE " + HISTORY + " SET script='other.sql' WHERE version='1025'")) { try (var f = fixture(null, HISTORY)) { var read = request(); @@ -450,11 +454,11 @@ void validNewClassificationRequiresExplicitNewOwnerEpochAndInvalidatesOldRequest .isInstanceOf(EntityRuntimeFamilyCatalogRepository.CatalogConflictException.class); f.dsl.execute( "INSERT INTO entity_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 2,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM (SELECT entity_runtime_family_catalog_bytes(2) AS bytes) revised"); + + " SELECT 3,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM (SELECT entity_runtime_family_catalog_bytes(3) AS bytes) revised"); assertThatThrownBy(() -> f.owner().read(read)) .isInstanceOf(EntityRuntimeFamilyCatalogRepository.CatalogConflictException.class); var revised = f.owner().read(request()); - assertThat(revised.catalog().catalogEpoch()).isEqualTo(2); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(3); assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); assertThat( f.dsl @@ -466,6 +470,122 @@ void validNewClassificationRequiresExplicitNewOwnerEpochAndInvalidatesOldRequest } } + @Test + void viewAuthorizationAndMaterializedOptionsInvalidateTheSealWithoutResampling() { + for (String alteration : + List.of( + "ALTER VIEW catalog_view SET (security_invoker=true)", + "ALTER VIEW catalog_view SET (security_barrier=true)", + "ALTER MATERIALIZED VIEW catalog_materialized SET (fillfactor=70)")) { + try (var f = fixture("1024", HISTORY)) { + f.dsl.execute("CREATE VIEW catalog_view AS SELECT id FROM characters"); + f.dsl.execute( + "CREATE MATERIALIZED VIEW catalog_materialized AS SELECT id FROM characters WITH NO DATA"); + migration(f.source, f.schema, HISTORY, null).load().migrate(); + var read = request(); + var original = f.owner().read(read); + var retained = f.rows("entity_runtime_family_catalog_snapshot"); + f.dsl.execute(alteration); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(EntityRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(read)) + .isInstanceOf(EntityRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(request())) + .isInstanceOf(EntityRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.rows("entity_runtime_family_catalog_snapshot")).isEqualTo(retained); + assertThat( + f.dsl + .fetchSingle( + "SELECT evidence_bytes FROM entity_runtime_family_catalog_snapshot WHERE read_request_id=?", + read.readRequestId()) + .get(0, byte[].class)) + .isEqualTo(EntityRuntimeFamilyCatalogCodec.evidenceBytes(original)); + } + } + } + + @Test + void forwardFrameGuardUpgradeRetainsOldEpochSnapshotAndHistoryWithoutResampling() { + try (var f = fixture("1025", HISTORY)) { + var read = request(); + var original = f.owner().read(read); + assertThat(original.catalog().catalogEpoch()).isEqualTo(1); + var epochs = f.rows("entity_runtime_family_catalog_epoch"); + var snapshots = f.rows("entity_runtime_family_catalog_snapshot"); + var history = f.rows(HISTORY); + migration(f.source, f.schema, HISTORY, null).load().migrate(); + assertThat(f.rows("entity_runtime_family_catalog_epoch")).containsAll(epochs).hasSize(2); + assertThat(f.rows("entity_runtime_family_catalog_snapshot")).isEqualTo(snapshots); + assertThat(f.rows(HISTORY)).containsAll(history).hasSize(history.size() + 1); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(EntityRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(read)) + .isInstanceOf(EntityRuntimeFamilyCatalogRepository.CatalogConflictException.class); + var current = f.owner().read(request()); + assertThat(current.catalog().catalogEpoch()).isEqualTo(2); + assertThat(current.catalog().digest()).isNotEqualTo(original.catalog().digest()); + assertThat(current.catalog().schemaFacts()) + .anyMatch( + fact -> + fact.kind() == FactKind.MIGRATION + && fact.identity().equals("catalog-installation:1026")); + migration(f.source, f.schema, HISTORY, null).load().validate(); + } + } + + @Test + void directSqlPoisonFramesRefuseWithoutConsumingRequestIdentity() { + try (var f = fixture(null, HISTORY)) { + var catalog = f.owner().read(request()).catalog(); + for (int mismatch = 0; mismatch < 6; mismatch++) { + var read = request(); + var snapshot = UUID.randomUUID(); + var evidence = new Evidence(read, snapshot, catalog); + byte[] requestBytes = EntityRuntimeFamilyCatalogCodec.requestBytes(read); + byte[] evidenceBytes = EntityRuntimeFamilyCatalogCodec.evidenceBytes(evidence); + switch (mismatch) { + case 0 -> requestBytes = "arbitrary".getBytes(StandardCharsets.US_ASCII); + case 1 -> requestBytes = EntityRuntimeFamilyCatalogCodec.requestBytes(request()); + case 2 -> + requestBytes = + EntityRuntimeFamilyCatalogCodec.requestBytes( + new Request(read.readRequestId(), "other")); + case 3 -> evidenceBytes = "arbitrary".getBytes(StandardCharsets.US_ASCII); + case 4 -> + evidenceBytes = + EntityRuntimeFamilyCatalogCodec.evidenceBytes( + new Evidence(request(), snapshot, catalog)); + case 5 -> + evidenceBytes = + EntityRuntimeFamilyCatalogCodec.evidenceBytes( + new Evidence(read, UUID.randomUUID(), catalog)); + default -> throw new AssertionError("Unknown poison vector"); + } + byte[] poisonedRequest = requestBytes; + byte[] poisonedEvidence = evidenceBytes; + long before = f.count("entity_runtime_family_catalog_snapshot"); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO entity_runtime_family_catalog_snapshot(read_request_id,target_namespace,request_bytes,request_digest,snapshot_id,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)", + read.readRequestId(), + read.targetNamespace(), + poisonedRequest, + EntityRuntimeFamilyCatalog.sha256(poisonedRequest), + snapshot, + catalog.catalogEpoch(), + catalog.digest(), + poisonedEvidence, + EntityRuntimeFamilyCatalog.sha256(poisonedEvidence))) + .hasMessageContaining("complete exact request and evidence"); + assertThat(f.count("entity_runtime_family_catalog_snapshot")).isEqualTo(before); + var committed = f.owner().read(read); + assertThat(f.owner().readExact(read)).isEqualTo(committed); + assertThat(f.count("entity_runtime_family_catalog_snapshot")).isEqualTo(before + 1); + } + } + } + @Test void metadataEpochAndSnapshotsRemainImmutableAndWrongSealCannotBeInserted() { try (var f = fixture(null, HISTORY)) { @@ -489,7 +609,7 @@ void metadataEpochAndSnapshotsRemainImmutableAndWrongSealCannotBeInserted() { () -> f.dsl.execute( "INSERT INTO entity_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 2,catalog_bytes,catalog_digest FROM entity_runtime_family_catalog_epoch WHERE catalog_epoch=1")) + + " SELECT 3,catalog_bytes,catalog_digest FROM entity_runtime_family_catalog_epoch WHERE catalog_epoch=2")) .hasMessageContaining("exact classified installed schema"); } } diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java index 7b261deb8a..17025e58cd 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java @@ -700,12 +700,7 @@ private static Store store(PostgreSQLContainer postgres, String service) { .placeholders(Map.of("serviceSchema", schema)) .locations(migrations(service)); if ("world-management".equals(service)) { - flyway.locations( - migrations(service), - "filesystem:" - + Path.of("../common-saga/src/main/resources/db/migration/saga") - .toAbsolutePath() - .normalize()); + flyway.locations(migrations(service), migrations("common-saga") + "/saga"); } flyway.load().migrate(); return new Store( @@ -718,7 +713,10 @@ private static String migrations(String service) { current != null; current = current.getParent()) { Path target = - current.resolve("services/" + service + "-service/src/main/resources/db/migration"); + current.resolve( + "services/" + + ("common-saga".equals(service) ? service : service + "-service") + + "/src/main/resources/db/migration"); if (Files.isDirectory(target)) return "filesystem:" + target; } throw new IllegalStateException("Owner migration directory unavailable"); diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java index 0dd54dee76..d050148d04 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java @@ -839,11 +839,7 @@ private WorldStore worldStore() { .table("flyway_schema_history_world_management") .placeholders(Map.of("serviceSchema", schema)) .locations( - migrationLocation("world-management"), - "filesystem:" - + Path.of("../common-saga/src/main/resources/db/migration/saga") - .toAbsolutePath() - .normalize()) + migrationLocation("world-management"), migrationLocation("common-saga") + "/saga") .load() .migrate(); var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); @@ -1000,7 +996,7 @@ private static TransactionTemplate transaction(DataSourceTransactionManager mana } private static String migrationLocation(String service) { - var directoryName = service + "-service"; + var directoryName = "common-saga".equals(service) ? service : service + "-service"; var current = Path.of("").toAbsolutePath(); while (current != null) { var migrations = diff --git a/services/social-groups-service/src/main/resources/db/migration/V1005__social_catalog_view_options.sql b/services/social-groups-service/src/main/resources/db/migration/V1005__social_catalog_view_options.sql new file mode 100644 index 0000000000..a896f9b55f --- /dev/null +++ b/services/social-groups-service/src/main/resources/db/migration/V1005__social_catalog_view_options.sql @@ -0,0 +1,128 @@ +-- Retain V1004 and all historical epochs, snapshots and migration rows byte-for-byte. +-- View and materialized-view options are part of the installed definition seal. +-- Flyway records each migration's own row after its transaction; distinct stable markers +-- bind the catalog installations without fabricating checksums or successful history rows. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION social_runtime_family_catalog_installed() RETURNS BOOLEAN +LANGUAGE SQL STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ + SELECT EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1004' AND script='V1004__social_owner_runtime_family_catalog.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1005' AND script='V1005__social_catalog_view_options.sql' AND success); +$$; + +CREATE OR REPLACE FUNCTION social_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE +SET search_path = "${serviceSchema}", pg_catalog +AS $$ +DECLARE + v_families JSONB; + v_facts JSONB; +BEGIN + IF p_epoch IS NULL OR p_epoch <= 0 THEN + RAISE EXCEPTION 'Positive Social catalog epoch required' USING ERRCODE='23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM social_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM social_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed Social schema family' USING ERRCODE='23514'; + END IF; + + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name, + 'component',component_name,'role',family_role,'freshDisposition',fresh_disposition, + 'targetOwner',target_owner) ORDER BY family_id COLLATE "C") + INTO v_families FROM social_runtime_family_classification; + + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname, + jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::TEXT + FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1004' AND version IS DISTINCT FROM '1005' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1004','V1004__social_owner_runtime_family_catalog.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1005','V1005__social_catalog_view_options.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + + IF jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 THEN + RAISE EXCEPTION 'Complete Social catalog exceeds source bounds' USING ERRCODE='23514'; + END IF; + RETURN convert_to(jsonb_build_object('schema','social-runtime-family-catalog/v1', + 'owner','social-groups-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts, + 'unimplementedContracts',jsonb_build_array( + 'CHAT_RESTRICTION_AND_REVISION', + 'DIRECTIONAL_BLOCK_LIFECYCLE', + 'ENTITY_ESCROW_REFERENCE_FAMILIES', + 'GAMEPLAY_WHISPER_NAMESPACE_SCOPE', + 'SAFETY_EVIDENCE_AND_CONTENT_FREE_RECEIPTS', + 'SOCIAL_PLAYER_STANDING_OWNER', + 'SOCIAL_SAGA_ADOPTER_CLASSIFICATION'))::TEXT,'UTF8'); +END; +$$; + +-- Replace every affected routine before sealing the next exact owner-local epoch. +INSERT INTO social_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT next_epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM (SELECT coalesce(max(catalog_epoch),0)+1 AS next_epoch FROM social_runtime_family_catalog_epoch) next +CROSS JOIN LATERAL (SELECT social_runtime_family_catalog_bytes(next.next_epoch) AS bytes) seal; +-- [jooq ignore stop] diff --git a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java index ecd0186d3b..eee813c9be 100644 --- a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -41,7 +41,7 @@ /** * Actual installed Social/Saga PostgreSQL proof; caller identity is controlled, not physical mTLS. */ -@Testcontainers +@Testcontainers(disabledWithoutDocker = false) @SuppressWarnings("resource") class SocialRuntimeFamilyCatalogPostgresIntegrationTest { private static final List RETAINED_TABLES = @@ -108,7 +108,7 @@ void actualCombinedSocialSagaCensusClassifiesEveryInstalledTableWithoutRowInfere throws Exception { try (Fixture f = fixture(null)) { var catalog = f.owner().read(request()).catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat(catalog.catalogEpoch()).isEqualTo(2); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -173,7 +173,7 @@ void actualCombinedSocialSagaCensusClassifiesEveryInstalledTableWithoutRowInfere f.dsl .fetchSingle( "SELECT catalog_bytes = social_runtime_family_catalog_bytes(catalog_epoch)" - + " FROM social_runtime_family_catalog_epoch") + + " FROM social_runtime_family_catalog_epoch ORDER BY catalog_epoch DESC LIMIT 1") .get(0, Boolean.class)) .isTrue(); } @@ -260,16 +260,16 @@ void forwardMigrationRetainsPopulatedSocialSagaRowsAndEveryPriorHistoryRow() thr List historyBefore = f.historyRows(); migrate(f, null); assertThat(f.retainedRows()).isEqualTo(rowsBefore); - assertThat(f.historyRowsExcluding("1004")).isEqualTo(historyBefore); + assertThat(f.historyRowsExcluding("1004", "1005")).isEqualTo(historyBefore); var catalog = f.owner().read(request()).catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat(catalog.catalogEpoch()).isEqualTo(2); assertThat(catalog.families()) .anySatisfy( family -> assertThat(family.freshDisposition()) .isEqualTo(FreshDisposition.ENTITY_VALUE_OWNERSHIP_DRIFT_BLOCKING)); assertThat(f.retainedRows()).isEqualTo(rowsBefore); - assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(1); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(2); assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); } } @@ -283,7 +283,7 @@ void emptyUnclassifiedNewTableInvalidatesExactAndNewReadsWithoutResampling() thr assertThat(f.count("unknown_runtime_family")).isZero(); assertThatThrownBy(() -> f.owner().readExact(retained)).hasMessageContaining("Unclassified"); assertThatThrownBy(() -> f.owner().read(request())).hasMessageContaining("Unclassified"); - assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(1); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(2); assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); } } @@ -325,7 +325,7 @@ void schemaColumnConstraintTriggerRoutineAndRemovalChangesCannotResampleUnderSam assertThatThrownBy(() -> f.owner().readExact(retained)) .isInstanceOf(RuntimeException.class); assertThatThrownBy(() -> f.owner().read(request())).isInstanceOf(RuntimeException.class); - assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(1); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(2); assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); } } @@ -352,7 +352,7 @@ void changedClassificationMigrationHistoryOrUnsuccessfulInstallationRefusesOldSo .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().read(request())) .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); - assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(1); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(2); assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); } try (Fixture f = fixture(null)) { @@ -419,9 +419,9 @@ void immutableMetadataAndSnapshotsRefuseMutationAndIncorrectEpochSeals() throws () -> f.dsl.execute( "INSERT INTO social_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 2,catalog_bytes,catalog_digest FROM social_runtime_family_catalog_epoch WHERE catalog_epoch=1")) + + " SELECT 3,catalog_bytes,catalog_digest FROM social_runtime_family_catalog_epoch WHERE catalog_epoch=2")) .hasMessageContaining("exact classified installed schema"); - assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(1); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(2); } } @@ -460,6 +460,145 @@ void actualProducerReturnsCompleteCorrelatedEvidenceWithoutCallerContextOrRuntim } } + @Test + void viewSecurityOptionsInvalidateReadRetryAndFreshCaptureWithoutChangingRetainedEvidence() + throws Exception { + for (String option : List.of("security_invoker", "security_barrier")) { + try (Fixture f = fixture("1003")) { + // Install the real view before either catalog migration so its initial options are sealed. + f.dsl.execute("CREATE VIEW catalog_security_probe AS SELECT 1 AS id"); + migrate(f, null); + Request read = request(); + var original = f.owner().read(read); + assertThat(original.catalog().catalogEpoch()).isEqualTo(2); + assertThat(original.catalog().schemaFacts()) + .anySatisfy( + fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.VIEW); + assertThat(fact.identity()).isEqualTo("catalog_security_probe"); + assertThat(fact.definitionDigest()) + .isEqualTo( + f.dsl + .fetchSingle( + "SELECT 'sha256:'||encode(sha256(convert_to(" + + "jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::text,'UTF8')),'hex')" + + " FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace" + + " WHERE n.nspname=? AND c.relname='catalog_security_probe'", + f.schema) + .get(0, String.class)); + }); + assertThat(f.owner().read(read)).isEqualTo(original); + assertThat(f.owner().readExact(read)).isEqualTo(original); + String definition = + f.dsl + .fetchSingle("SELECT pg_get_viewdef('catalog_security_probe'::regclass,true)") + .get(0, String.class); + String epochs = f.catalogRows("social_runtime_family_catalog_epoch"); + String snapshots = f.catalogRows("social_runtime_family_catalog_snapshot"); + f.dsl.execute("ALTER VIEW catalog_security_probe SET (" + option + "=true)"); + assertThat( + f.dsl + .fetchSingle("SELECT pg_get_viewdef('catalog_security_probe'::regclass,true)") + .get(0, String.class)) + .isEqualTo(definition); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(read)) + .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(request())) + .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.catalogRows("social_runtime_family_catalog_epoch")).isEqualTo(epochs); + assertThat(f.catalogRows("social_runtime_family_catalog_snapshot")).isEqualTo(snapshots); + } + } + } + + @Test + void catalogViewOptionsUpgradeRetainsV1004DataHistoryEpochAndSnapshot() throws Exception { + try (Fixture f = fixture("1004")) { + f.dsl.execute( + "INSERT INTO guilds(tenant_id,name,owner_account_id) VALUES (7,'retained',?::uuid)", + "10000000-0000-4000-8000-000000000001"); + f.dsl.execute("INSERT INTO saga_instance(saga_name,state) VALUES ('retained','PENDING')"); + Map rows = f.retainedRows(); + Request read = request(); + var original = f.owner().read(read); + assertThat(original.catalog().catalogEpoch()).isEqualTo(1); + List history = f.historyRows(); + String epoch = f.catalogRows("social_runtime_family_catalog_epoch"); + String snapshots = f.catalogRows("social_runtime_family_catalog_snapshot"); + migrate(f, null); + for (var retained : rows.entrySet()) + assertThat(f.jsonRows(retained.getKey())).isEqualTo(retained.getValue()); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(h)::text FROM " + + f.history + + " h WHERE version IS DISTINCT FROM '1005' ORDER BY installed_rank") + .getValues(0, String.class)) + .isEqualTo(history); + assertThat(f.catalogRows("social_runtime_family_catalog_epoch WHERE catalog_epoch=1")) + .isEqualTo(epoch); + assertThat(f.catalogRows("social_runtime_family_catalog_snapshot")).isEqualTo(snapshots); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(2); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(read)) + .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.catalogRows("social_runtime_family_catalog_snapshot")).isEqualTo(snapshots); + var current = f.owner().read(request()); + assertThat(current.catalog().catalogEpoch()).isEqualTo(2); + assertThat(current.catalog().digest()).isNotEqualTo(original.catalog().digest()); + assertThat(f.owner().readExact(current.request())).isEqualTo(current); + assertThat( + current.catalog().schemaFacts().stream() + .filter(fact -> fact.kind() == FactKind.MIGRATION) + .map(SocialRuntimeFamilyCatalog.SchemaFact::identity) + .toList()) + .contains("catalog-installation:1004", "catalog-installation:1005") + .noneMatch(identity -> identity.contains(":1004:") || identity.contains(":1005:")); + for (String version : List.of("1004", "1005")) { + String script = + version.equals("1004") + ? "V1004__social_owner_runtime_family_catalog.sql" + : "V1005__social_catalog_view_options.sql"; + assertThat(current.catalog().schemaFacts()) + .anySatisfy( + fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); + assertThat(fact.identity()).isEqualTo("catalog-installation:" + version); + assertThat(fact.definitionDigest()) + .isEqualTo( + SocialRuntimeFamilyCatalog.sha256( + script.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + }); + } + flyway(f.source, f.schema, f.history, null).validate(); + } + } + + @Test + void bothExactSuccessfulCatalogInstallationsAreRequired() throws Exception { + for (String version : List.of("1004", "1005")) { + for (String change : List.of("success=false", "script='wrong_catalog_installation.sql'")) { + try (Fixture f = fixture(null)) { + Request read = request(); + f.owner().read(read); + String snapshots = f.catalogRows("social_runtime_family_catalog_snapshot"); + f.dsl.execute("UPDATE " + f.history + " SET " + change + " WHERE version=?", version); + assertThatThrownBy(() -> f.owner().readExact(read)) + .hasMessageContaining("No durable Social catalog epoch"); + assertThatThrownBy(() -> f.owner().read(read)) + .hasMessageContaining("No durable Social catalog epoch"); + assertThatThrownBy(() -> f.owner().read(request())) + .hasMessageContaining("No durable Social catalog epoch"); + assertThat(f.catalogRows("social_runtime_family_catalog_snapshot")).isEqualTo(snapshots); + } + } + } + } + private static Request request() { return new Request(UUID.randomUUID(), "test"); } @@ -533,6 +672,15 @@ SocialRuntimeFamilyCatalogRepository owner() { return new SocialRuntimeFamilyCatalogRepository(dsl, manager, schema, "test"); } + String catalogRows(String source) { + return dsl.fetchSingle( + "SELECT coalesce(jsonb_agg(row_json ORDER BY row_json::text),'[]'::jsonb)::text" + + " FROM (SELECT to_jsonb(t) AS row_json FROM (SELECT * FROM " + + source + + ") t) retained_rows") + .get(0, String.class); + } + long count(String table) { return dsl.fetchSingle("SELECT count(*) FROM " + table).get(0, Long.class); } @@ -560,12 +708,13 @@ List historyRows() { .getValues(0, String.class); } - List historyRowsExcluding(String version) { + List historyRowsExcluding(String first, String second) { return dsl.fetch( "SELECT to_jsonb(h)::text FROM " + history - + " h WHERE version IS DISTINCT FROM ? ORDER BY installed_rank", - version) + + " h WHERE version IS DISTINCT FROM ? AND version IS DISTINCT FROM ? ORDER BY installed_rank", + first, + second) .getValues(0, String.class); } diff --git a/services/world-management-service/src/main/resources/db/migration/V1047__world_catalog_snapshot_exact_frames.sql b/services/world-management-service/src/main/resources/db/migration/V1047__world_catalog_snapshot_exact_frames.sql new file mode 100644 index 0000000000..754bc938a9 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1047__world_catalog_snapshot_exact_frames.sql @@ -0,0 +1,146 @@ +-- Retain V1046 and all historical epochs, snapshots and migration rows byte-for-byte. +-- Replacing census routines requires an explicit next epoch after every routine is installed. +-- Flyway records each migration's own row after its transaction; stable, distinct markers +-- bind those installations without inventing a checksum or successful history row. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION world_runtime_family_catalog_installed() RETURNS BOOLEAN +LANGUAGE SQL STABLE +SET search_path = "${serviceSchema}", pg_catalog +AS $$ + SELECT EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1046' AND script='V1046__world_owner_runtime_family_catalog.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1047' AND script='V1047__world_catalog_snapshot_exact_frames.sql' AND success); +$$; + +CREATE OR REPLACE FUNCTION world_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE +SET search_path = "${serviceSchema}", pg_catalog +AS $$ +DECLARE + v_families JSONB; + v_facts JSONB; +BEGIN + IF p_epoch IS NULL OR p_epoch <= 0 THEN + RAISE EXCEPTION 'Positive World catalog epoch required' USING ERRCODE = '23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM world_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM world_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed World schema family' USING ERRCODE = '23514'; + END IF; + + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name, + 'component',component_name,'role',family_role,'stateClass',state_class, + 'freshDisposition',fresh_disposition) ORDER BY family_id COLLATE "C") + INTO v_families FROM world_runtime_family_classification; + + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname, + jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::TEXT + FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1046' AND version IS DISTINCT FROM '1047' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1046','V1046__world_owner_runtime_family_catalog.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1047','V1047__world_catalog_snapshot_exact_frames.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + + IF jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 THEN + RAISE EXCEPTION 'Complete World catalog exceeds source bounds' USING ERRCODE = '23514'; + END IF; + RETURN convert_to(jsonb_build_object('schema','world-runtime-family-catalog/v1', + 'owner','world-management-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts)::TEXT,'UTF8'); +END; +$$; + +CREATE OR REPLACE FUNCTION world_runtime_catalog_snapshot_guard() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE + v_epoch world_runtime_family_catalog_epoch%ROWTYPE; + v_request BYTEA; + v_evidence BYTEA; +BEGIN + SELECT * INTO STRICT v_epoch FROM world_runtime_family_catalog_epoch ORDER BY catalog_epoch DESC LIMIT 1; + IF NEW.catalog_epoch<>v_epoch.catalog_epoch OR NEW.catalog_digest<>v_epoch.catalog_digest + OR world_runtime_family_catalog_bytes(v_epoch.catalog_epoch)<>v_epoch.catalog_bytes + OR NOT world_runtime_family_catalog_installed() THEN + RAISE EXCEPTION 'World runtime catalog changed; new owner epoch required' USING ERRCODE='23514'; + END IF; + v_request := decode('57435231','hex') || uuid_send(NEW.read_request_id) + || int4send(octet_length(convert_to(NEW.target_namespace,'UTF8'))) || convert_to(NEW.target_namespace,'UTF8'); + v_evidence := decode('57434531','hex') || int4send(octet_length(v_request)) || v_request + || uuid_send(NEW.snapshot_id) || int4send(octet_length(convert_to(v_epoch.catalog_digest,'UTF8'))) + || convert_to(v_epoch.catalog_digest,'UTF8') || int4send(octet_length(v_epoch.catalog_bytes)) || v_epoch.catalog_bytes; + IF NEW.request_bytes<>v_request OR NEW.evidence_bytes<>v_evidence THEN + RAISE EXCEPTION 'World snapshot must bind complete exact request and evidence' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; + +INSERT INTO world_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT next_epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM (SELECT coalesce(max(catalog_epoch),0)+1 AS next_epoch FROM world_runtime_family_catalog_epoch) next +CROSS JOIN LATERAL (SELECT world_runtime_family_catalog_bytes(next.next_epoch) AS bytes) seal; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java index c68197b89e..edf6f8d3a1 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java @@ -1443,6 +1443,25 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp var retainedRowsAtDefaultFrontierOriginalColumns = new LinkedHashMap<>(allRowsWithoutNewServerStamps(connection)); retainedRowsAtDefaultFrontierOriginalColumns.remove(HISTORY); + for (String addedCatalog : + List.of( + "world_runtime_family_classification", + "world_runtime_family_catalog_epoch", + "world_runtime_family_catalog_snapshot")) { + assertThat(retainedRowsAtDefaultFrontierOriginalColumns.remove(addedCatalog)) + .as("new additive catalog table %s is installed", addedCatalog) + .isNotNull(); + } + assertThat( + connection + .fetchSingle("SELECT count(*) FROM world_runtime_family_catalog_epoch") + .get(0, Long.class)) + .isEqualTo(2L); + assertThat( + connection + .fetchSingle("SELECT count(*) FROM world_runtime_family_catalog_snapshot") + .get(0, Long.class)) + .isZero(); assertThat(retainedRowsAtDefaultFrontierOriginalColumns) .as("all retained original row values and xmin from V1042.8 through the V1042.11 repairs") .isEqualTo(retainedRowsAt10428); @@ -3142,6 +3161,8 @@ private static List remainingVersions() { versions.add("1044"); versions.add("1044.1"); versions.add("1045"); + versions.add("1046"); + versions.add("1047"); return List.copyOf(versions); } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java index fd13782934..e8ddc57358 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java @@ -199,7 +199,7 @@ void forwardMigrationBindsSemanticReceiptDigestOnFreshAndUpgradedSchemas() throw probeCurrent.validate(); assertThat(probeCurrent.info().pending()).isEmpty(); - assertThat(latestVersion(upgradeDsl)).isEqualTo("1045"); + assertThat(latestVersion(upgradeDsl)).isEqualTo("1047"); assertThat(latestVersion(freshDsl)).isEqualTo(latestVersion(upgradeDsl)); assertThat(latestVersion(probeDsl)).isEqualTo(latestVersion(upgradeDsl)); assertThat(migrationHistory(upgradeDsl, "1012")).isEqualTo(history1012Before); @@ -210,12 +210,18 @@ void forwardMigrationBindsSemanticReceiptDigestOnFreshAndUpgradedSchemas() throw assertThat(migrationHistory(upgradeDsl, "1044")).isNotNull(); assertThat(migrationHistory(upgradeDsl, "1044.1")).isNotNull(); assertThat(migrationHistory(upgradeDsl, "1045")).isNotNull(); + assertThat(migrationHistory(upgradeDsl, "1046")).isNotNull(); + assertThat(migrationHistory(upgradeDsl, "1047")).isNotNull(); assertThat(migrationHistory(freshDsl, "1042.12")).isNotNull(); assertThat(migrationHistory(freshDsl, "1042.13")).isNotNull(); assertThat(migrationHistory(freshDsl, "1044")).isNotNull(); assertThat(migrationHistory(freshDsl, "1045")).isNotNull(); + assertThat(migrationHistory(freshDsl, "1046")).isNotNull(); + assertThat(migrationHistory(freshDsl, "1047")).isNotNull(); assertThat(migrationHistory(probeDsl, "1044")).isNotNull(); assertThat(migrationHistory(probeDsl, "1045")).isNotNull(); + assertThat(migrationHistory(probeDsl, "1046")).isNotNull(); + assertThat(migrationHistory(probeDsl, "1047")).isNotNull(); assertCanonicalInitialAdmissionHoldLifecycleGuard(upgradeDsl, upgradeSchema); assertCanonicalInitialAdmissionHoldLifecycleGuard(freshDsl, freshSchema); assertCanonicalInitialAdmissionHoldLifecycleGuard(probeDsl, probeSchema); @@ -337,7 +343,20 @@ private static void assertCanonicalInitialAdmissionHoldLifecycleGuard( private static void cloneProbeTables(DSLContext dsl, String sourceSchema, String probeSchema) { dsl.execute("CREATE SCHEMA " + DSL.name(probeSchema)); - for (String table : PROBE_TABLES) + // The latest catalog migration requires every installed World/Saga table to exist. + // Retain the controlled predicate-only clones, including every original positive table, + // and clone the remaining installed source/control/replay/Saga tables without row data. + // Flyway creates its own real configured history below; never clone migration rows. + List tables = + dsl.fetch( + "SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace" + + " WHERE n.nspname=? AND c.relkind IN ('r','p','f') AND c.relname<>?" + + " ORDER BY c.relname", + sourceSchema, + HISTORY) + .getValues(0, String.class); + assertThat(tables).containsAll(PROBE_TABLES); + for (String table : tables) dsl.execute( "CREATE TABLE " + DSL.name(probeSchema, table) diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java index 89966f1b2f..b845ff5784 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -7,12 +7,14 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Evidence; import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.FactKind; import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.FreshDisposition; import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Request; @@ -37,7 +39,7 @@ * RPC identity context; these cases do not prove live PKI, FRESH authorization or materialization. * No positive case is disabled when Docker is unavailable: Gameplay must obtain physical results. */ -@Testcontainers +@Testcontainers(disabledWithoutDocker = false) @SuppressWarnings("resource") class WorldRuntimeFamilyCatalogPostgresIntegrationTest { @Container @@ -73,7 +75,7 @@ void actualCompleteCurrentCensusIncludesEmptyRuntimeAndNonPayloadFamilies() thro try (Fixture f = fixture(null)) { var evidence = f.owner().read(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(1); + assertThat(catalog.catalogEpoch()).isEqualTo(2); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -130,7 +132,7 @@ void actualCompleteCurrentCensusIncludesEmptyRuntimeAndNonPayloadFamilies() thro f.dsl .fetchSingle( "SELECT catalog_bytes = world_runtime_family_catalog_bytes(catalog_epoch)" - + " FROM world_runtime_family_catalog_epoch") + + " FROM world_runtime_family_catalog_epoch ORDER BY catalog_epoch DESC LIMIT 1") .get(0, Boolean.class)) .isTrue(); } @@ -205,7 +207,7 @@ void additiveForwardMigrationRetainsLegacyPayloadAndPriorMigrationHistoryExactly assertThat( f.dsl .fetch( - "SELECT to_jsonb(h)::text FROM flyway_schema_history_world_management_service h WHERE version IS DISTINCT FROM '1046' ORDER BY installed_rank") + "SELECT to_jsonb(h)::text FROM flyway_schema_history_world_management_service h WHERE version IS DISTINCT FROM '1046' AND version IS DISTINCT FROM '1047' ORDER BY installed_rank") .getValues(0, String.class)) .isEqualTo(historyBefore); f.owner().read(request()); @@ -279,6 +281,56 @@ void schemaColumnRenameConstraintAndRoutineChangesCannotResampleUnderSameEpoch() } } + @Test + void installedViewAndMaterializedViewOptionsInvalidateTheSealWithoutResampling() + throws Exception { + for (String change : + List.of( + "ALTER VIEW catalog_option_probe SET (security_invoker=true)", + "ALTER VIEW catalog_option_probe SET (security_barrier=true)", + "ALTER MATERIALIZED VIEW catalog_materialized_probe SET (fillfactor=70)")) { + try (Fixture f = fixture("1045")) { + // Install controlled views before the genuine catalog migrations, so both epochs + // capture installed schema objects rather than a view added after sealing. + f.dsl.execute( + "CREATE VIEW catalog_option_probe WITH (security_invoker=false,security_barrier=false)" + + " AS SELECT id FROM world_event"); + f.dsl.execute( + "CREATE MATERIALIZED VIEW catalog_materialized_probe AS SELECT id FROM world_event"); + migration(f.source, f.schema, null).migrate(); + Request read = request(); + var original = f.owner().read(read); + assertThat(original.catalog().catalogEpoch()).isEqualTo(2); + assertThat(original.catalog().schemaFacts()) + .anyMatch( + fact -> + fact.kind() == FactKind.VIEW && fact.identity().equals("catalog_option_probe")) + .anyMatch( + fact -> + fact.kind() == FactKind.VIEW + && fact.identity().equals("catalog_materialized_probe")); + var snapshots = f.retainedRows("world_runtime_family_catalog_snapshot"); + var epochs = f.retainedRows("world_runtime_family_catalog_epoch"); + f.dsl.execute(change); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(read)) + .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(request())) + .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.retainedRows("world_runtime_family_catalog_snapshot")).isEqualTo(snapshots); + assertThat(f.retainedRows("world_runtime_family_catalog_epoch")).isEqualTo(epochs); + assertThat( + f.dsl + .fetchSingle( + "SELECT evidence_bytes FROM world_runtime_family_catalog_snapshot WHERE read_request_id=?", + read.readRequestId()) + .get(0, byte[].class)) + .isEqualTo(WorldRuntimeFamilyCatalogCodec.evidenceBytes(original)); + } + } + } + @Test void removalAndClassificationChangeAreExplicitlyInvalidating() throws Exception { try (Fixture f = fixture(null)) { @@ -300,7 +352,7 @@ void removalAndClassificationChangeAreExplicitlyInvalidating() throws Exception .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().read(request())) .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); - assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(1); + assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(2); } } @@ -324,6 +376,147 @@ void oldMigrationFactChangeInvalidatesTheSealAndMissingOwnerEpochNeverMeansCompl } } + @Test + void directSnapshotInsertRequiresBothSuccessfulExactCatalogMigrationRows() throws Exception { + try (Fixture f = fixture(null)) { + var catalog = f.owner().read(request()).catalog(); + for (String version : List.of("1046", "1047")) { + for (String column : List.of("success", "script")) { + Request read = request(); + var evidence = new Evidence(read, UUID.randomUUID(), catalog); + byte[] requestBytes = WorldRuntimeFamilyCatalogCodec.requestBytes(read); + byte[] evidenceBytes = WorldRuntimeFamilyCatalogCodec.evidenceBytes(evidence); + var original = + f.dsl.fetchSingle( + "SELECT success,script FROM flyway_schema_history_world_management_service WHERE version=?", + version); + f.dsl.execute( + "UPDATE flyway_schema_history_world_management_service SET " + + column + + "=? WHERE version=?", + column.equals("success") ? false : "other.sql", + version); + // These own rows use honest installation markers, so the installed-row guard must + // refuse even though the live census still matches the seal and all digests are valid. + assertThat( + f.dsl + .fetchSingle( + "SELECT world_runtime_family_catalog_bytes(?)=?", + catalog.catalogEpoch(), + catalog.exactBytes()) + .get(0, Boolean.class)) + .isTrue(); + long before = f.count("world_runtime_family_catalog_snapshot"); + assertThatThrownBy(() -> f.insertSnapshot(evidence, requestBytes, evidenceBytes)) + .hasMessageContaining("new owner epoch required"); + assertThat(f.count("world_runtime_family_catalog_snapshot")).isEqualTo(before); + assertThatThrownBy(() -> f.owner().read(read)) + .hasMessageContaining("No durable World catalog epoch"); + f.dsl.execute( + "UPDATE flyway_schema_history_world_management_service SET success=?,script=? WHERE version=?", + original.get("success", Boolean.class), + original.get("script", String.class), + version); + var committed = f.owner().read(read); + assertThat(f.owner().readExact(read)).isEqualTo(committed); + assertThat(f.count("world_runtime_family_catalog_snapshot")).isEqualTo(before + 1); + } + } + } + } + + @Test + void directSqlPoisonFramesRefuseWithoutConsumingRequestIdentity() throws Exception { + try (Fixture f = fixture(null)) { + var catalog = f.owner().read(request()).catalog(); + for (int mismatch = 0; mismatch < 9; mismatch++) { + Request read = request(); + var snapshot = UUID.randomUUID(); + var evidence = new Evidence(read, snapshot, catalog); + byte[] requestBytes = WorldRuntimeFamilyCatalogCodec.requestBytes(read); + byte[] evidenceBytes = WorldRuntimeFamilyCatalogCodec.evidenceBytes(evidence); + switch (mismatch) { + case 0 -> requestBytes = "arbitrary".getBytes(StandardCharsets.US_ASCII); + case 1 -> requestBytes = WorldRuntimeFamilyCatalogCodec.requestBytes(request()); + case 2 -> + requestBytes = + WorldRuntimeFamilyCatalogCodec.requestBytes( + new Request(read.readRequestId(), "other")); + case 3 -> evidenceBytes = "arbitrary".getBytes(StandardCharsets.US_ASCII); + case 4 -> + evidenceBytes = + WorldRuntimeFamilyCatalogCodec.evidenceBytes( + new Evidence(request(), snapshot, catalog)); + case 5 -> + evidenceBytes = + WorldRuntimeFamilyCatalogCodec.evidenceBytes( + new Evidence(read, UUID.randomUUID(), catalog)); + case 6 -> + evidenceBytes = + WorldRuntimeFamilyCatalogCodec.evidenceBytes( + new Evidence(new Request(read.readRequestId(), "other"), snapshot, catalog)); + case 7 -> { + int digestOffset = 4 + 4 + requestBytes.length + 16 + 4; + evidenceBytes[digestOffset + "sha256:".length()] ^= 1; + } + case 8 -> evidenceBytes[evidenceBytes.length - 1] ^= 1; + default -> throw new AssertionError("Unknown poison vector"); + } + byte[] poisonedRequest = requestBytes; + byte[] poisonedEvidence = evidenceBytes; + long before = f.count("world_runtime_family_catalog_snapshot"); + // Compute valid SHA-256 digests for the poisoned bytes to exercise the exact-frame + // trigger itself rather than merely the independent per-column digest CHECKs. + assertThatThrownBy(() -> f.insertSnapshot(evidence, poisonedRequest, poisonedEvidence)) + .hasMessageContaining("complete exact request and evidence"); + assertThat(f.count("world_runtime_family_catalog_snapshot")).isEqualTo(before); + var committed = f.owner().read(read); + assertThat(f.owner().readExact(read)).isEqualTo(committed); + assertThat(f.count("world_runtime_family_catalog_snapshot")).isEqualTo(before + 1); + } + } + } + + @Test + void forwardFrameGuardUpgradeRetainsOldEpochSnapshotAndHistoryWithoutResampling() + throws Exception { + try (Fixture f = fixture("1046")) { + Request read = request(); + var original = f.owner().read(read); + assertThat(original.catalog().catalogEpoch()).isEqualTo(1); + var epochs = f.retainedRows("world_runtime_family_catalog_epoch"); + var snapshots = f.retainedRows("world_runtime_family_catalog_snapshot"); + var history = f.retainedRows("flyway_schema_history_world_management_service"); + migration(f.source, f.schema, null).migrate(); + assertThat(f.retainedRows("world_runtime_family_catalog_epoch")) + .containsAll(epochs) + .hasSize(2); + assertThat(f.retainedRows("world_runtime_family_catalog_snapshot")).isEqualTo(snapshots); + assertThat(f.retainedRows("flyway_schema_history_world_management_service")) + .containsAll(history) + .hasSize(history.size() + 1); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(read)) + .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.retainedRows("world_runtime_family_catalog_snapshot")).isEqualTo(snapshots); + var current = f.owner().read(request()); + assertThat(current.catalog().catalogEpoch()).isEqualTo(2); + assertThat(current.catalog().digest()).isNotEqualTo(original.catalog().digest()); + assertThat(current.catalog().schemaFacts()) + .anyMatch( + fact -> + fact.kind() == FactKind.MIGRATION + && fact.identity().equals("catalog-installation:1046")) + .anyMatch( + fact -> + fact.kind() == FactKind.MIGRATION + && fact.identity().equals("catalog-installation:1047")); + assertThat(f.count("world_runtime_family_catalog_snapshot")).isEqualTo(2); + migration(f.source, f.schema, null).validate(); + } + } + @Test void explicitOwnerEpochAdvanceInvalidatesOldRequestsWithoutRewritingTheirEvidence() throws Exception { @@ -336,8 +529,8 @@ void explicitOwnerEpochAdvanceInvalidatesOldRequestsWithoutRewritingTheirEvidenc + " ('region_instance.name','region_instance','name','RUNTIME_PAYLOAD','S3','REQUIRED_TOPOLOGY')"); f.dsl.execute( "INSERT INTO world_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 2,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM" - + " (SELECT world_runtime_family_catalog_bytes(2) AS bytes) revised"); + + " SELECT 3,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM" + + " (SELECT world_runtime_family_catalog_bytes(3) AS bytes) revised"); assertThatThrownBy(() -> f.owner().readExact(read)) .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().read(read)) @@ -350,9 +543,9 @@ void explicitOwnerEpochAdvanceInvalidatesOldRequestsWithoutRewritingTheirEvidenc .get(0, byte[].class)) .isEqualTo(WorldRuntimeFamilyCatalogCodec.evidenceBytes(original)); var revised = f.owner().read(request()); - assertThat(revised.catalog().catalogEpoch()).isEqualTo(2); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(3); assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); - assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(2); + assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(3); } } @@ -382,7 +575,7 @@ void epochMetadataAndSnapshotsAreRetainedAndWrongSealsCannotBeInserted() throws () -> f.dsl.execute( "INSERT INTO world_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 2,catalog_bytes,catalog_digest FROM world_runtime_family_catalog_epoch WHERE catalog_epoch=1")) + + " SELECT 3,catalog_bytes,catalog_digest FROM world_runtime_family_catalog_epoch WHERE catalog_epoch=2")) .hasMessageContaining("exact classified installed schema"); } } @@ -454,6 +647,30 @@ WorldRuntimeFamilyCatalogRepository owner() { return new WorldRuntimeFamilyCatalogRepository(dsl, manager, schema, "test"); } + void insertSnapshot(Evidence evidence, byte[] requestBytes, byte[] evidenceBytes) { + dsl.execute( + "INSERT INTO world_runtime_family_catalog_snapshot" + + "(read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," + + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)", + evidence.request().readRequestId(), + evidence.request().targetNamespace(), + requestBytes, + WorldRuntimeFamilyCatalog.sha256(requestBytes), + evidence.snapshotId(), + evidence.catalog().catalogEpoch(), + evidence.catalog().digest(), + evidenceBytes, + WorldRuntimeFamilyCatalog.sha256(evidenceBytes)); + } + + List retainedRows(String table) { + return dsl.fetch( + "SELECT to_jsonb(t)::text||':'||xmin::text AS value FROM " + + table + + " t ORDER BY value") + .getValues(0, String.class); + } + long count(String table) { return dsl.fetchSingle("SELECT count(*) FROM " + table).get(0, Long.class); } From b0596691455c2c01c5eb365eb5d2f3b3804bcdfb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:42:37 +1300 Subject: [PATCH 04/11] Bind Social catalog snapshots to exact retained frames --- .../game-session-service/api-contracts.md | 2 +- .../social-groups-service/runtime-and-data.md | 2 +- .../automation-and-scheduler-runtime.md | 4 +- ...r-experience-commands-and-communication.md | 2 +- .../realm-routing-and-playable-state.md | 4 +- ...__social_catalog_snapshot_exact_frames.sql | 159 +++++++++++++ ...eFamilyCatalogPostgresIntegrationTest.java | 211 ++++++++++++++++-- 7 files changed, 359 insertions(+), 25 deletions(-) create mode 100644 services/social-groups-service/src/main/resources/db/migration/V1006__social_catalog_snapshot_exact_frames.sql diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 21fd29d23a..414419ed25 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -88,7 +88,7 @@ Game Session may manually consume the [Social & Groups owner-local runtime-famil The manually composed, unregistered `WorldRuntimeFamilyCatalogClient` consumes the [World-owned runtime-family catalog read](../world-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). It authenticates the exact same-namespace World server, preserves the complete typed catalog bytes/digest, durable World epoch, snapshot identity and original read correlation, and refuses malformed, incomplete, stale-catalog, oversized or unavailable source evidence. The finite deadline and wire/source bounds are defined at that World contract owner. It runs outside ambient SQL and supplies only an as-of World-local classification input. It does not invent a complete owner set, wire evidence into FRESH preparation, mutate catalog/pointer authority, produce a FRESH manifest or protect a later Game Session commit. The whole-FRESH batch and focused proof status remain in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#world-owner-local-runtime-family-catalog-prerequisite). -The separate manually composed, unregistered `EntityRuntimeFamilyCatalogClient` consumes the [Entity-owned local catalog read](../entity-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). It authenticates the exact same-namespace Entity server, runs outside ambient SQL, and preserves the original request, immutable owner snapshot, exact catalog bytes/digests and Entity epoch under that owner's finite bounds/deadline. Conditional and unresolved Entity families remain blocking facts, not qualified resources/conditions, holder closure, mapping application, target emptiness or FRESH readiness. This evidence-only client is not wired into preparation, namespace/current-pointer authority, allocation or a later Game Session commit; its unrun source/proof status belongs to the [Entity tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#entity-owner-local-runtime-family-catalog-prerequisite). +The separate manually composed, unregistered `EntityRuntimeFamilyCatalogClient` consumes the [Entity-owned local catalog read](../entity-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). It authenticates the exact same-namespace Entity server, runs outside ambient SQL, and preserves the original request, immutable owner snapshot, exact catalog bytes/digests and Entity epoch under that owner's finite bounds/deadline. Conditional and unresolved Entity families remain blocking facts, not qualified resources/conditions, holder closure, mapping application, target emptiness or FRESH readiness. This evidence-only client is not wired into preparation, namespace/current-pointer authority, allocation or a later Game Session commit; its source/proof status belongs to the [Entity tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#entity-owner-local-runtime-family-catalog-prerequisite). Game Session has a manually composed, unregistered Automation runtime-family catalog client that requires file-backed mTLS, pins the exact same-namespace Automation peer, applies finite size/deadline bounds, and validates complete request/snapshot/catalog evidence. Its [Automation API owner contract](../automation-scripting-service/api-contracts.md#owner-local-runtime-family-catalog-read) and [classification/retention owner contract](../automation-scripting-service/runtime-and-data.md#owner-local-runtime-family-catalog) remain authoritative. A successful source read does not resolve blocking families or non-SQL gaps, enroll Automation, establish FRESH completeness/materialization, authorize an actor, or enable runtime admission, CLOSED aggregation or activation; unavailable evidence is never empty-source or initialized-state proof. diff --git a/design/architecture/microservices/social-groups-service/runtime-and-data.md b/design/architecture/microservices/social-groups-service/runtime-and-data.md index ce0ae3ae02..14065e7df1 100644 --- a/design/architecture/microservices/social-groups-service/runtime-and-data.md +++ b/design/architecture/microservices/social-groups-service/runtime-and-data.md @@ -61,7 +61,7 @@ The additive V1004 owner-local catalog is schema-derived source evidence. It ass An unclassified table refuses catalog installation even when it has no rows. After installation, changed, removed, renamed, or newly added schema objects, classifications, or prior migration facts invalidate the stored epoch and refuse both retained and new reads. No runtime path resamples drift or accepts an epoch; future schema/classification evolution requires an explicit owning forward migration. The immutable classification, epoch, and snapshot records preserve the installed source and exact request-bound evidence. -Flyway 13.12's built-in `${flyway:table}` placeholder binds the configured history table, including a custom name; the catalog never assumes a public-schema history name. View and materialized-view facts bind both `pg_get_viewdef` and `pg_class.reloptions`, including view security options; changing either invalidates the sealed epoch. The V1005 forward migration replaces the census routines and appends the next exact owner-local epoch without rewriting prior epochs, snapshots, payload rows, or history. Flyway writes catalog migrations' successful history rows after their transactions, so the current seal uses distinct `catalog-installation:1004` and `catalog-installation:1005` markers in place of those rows and the separate installed check requires both exact successful scripts. These markers do not attest to post-transaction checksums; normal Flyway validation remains required. An old request cannot be resampled under the new epoch. +Flyway 13.12's built-in `${flyway:table}` placeholder binds the configured history table, including a custom name; the catalog never assumes a public-schema history name. View and materialized-view facts bind both `pg_get_viewdef` and `pg_class.reloptions`, including view security options; changing either invalidates the sealed epoch. V1005 seals view options; V1006 additionally requires the canonical `SCR1` request frame reconstructed from the row request UUID and namespace and the complete `SCE1` evidence frame reconstructed from that request, the row snapshot UUID, and the current exact catalog bytes and digest. Independently correct frame digests do not substitute for exact frame equality. Each forward migration replaces its affected routines before appending the next exact owner-local epoch without rewriting prior epochs, snapshots, payload rows, or history. Flyway writes catalog migrations' successful history rows after their transactions, so the current seal uses distinct `catalog-installation:1004`, `catalog-installation:1005`, and `catalog-installation:1006` markers in place of those rows and the separate installed check requires all three exact successful scripts. These markers do not attest to post-transaction checksums; normal Flyway validation remains required. An old request cannot be resampled under the new epoch. The separate `ReadSocialRuntimeFamilyCatalog` contract in [API Contracts](./api-contracts.md#owner-local-runtime-family-catalog-read) retains one complete request-bound evidence frame and refuses drift or storage failure. The handler and Game Session mTLS client are manual source only; the Social handler is not registered with the application's gRPC server, and neither side is connected to player/API flows. This catalog is not row-level evidence, owner enrollment, target initialization, a global FRESH manifest, runtime authority, or admission; its explicit blockers—including tenant-bound account friendships, Social guild value storage, unresolved Saga adoption, and missing communication, safety, and standing contracts—do not qualify for readiness. diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index f38e04e627..3f78bcfc87 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -16,9 +16,9 @@ The exact-base publication-provenance candidates in this stack are not yet live. ### Owner-local runtime-family catalog source prerequisite -The unregistered Automation catalog source comprises [V1004](../../../services/automation-scripting-service/src/main/resources/db/migration/V1004__automation_owner_runtime_family_catalog.sql), the [capture/readback repository](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogRepository.java), [authenticated read handler](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java), [Common value](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java), [closed codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogCodec.java), [proto](../../../protos/automation-scripting/v1/automation_runtime_family_catalog_read.proto) and [Game Session client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClient.java). The database-derived catalog, durable epoch and immutable request snapshot retain actual combined Automation/Saga schema and configured Flyway-history facts. Normative classification/retention belongs to [Automation runtime/data](../../architecture/microservices/automation-scripting-service/runtime-and-data.md#owner-local-runtime-family-catalog); wire and consumer constraints belong to [Automation API contracts](../../architecture/microservices/automation-scripting-service/api-contracts.md#owner-local-runtime-family-catalog-read). +The unregistered Automation catalog source comprises [V1004](../../../services/automation-scripting-service/src/main/resources/db/migration/V1004__automation_owner_runtime_family_catalog.sql), forward [V1005](../../../services/automation-scripting-service/src/main/resources/db/migration/V1005__automation_catalog_view_options.sql), the [capture/readback repository](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogRepository.java), [authenticated read handler](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java), [Common value](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java), [closed codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogCodec.java), [proto](../../../protos/automation-scripting/v1/automation_runtime_family_catalog_read.proto) and [Game Session client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClient.java). The database-derived catalog, durable epoch and immutable request snapshot retain actual combined Automation/Saga schema and configured Flyway-history facts. Normative classification/retention belongs to [Automation runtime/data](../../architecture/microservices/automation-scripting-service/runtime-and-data.md#owner-local-runtime-family-catalog); wire and consumer constraints belong to [Automation API contracts](../../architecture/microservices/automation-scripting-service/api-contracts.md#owner-local-runtime-family-catalog-read). -Receiving proof243/244 passes six Common value/codec cases, four workload-guard cases, thirteen actual PostgreSQL cases and five physical client mTLS cases, with zero failures, errors or skips. Proof242 passes owning generation/formatting after correcting H2 simulation of PostgreSQL-only consequence constraints without weakening their physical guards. Proof245 passes 76 cases across all six affected existing Automation migration-fixture suites, affected main/unit/integration static analysis, formatting and documentation checks. Latest-frontier fixtures use the actual combined Saga/service migrations and explicit service schema; historical migration targets and positive assertions remain. The [catalog SQL suite](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java) and [mTLS suite](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClientMtlsTest.java) execute separately with controlled upstream identities, source bytes and local PKI. They do not prove a coupled deployed SQL-to-mTLS boundary, genuine issuer/custody, fresh images or private initialization. Game Session main SpotBugs remains unqualified under the separate JVM investigation. +Historical receiving proof243/244 passes six Common value/codec cases, four workload-guard cases, thirteen actual PostgreSQL cases and five physical client mTLS cases, with zero failures, errors or skips. Proof242 passes owning generation/formatting after correcting H2 simulation of PostgreSQL-only consequence constraints without weakening their physical guards. Proof245 passes 76 cases across all six affected existing Automation migration-fixture suites, affected main/unit/integration static analysis, formatting and documentation checks. Historical proof275/276 subsequently passes all sixteen Automation catalog PostgreSQL cases and the full 117-case Automation integration suite, including V1005 view-option drift and retained-evidence upgrade coverage; these are the V1005 batch results, not a rerun on later changes. The [realm-routing tracker](./realm-routing-and-playable-state.md#world-owner-local-runtime-family-catalog-prerequisite) owns consolidated four-owner batch proof. Latest-frontier fixtures use the actual combined Saga/service migrations and explicit service schema; historical migration targets and positive assertions remain. The [catalog SQL suite](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java) and [mTLS suite](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClientMtlsTest.java) execute separately with controlled upstream identities, source bytes and local PKI. They do not prove a coupled deployed SQL-to-mTLS boundary, genuine issuer/custody, fresh images or private initialization. Game Session main SpotBugs remains unqualified under the separate JVM investigation. NPC memory/formations, admitted work/plugin state, stable schedule namespace/mapping, the Automation/Social faction-standing ownership conflict, and non-SQL Redis/charge/accounting/reset sources remain explicit blockers at the owning contract. This source does not enroll Automation, establish a complete owner set or FRESH manifest, copy runtime state, run initialization, authorize an actor, or aggregate CLOSED. Capability ratings are unchanged. Private first admission, default registration, activation, Unit1B, reset, seeded/snapshot, issuer/custody and PKI holds remain. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index 273d463990..3e3b758ea7 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -79,7 +79,7 @@ Focused source proof covers complete Common Security and Social unit suites, nat - Previously recorded focused unit, native application and WebSocket composition evidence covers bounded presence-owner correlation, the earlier tenant-scoped classification, profile-policy projection and player-facing output corrections; its exact run attribution remains in the review records. The current receiving source changes make Game Session presence PLAYER-only while no independent gameplay-grant carrier is available, and add cached-role projection plus ordinary-update demotion. R1423’s receiving preparation, committed as `d12c0ab2e7a7d1d40f62991e3d097bd9090cc2ef`, executed 137 selected Common/Game Session units, including Redis presence, WHO and reconnect cases, plus six actual-Redis cases using the production serializer. Its retained `qualification.log` and `recovery.log` distinguish the original aggregate failure from fixture recovery; these are preparation-time results, not a rerun on the current review head. Its physical cache cases compare retained bytes and TTL through session, game and account reads before field-preserving activity demotion. The initial aggregate fails only new integration-fixture mutable-long analysis; immutable per-case IDs recover all six physical cases and enabled integration static analysis, formatting and documentation. Earlier unit/main-analysis results keep their source attribution; these scoped results do not establish full native-service, production gameplay-grant or admission proof. Snapshot-bound continuation, current relationship/block revalidation and broader authorization/disclosure remain incomplete. [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md), the [authentication owner](../../architecture/system-architecture-authentication.md), and the [Game Session runtime/data owner](../../architecture/microservices/game-session-service/runtime-and-data.md) own the target behavior. - Guild creation/member lifecycle callbacks emit best-effort operational logs after commit, with no committed lifecycle event on rollback. This logging supplies no durable audit or delivery guarantee. Consolidated receiving R1137 passes all 109 Social unit cases and all 15 selected native application cases, including the 12 `GuildServiceImplTest` cases covering all four actions, commit-versus-rollback context and a scoped throwing-appender regression. Enabled affected main/test/integration analysis, formatting and documentation checks pass. This proves the local dispatch boundary and supported service seams, not durable audit, delivery guarantees or current published-head/fresh-image qualification. - Current behavior/proof: `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, mail APIs, friends, guild APIs, presence reads, privacy settings, recipient delivery, and speech normalization are live at bounded service/API seams; focused communication, social, presence, privacy, moderation, and cross-service tests cover those seams. -- The Social owner-local runtime-family source prerequisite adds V1004 schema/history classification and an exact request-bound snapshot repository, a separately defined bounded `ReadSocialRuntimeFamilyCatalog` contract, and a manual Game Session mTLS client. It classifies installed Social/Saga/Flyway-history schema facts and explicit blockers only; it does not inspect row values, enroll an owner, establish target initialization, or produce FRESH readiness. The Social handler is not registered with the application gRPC server, and neither side is wired to a player path. Receiving proof243/244 passes six Common value/codec, four workload-guard, ten actual combined Social/Saga PostgreSQL and four physical Game Session mTLS cases, with zero failures, errors or skips; proof245 passes affected Social/Common static analysis, formatting and documentation checks. SQL and transport execute separately with controlled upstream data and local PKI, without deployed owner-chain, fresh-image or private-initialization proof. Game Session main SpotBugs remains unqualified under the separate JVM investigation. Current behavior and proof limits remain with [Social API Contracts](../../architecture/microservices/social-groups-service/api-contracts.md#grpc-apis) and [Social runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md#owner-local-runtime-family-catalog). +- The Social owner-local runtime-family source prerequisite comprises [V1004](../../../services/social-groups-service/src/main/resources/db/migration/V1004__social_owner_runtime_family_catalog.sql) schema/history classification, forward [V1005](../../../services/social-groups-service/src/main/resources/db/migration/V1005__social_catalog_view_options.sql), forward [V1006](../../../services/social-groups-service/src/main/resources/db/migration/V1006__social_catalog_snapshot_exact_frames.sql), an exact request-bound snapshot repository, a separately defined bounded `ReadSocialRuntimeFamilyCatalog` contract, and a manual Game Session mTLS client. It classifies installed Social/Saga/Flyway-history schema facts and explicit blockers only; it does not inspect row values, enroll an owner, establish target initialization, or produce FRESH readiness. The Social handler is not registered with the application gRPC server, and neither side is wired to a player path. Historical receiving proof243/244 passes six Common value/codec, four workload-guard, ten actual combined Social/Saga PostgreSQL and four physical Game Session mTLS cases, with zero failures, errors or skips; proof245 passes affected Social/Common static analysis, formatting and documentation checks. Historical proof275/276 subsequently passes all thirteen Social catalog PostgreSQL cases and the full 36-case Social integration suite, including V1005 view-option drift and retained-evidence upgrade coverage; these are the V1005 batch results, not V1006 proof. Proof281 passes the current fifteen-case catalog suite and full 38-case Social integration suite with no failures, errors or skips, including twelve independently hashed poisoned-frame vectors, same-identity recovery and genuine V1005 upgrade retention. Owning generation, selected integration analysis, formatting and documentation checks pass (50s). The [realm-routing tracker](./realm-routing-and-playable-state.md#world-owner-local-runtime-family-catalog-prerequisite) owns consolidated four-owner batch proof. SQL and transport execute separately with controlled upstream data and local PKI, without deployed owner-chain, fresh-image or private-initialization proof. Game Session main SpotBugs remains unqualified under the separate JVM investigation. Current behavior and proof limits remain with [Social API Contracts](../../architecture/microservices/social-groups-service/api-contracts.md#grpc-apis) and [Social runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md#owner-local-runtime-family-catalog). - Local gaps linked to [ADR 0147](../../architecture/decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md), [ADR 0148](../../architecture/decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md), [ADR 0149](../../architecture/decisions/adr-0149-communication-type-specific-history-and-retention.md), and [ADR 0150](../../architecture/decisions/adr-0150-closed-observer-views-and-profile-scoped-shout.md) include offline `TELL`, profile-scoped `SHOUT`, richer topology/interception, type-specific history/acknowledgement, entity-owned social value/attachments, closed observer views, cross-pod delivery, first-party recipient presentation, and the canonical gameplay `WHISPER` recipient-scope migration. These ADR links identify gaps; they do not restate target policy. - Presence/privacy drift remains tracked against [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md) and [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). Current `gameplaypresence:*` and `accountrecentpresence:*` Redis shapes, partial-write behavior, reset/readback behavior, storage role, and proof of private-by-failure enforcement for missing, stale, partial, or ambiguous evidence remain implementation/proof gaps. The canonical raw-presence/friend-projection ownership and disclosure rules are in the [Social & Groups Friend Presence Privacy Contract](../../architecture/microservices/social-groups-service/api-contracts.md#friend-presence-privacy-contract); canonical owner/reset details also live in the [Redis reset catalog](../../architecture/system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Current Game Session has no independent gameplay-grant carrier, so the received source defaults presence to `PLAYER`; the focused R1423 receiving proof does not establish production grant qualification. This correction does not complete snapshot-bound continuation, broad activity consumers, private-by-failure enforcement, or broader authorization/disclosure proof. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index b9d4418530..c8d49a9035 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -25,11 +25,11 @@ Current-selection CAS is implemented by [`GameSessionCurrentPrivatePlaytestRepos ### World owner-local runtime-family catalog prerequisite -The private FRESH prerequisite batch now has a concrete World-local catalog producer and Game Session consumer in working source: forward [V1046](../../../services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql), [World persistence/readback owner](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogRepository.java), [authenticated World read](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java), [shared exact value](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java), [closed codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java) and [Game Session client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClient.java). The normative census/classification/retention detail stays with [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#owner-local-runtime-family-catalog), and wire/authentication/bounds with [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). This is an actual database-derived World schema/family source and durable epoch/snapshot prerequisite, not a static expected-table list, global runtime registry, complete owner-epoch set or FRESH manifest. +The private FRESH prerequisite batch now has a concrete World-local catalog producer and Game Session consumer in working source: forward [V1046](../../../services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql) and [V1047](../../../services/world-management-service/src/main/resources/db/migration/V1047__world_catalog_snapshot_exact_frames.sql), [World persistence/readback owner](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogRepository.java), [authenticated World read](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java), [shared exact value](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java), [closed codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogCodec.java) and [Game Session client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClient.java). The normative census/classification/retention detail stays with [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#owner-local-runtime-family-catalog), and wire/authentication/bounds with [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). This is an actual database-derived World schema/family source and durable epoch/snapshot prerequisite, not a static expected-table list, global runtime registry, complete owner-epoch set or FRESH manifest. Receiving proof243/244 passes six World [value/codec cases](../../../services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogTest.java), four [workload-guard cases](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcServiceTest.java), thirteen [actual PostgreSQL cases](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java) and four [physical client mTLS cases](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClientMtlsTest.java), with zero failures, errors or skips. The four-owner receiving batch totals 107 focused cases; proof245 separately passes 129 affected existing Entity/Automation migration-fixture cases and selected owner/Common main-unit-integration static analysis, formatting and documentation checks. Owning generation passes in proof242/243. Earlier retained proof238 reproduces the configured-history refusal corrected before proof239; it is not a passing aggregate. Proof243 retains its missing Social client-import compilation failure; proof244 runs the corrected eighteen client cases and reuses unchanged passing codec/guard/SQL results. Exact XML and logs retain those scopes. The complete foreign-catalog fixture dependency pass aligns seven additional sites without changing historical targets or assertions. Proof262 passes the actual Entity/World cross-owner case after the Entity setup discovers Saga; proof263 passes twenty-four cases across the affected Account, World and Game Design suites, plus selected analysis/formatting/docs (3m25). Account’s V1023 predecessor discovers Saga before its later Entity upgrade; World targets 25/26 remain unchanged. These controlled source compositions do not establish genuine private initialization. Game Session main SpotBugs remains unqualified under the separate JVM investigation. PostgreSQL identity/legacy inputs and guard peer contexts are controlled; mTLS uses local test PKI and catalog responses rather than a live database producer. No coupled database-plus-mTLS owner chain, fresh-image/runtime or whole-FRESH proof is claimed. -Review corrections retain the published catalog migrations and add forward owner seals for view definitions and options. Proof275/276 passes 252 actual PostgreSQL cases across the affected Entity, World, Automation and Social suites, including seventeen World catalog cases, the receipt-digest migration composition and thirteen fixed-preset upgrade cases. World's controlled receipt probe now installs every source World/Saga table before reaching the full census; its predicate-only clone is not production authority. The fixed-preset retention case compares all original row values and `xmin` while separately asserting the three new catalog tables, two retained epochs and empty request snapshots. Proof275 retains that comparison failure; proof276 passes the corrected thirty-one World cases and selected integration static, formatting and documentation checks. The four mandatory-Docker catalog fixtures and combined forward-version checks pass their canonical contracts. Proof273 separately passes twenty-five Common codec cases, five Game Design compositions and eighteen physical mTLS client cases after the shared framing helper adds defensive copies; proof272's earlier mutable-array analysis failure remains recorded. These component proofs do not expand the source or runtime authority boundary. +Review corrections retain the published catalog migrations and add forward owner seals for view definitions and options. World V1047 supplies the exact snapshot-frame and installed-script guard; its normative behavior remains at the linked World data owner. Later Social V1006 is qualified by proof281: all fifteen catalog cases and the full 38-case integration suite pass, including twelve poisoned-frame vectors, same-identity recovery and retained V1005 upgrade evidence, with generation and selected checks. Proof275/276 passes 252 actual PostgreSQL cases across the affected Entity, World, Automation and Social suites, including seventeen World catalog cases, the receipt-digest migration composition and thirteen fixed-preset upgrade cases. World's controlled receipt probe now installs every source World/Saga table before reaching the full census; its predicate-only clone is not production authority. The fixed-preset retention case compares all original row values and `xmin` while separately asserting the three new catalog tables, two retained epochs and empty request snapshots. Proof275 retains that comparison failure; proof276 passes the corrected thirty-one World cases and selected integration static, formatting and documentation checks. The four mandatory-Docker catalog fixtures and combined forward-version checks pass their canonical contracts. Proof273 separately passes twenty-five Common codec cases, five Game Design compositions and eighteen physical mTLS client cases after the shared framing helper adds defensive copies; proof272's earlier mutable-array analysis failure remains recorded. These component proofs do not expand the source or runtime authority boundary. Remaining batch obligations are the genuine World-owned global enrollment/required-owner-set source, remaining actual owner catalogs/epochs, complete build/lifecycle/namespace/generation-bound FRESH manifest production and immutable authenticated readback, genuine protected private authorization/runtime/materialization, and complete-set aggregation into the existing canonical CLOSED pointer/audit/outcome owner. Current World canonical materialization is still public `SHARED` and original-`StartSession`-only; no private FRESH relabelling is valid. The existing unregistered [canonical CLOSED owner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java) supplies public initial CLOSED persistence, not the missing private aggregate; the registered legacy routing model described elsewhere remains narrower. No second private pointer authority is added. CLOSED-to-OPEN, private first admission, issuer/custody/PKI qualification, runtime/default registration, operational activation, reset and Unit1B remain held. Capability ratings are unchanged; this source batch does not complete FRESH capability. diff --git a/services/social-groups-service/src/main/resources/db/migration/V1006__social_catalog_snapshot_exact_frames.sql b/services/social-groups-service/src/main/resources/db/migration/V1006__social_catalog_snapshot_exact_frames.sql new file mode 100644 index 0000000000..689f21fa97 --- /dev/null +++ b/services/social-groups-service/src/main/resources/db/migration/V1006__social_catalog_snapshot_exact_frames.sql @@ -0,0 +1,159 @@ +-- Retain V1004/V1005 and all historical epochs, snapshots and migration rows byte-for-byte. +-- Bind Social snapshots to the complete exact SCR1 request and SCE1 evidence frames. +-- Flyway records each migration's own row after its transaction; distinct stable markers +-- bind the catalog installations without fabricating checksums or successful history rows. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION social_runtime_family_catalog_installed() RETURNS BOOLEAN +LANGUAGE SQL STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ + SELECT EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1004' AND script='V1004__social_owner_runtime_family_catalog.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1005' AND script='V1005__social_catalog_view_options.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1006' AND script='V1006__social_catalog_snapshot_exact_frames.sql' AND success); +$$; + +CREATE OR REPLACE FUNCTION social_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE +SET search_path = "${serviceSchema}", pg_catalog +AS $$ +DECLARE + v_families JSONB; + v_facts JSONB; +BEGIN + IF p_epoch IS NULL OR p_epoch <= 0 THEN + RAISE EXCEPTION 'Positive Social catalog epoch required' USING ERRCODE='23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM social_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM social_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed Social schema family' USING ERRCODE='23514'; + END IF; + + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name, + 'component',component_name,'role',family_role,'freshDisposition',fresh_disposition, + 'targetOwner',target_owner) ORDER BY family_id COLLATE "C") + INTO v_families FROM social_runtime_family_classification; + + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname, + jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::TEXT + FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1004' AND version IS DISTINCT FROM '1005' + AND version IS DISTINCT FROM '1006' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1004','V1004__social_owner_runtime_family_catalog.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1005','V1005__social_catalog_view_options.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1006','V1006__social_catalog_snapshot_exact_frames.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + + IF jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 THEN + RAISE EXCEPTION 'Complete Social catalog exceeds source bounds' USING ERRCODE='23514'; + END IF; + RETURN convert_to(jsonb_build_object('schema','social-runtime-family-catalog/v1', + 'owner','social-groups-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts, + 'unimplementedContracts',jsonb_build_array( + 'CHAT_RESTRICTION_AND_REVISION', + 'DIRECTIONAL_BLOCK_LIFECYCLE', + 'ENTITY_ESCROW_REFERENCE_FAMILIES', + 'GAMEPLAY_WHISPER_NAMESPACE_SCOPE', + 'SAFETY_EVIDENCE_AND_CONTENT_FREE_RECEIPTS', + 'SOCIAL_PLAYER_STANDING_OWNER', + 'SOCIAL_SAGA_ADOPTER_CLASSIFICATION'))::TEXT,'UTF8'); +END; +$$; + +CREATE OR REPLACE FUNCTION social_runtime_family_catalog_snapshot_guard() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = "${serviceSchema}", pg_catalog AS $$ +DECLARE + v_epoch social_runtime_family_catalog_epoch%ROWTYPE; + v_request BYTEA; + v_evidence BYTEA; +BEGIN + SELECT * INTO STRICT v_epoch FROM social_runtime_family_catalog_epoch ORDER BY catalog_epoch DESC LIMIT 1; + IF NEW.catalog_epoch<>v_epoch.catalog_epoch OR NEW.catalog_digest<>v_epoch.catalog_digest + OR social_runtime_family_catalog_bytes(v_epoch.catalog_epoch)<>v_epoch.catalog_bytes + OR NOT social_runtime_family_catalog_installed() THEN + RAISE EXCEPTION 'Social schema/classification changed; new owner epoch required' USING ERRCODE='23514'; + END IF; + -- Exact SCR1/SCE1 binary frames match the closed Java codec, including the original request. + v_request := decode('53435231','hex') || uuid_send(NEW.read_request_id) + || int4send(octet_length(convert_to(NEW.target_namespace,'UTF8'))) || convert_to(NEW.target_namespace,'UTF8'); + v_evidence := decode('53434531','hex') || int4send(octet_length(v_request)) || v_request + || uuid_send(NEW.snapshot_id) || int4send(octet_length(convert_to(v_epoch.catalog_digest,'UTF8'))) + || convert_to(v_epoch.catalog_digest,'UTF8') || int4send(octet_length(v_epoch.catalog_bytes)) || v_epoch.catalog_bytes; + IF NEW.request_bytes<>v_request OR NEW.evidence_bytes<>v_evidence THEN + RAISE EXCEPTION 'Social snapshot must bind complete exact request and evidence' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; + +-- Replace every affected routine before sealing the next exact owner-local epoch. +INSERT INTO social_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT next_epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM (SELECT coalesce(max(catalog_epoch),0)+1 AS next_epoch FROM social_runtime_family_catalog_epoch) next +CROSS JOIN LATERAL (SELECT social_runtime_family_catalog_bytes(next.next_epoch) AS bytes) seal; +-- [jooq ignore stop] diff --git a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java index eee813c9be..3b7b1bd403 100644 --- a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -8,6 +8,7 @@ import io.grpc.stub.StreamObserver; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.UUID; @@ -86,6 +87,16 @@ void configuredFlywayHistoryNameIsTheInstalledHistoryFamilyAndExactHistorySource fact -> { assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); assertThat(fact.identity()).isEqualTo("catalog-installation:1004"); + }) + .anySatisfy( + fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); + assertThat(fact.identity()).isEqualTo("catalog-installation:1005"); + }) + .anySatisfy( + fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); + assertThat(fact.identity()).isEqualTo("catalog-installation:1006"); }); assertThat(f.owner().readExact(evidence.request())).isEqualTo(evidence); assertThat( @@ -108,7 +119,7 @@ void actualCombinedSocialSagaCensusClassifiesEveryInstalledTableWithoutRowInfere throws Exception { try (Fixture f = fixture(null)) { var catalog = f.owner().read(request()).catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(2); + assertThat(catalog.catalogEpoch()).isEqualTo(3); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -260,16 +271,16 @@ void forwardMigrationRetainsPopulatedSocialSagaRowsAndEveryPriorHistoryRow() thr List historyBefore = f.historyRows(); migrate(f, null); assertThat(f.retainedRows()).isEqualTo(rowsBefore); - assertThat(f.historyRowsExcluding("1004", "1005")).isEqualTo(historyBefore); + assertThat(f.historyRowsExcluding("1004", "1005", "1006")).isEqualTo(historyBefore); var catalog = f.owner().read(request()).catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(2); + assertThat(catalog.catalogEpoch()).isEqualTo(3); assertThat(catalog.families()) .anySatisfy( family -> assertThat(family.freshDisposition()) .isEqualTo(FreshDisposition.ENTITY_VALUE_OWNERSHIP_DRIFT_BLOCKING)); assertThat(f.retainedRows()).isEqualTo(rowsBefore); - assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(2); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(3); assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); } } @@ -283,7 +294,7 @@ void emptyUnclassifiedNewTableInvalidatesExactAndNewReadsWithoutResampling() thr assertThat(f.count("unknown_runtime_family")).isZero(); assertThatThrownBy(() -> f.owner().readExact(retained)).hasMessageContaining("Unclassified"); assertThatThrownBy(() -> f.owner().read(request())).hasMessageContaining("Unclassified"); - assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(2); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(3); assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); } } @@ -325,7 +336,7 @@ void schemaColumnConstraintTriggerRoutineAndRemovalChangesCannotResampleUnderSam assertThatThrownBy(() -> f.owner().readExact(retained)) .isInstanceOf(RuntimeException.class); assertThatThrownBy(() -> f.owner().read(request())).isInstanceOf(RuntimeException.class); - assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(2); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(3); assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); } } @@ -352,7 +363,7 @@ void changedClassificationMigrationHistoryOrUnsuccessfulInstallationRefusesOldSo .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().read(request())) .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); - assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(2); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(3); assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); } try (Fixture f = fixture(null)) { @@ -419,9 +430,9 @@ void immutableMetadataAndSnapshotsRefuseMutationAndIncorrectEpochSeals() throws () -> f.dsl.execute( "INSERT INTO social_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 3,catalog_bytes,catalog_digest FROM social_runtime_family_catalog_epoch WHERE catalog_epoch=2")) + + " SELECT 4,catalog_bytes,catalog_digest FROM social_runtime_family_catalog_epoch WHERE catalog_epoch=3")) .hasMessageContaining("exact classified installed schema"); - assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(2); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(3); } } @@ -465,12 +476,12 @@ void viewSecurityOptionsInvalidateReadRetryAndFreshCaptureWithoutChangingRetaine throws Exception { for (String option : List.of("security_invoker", "security_barrier")) { try (Fixture f = fixture("1003")) { - // Install the real view before either catalog migration so its initial options are sealed. + // Install the real view before the catalog migrations so its initial options are sealed. f.dsl.execute("CREATE VIEW catalog_security_probe AS SELECT 1 AS id"); migrate(f, null); Request read = request(); var original = f.owner().read(read); - assertThat(original.catalog().catalogEpoch()).isEqualTo(2); + assertThat(original.catalog().catalogEpoch()).isEqualTo(3); assertThat(original.catalog().schemaFacts()) .anySatisfy( fact -> { @@ -527,7 +538,7 @@ void catalogViewOptionsUpgradeRetainsV1004DataHistoryEpochAndSnapshot() throws E List history = f.historyRows(); String epoch = f.catalogRows("social_runtime_family_catalog_epoch"); String snapshots = f.catalogRows("social_runtime_family_catalog_snapshot"); - migrate(f, null); + migrate(f, "1005"); for (var retained : rows.entrySet()) assertThat(f.jsonRows(retained.getKey())).isEqualTo(retained.getValue()); assertThat( @@ -574,13 +585,13 @@ void catalogViewOptionsUpgradeRetainsV1004DataHistoryEpochAndSnapshot() throws E script.getBytes(java.nio.charset.StandardCharsets.UTF_8))); }); } - flyway(f.source, f.schema, f.history, null).validate(); + flyway(f.source, f.schema, f.history, "1005").validate(); } } @Test - void bothExactSuccessfulCatalogInstallationsAreRequired() throws Exception { - for (String version : List.of("1004", "1005")) { + void allThreeExactSuccessfulCatalogInstallationsAreRequired() throws Exception { + for (String version : List.of("1004", "1005", "1006")) { for (String change : List.of("success=false", "script='wrong_catalog_installation.sql'")) { try (Fixture f = fixture(null)) { Request read = request(); @@ -599,6 +610,152 @@ void bothExactSuccessfulCatalogInstallationsAreRequired() throws Exception { } } + @Test + void poisonedFramesWithCorrectIndependentDigestsRefuseWithoutConsumingRequestIdentity() + throws Exception { + try (Fixture f = fixture(null)) { + var original = f.owner().read(request()); + for (String vector : + List.of( + "request-id", + "namespace", + "request-magic", + "request-trailing", + "request-truncated", + "evidence-request", + "snapshot", + "catalog-digest", + "catalog-bytes", + "evidence-magic", + "evidence-trailing", + "evidence-truncated")) { + Request read = request(); + var proposal = new Evidence(read, UUID.randomUUID(), original.catalog()); + byte[] requestBytes = SocialRuntimeFamilyCatalogCodec.requestBytes(read); + byte[] evidenceBytes = SocialRuntimeFamilyCatalogCodec.evidenceBytes(proposal); + String namespace = read.targetNamespace(); + switch (vector) { + case "request-id" -> + requestBytes = SocialRuntimeFamilyCatalogCodec.requestBytes(request()); + case "namespace" -> namespace = "other"; + case "request-magic" -> requestBytes[0] ^= 1; + case "request-trailing" -> + requestBytes = Arrays.copyOf(requestBytes, requestBytes.length + 1); + case "request-truncated" -> + requestBytes = Arrays.copyOf(requestBytes, requestBytes.length - 1); + case "evidence-request" -> + evidenceBytes = + SocialRuntimeFamilyCatalogCodec.evidenceBytes( + new Evidence(request(), proposal.snapshotId(), original.catalog())); + case "snapshot" -> + evidenceBytes = + SocialRuntimeFamilyCatalogCodec.evidenceBytes( + new Evidence(read, UUID.randomUUID(), original.catalog())); + case "catalog-digest" -> evidenceBytes[4 + 4 + requestBytes.length + 16 + 4] ^= 1; + case "catalog-bytes" -> evidenceBytes[evidenceBytes.length - 1] ^= 1; + case "evidence-magic" -> evidenceBytes[0] ^= 1; + case "evidence-trailing" -> + evidenceBytes = Arrays.copyOf(evidenceBytes, evidenceBytes.length + 1); + case "evidence-truncated" -> + evidenceBytes = Arrays.copyOf(evidenceBytes, evidenceBytes.length - 1); + default -> throw new AssertionError("Unknown frame vector: " + vector); + } + byte[] insertedRequest = requestBytes; + byte[] insertedEvidence = evidenceBytes; + String insertedNamespace = namespace; + String retained = f.catalogRows("social_runtime_family_catalog_snapshot"); + // Each forged frame gets its own correct digest; a hash-only constraint cannot reject it. + assertThatThrownBy( + () -> + f.insertSnapshot( + proposal, insertedNamespace, insertedRequest, insertedEvidence)) + .as(vector) + .hasMessageContaining("complete exact request and evidence"); + assertThat(f.catalogRows("social_runtime_family_catalog_snapshot")).isEqualTo(retained); + // The failed insert must leave the same request and snapshot identities available. + f.insertSnapshot( + proposal, + read.targetNamespace(), + SocialRuntimeFamilyCatalogCodec.requestBytes(read), + SocialRuntimeFamilyCatalogCodec.evidenceBytes(proposal)); + assertThat(f.owner().read(read)).isEqualTo(proposal); + assertThat(f.owner().readExact(read)).isEqualTo(proposal); + assertThat(f.owner().read(original.request())).isEqualTo(original); + assertThat(f.owner().readExact(original.request())).isEqualTo(original); + } + } + } + + @Test + void exactFramesUpgradeRetainsV1005RowsHistoryEpochsAndSnapshot() throws Exception { + try (Fixture f = fixture("1005")) { + f.dsl.execute( + "INSERT INTO guilds(tenant_id,name,owner_account_id) VALUES (7,'retained',?::uuid)", + "10000000-0000-4000-8000-000000000001"); + f.dsl.execute("INSERT INTO saga_instance(saga_name,state) VALUES ('retained','PENDING')"); + Map rows = f.retainedRows(); + Request read = request(); + var original = f.owner().read(read); + assertThat(original.catalog().catalogEpoch()).isEqualTo(2); + List history = f.historyRows(); + String epochs = f.catalogRows("social_runtime_family_catalog_epoch"); + String snapshots = f.catalogRows("social_runtime_family_catalog_snapshot"); + migrate(f, null); + assertThat(f.retainedRows()).isEqualTo(rows); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(h)::text FROM " + + f.history + + " h WHERE version IS DISTINCT FROM '1006' ORDER BY installed_rank") + .getValues(0, String.class)) + .isEqualTo(history); + assertThat(f.catalogRows("social_runtime_family_catalog_epoch WHERE catalog_epoch<3")) + .isEqualTo(epochs); + assertThat(f.catalogRows("social_runtime_family_catalog_snapshot")).isEqualTo(snapshots); + assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(3); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().read(read)) + .isInstanceOf(SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThat(f.catalogRows("social_runtime_family_catalog_snapshot")).isEqualTo(snapshots); + var current = f.owner().read(request()); + assertThat(current.catalog().catalogEpoch()).isEqualTo(3); + assertThat(current.catalog().digest()).isNotEqualTo(original.catalog().digest()); + assertThat(f.owner().readExact(current.request())).isEqualTo(current); + assertThat( + current.catalog().schemaFacts().stream() + .filter(fact -> fact.kind() == FactKind.MIGRATION) + .map(SocialRuntimeFamilyCatalog.SchemaFact::identity) + .toList()) + .contains( + "catalog-installation:1004", "catalog-installation:1005", "catalog-installation:1006") + .noneMatch( + identity -> + identity.contains(":1004:") + || identity.contains(":1005:") + || identity.contains(":1006:")); + for (var marker : + Map.of( + "1004", "V1004__social_owner_runtime_family_catalog.sql", + "1005", "V1005__social_catalog_view_options.sql", + "1006", "V1006__social_catalog_snapshot_exact_frames.sql") + .entrySet()) { + assertThat(current.catalog().schemaFacts()) + .anySatisfy( + fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); + assertThat(fact.identity()).isEqualTo("catalog-installation:" + marker.getKey()); + assertThat(fact.definitionDigest()) + .isEqualTo( + SocialRuntimeFamilyCatalog.sha256( + marker.getValue().getBytes(java.nio.charset.StandardCharsets.UTF_8))); + }); + } + flyway(f.source, f.schema, f.history, null).validate(); + } + } + private static Request request() { return new Request(UUID.randomUUID(), "test"); } @@ -672,6 +829,23 @@ SocialRuntimeFamilyCatalogRepository owner() { return new SocialRuntimeFamilyCatalogRepository(dsl, manager, schema, "test"); } + void insertSnapshot( + Evidence proposal, String namespace, byte[] requestBytes, byte[] evidenceBytes) { + dsl.execute( + "INSERT INTO social_runtime_family_catalog_snapshot" + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," + + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)", + proposal.request().readRequestId(), + namespace, + requestBytes, + SocialRuntimeFamilyCatalog.sha256(requestBytes), + proposal.snapshotId(), + proposal.catalog().catalogEpoch(), + proposal.catalog().digest(), + evidenceBytes, + SocialRuntimeFamilyCatalog.sha256(evidenceBytes)); + } + String catalogRows(String source) { return dsl.fetchSingle( "SELECT coalesce(jsonb_agg(row_json ORDER BY row_json::text),'[]'::jsonb)::text" @@ -708,13 +882,14 @@ List historyRows() { .getValues(0, String.class); } - List historyRowsExcluding(String first, String second) { + List historyRowsExcluding(String first, String second, String third) { return dsl.fetch( "SELECT to_jsonb(h)::text FROM " + history - + " h WHERE version IS DISTINCT FROM ? AND version IS DISTINCT FROM ? ORDER BY installed_rank", + + " h WHERE version IS DISTINCT FROM ? AND version IS DISTINCT FROM ? AND version IS DISTINCT FROM ? ORDER BY installed_rank", first, - second) + second, + third) .getValues(0, String.class); } From cf0f1e6cee7a30c7e3cfa7eab888b6ab0afa71a8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:22:41 +1300 Subject: [PATCH 05/11] Share runtime catalog storage status classification --- ...onRuntimeFamilyCatalogReadGrpcService.java | 26 ++-------- .../RuntimeFamilyCatalogStorageStatus.java | 34 ++++++++++++++ ...RuntimeFamilyCatalogStorageStatusTest.java | 47 +++++++++++++++++++ ...tyRuntimeFamilyCatalogReadGrpcService.java | 26 +++------- ...alRuntimeFamilyCatalogReadGrpcService.java | 32 +++---------- ...ldRuntimeFamilyCatalogReadGrpcService.java | 6 ++- 6 files changed, 103 insertions(+), 68 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogStorageStatus.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogStorageStatusTest.java diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java index 7d900451e3..24164ae96c 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java @@ -2,7 +2,6 @@ import io.grpc.Status; import io.grpc.stub.StreamObserver; -import java.sql.SQLException; import java.util.Objects; import net.firedevops.firemud.automationscripting.v1.AutomationRuntimeFamilyCatalogReadServiceGrpc; import net.firedevops.firemud.automationscripting.v1.ReadAutomationRuntimeFamilyCatalogRequest; @@ -93,26 +92,11 @@ public void readAutomationRuntimeFamilyCatalog( } private static Status storageStatus(RuntimeException failure) { - for (Throwable cause = failure; cause != null; cause = cause.getCause()) { - if (cause instanceof SQLException sql) { - String state = sql.getSQLState(); - if (state == null) continue; - if (state.startsWith("23") || state.startsWith("P0") || state.equals("55000")) - return Status.FAILED_PRECONDITION; - if (state.equals("40001") || state.equals("40P01")) return Status.ABORTED; - if (state.startsWith("08") || state.startsWith("57") || state.equals("55P03")) - return Status.UNAVAILABLE; - if (state.startsWith("22") || state.startsWith("42") || state.startsWith("XX")) - return Status.INTERNAL; - } - } - if (failure instanceof org.springframework.dao.DataIntegrityViolationException) - return Status.FAILED_PRECONDITION; - if (failure instanceof org.jooq.exception.DataAccessException - || failure instanceof org.springframework.dao.TransientDataAccessException - || failure instanceof org.springframework.dao.DataAccessResourceFailureException) - return Status.UNAVAILABLE; - return Status.INTERNAL; + return net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogStorageStatus.classify( + failure, + failure instanceof org.jooq.exception.DataAccessException + ? Status.UNAVAILABLE + : Status.INTERNAL); } private static void refuse(StreamObserver observer, Status status, String message) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogStorageStatus.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogStorageStatus.java new file mode 100644 index 0000000000..e384199460 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogStorageStatus.java @@ -0,0 +1,34 @@ +package net.firedevops.firemud.common.runtimecatalog; + +import io.grpc.Status; +import java.sql.SQLException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.TransientDataAccessException; + +/** Shared catalog transport classification; messages and owner conflict types remain local. */ +public final class RuntimeFamilyCatalogStorageStatus { + private RuntimeFamilyCatalogStorageStatus() {} + + /** + * The owner supplies the fallback for its persistence adapter without coupling this module to it. + */ + public static Status classify(Throwable failure, Status unmappedStorageStatus) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql && sql.getSQLState() != null) { + String state = sql.getSQLState(); + if (state.startsWith("23") || state.startsWith("P0") || state.equals("55000")) + return Status.FAILED_PRECONDITION; + if (state.equals("40001") || state.equals("40P01")) return Status.ABORTED; + if (state.startsWith("08") || state.startsWith("57") || state.equals("55P03")) + return Status.UNAVAILABLE; + if (state.startsWith("22") || state.startsWith("42") || state.startsWith("XX")) + return Status.INTERNAL; + } + } + if (failure instanceof DataIntegrityViolationException) return Status.FAILED_PRECONDITION; + if (failure instanceof TransientDataAccessException + || failure instanceof DataAccessResourceFailureException) return Status.UNAVAILABLE; + return java.util.Objects.requireNonNull(unmappedStorageStatus, "unmappedStorageStatus"); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogStorageStatusTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogStorageStatusTest.java new file mode 100644 index 0000000000..92156f6eaa --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogStorageStatusTest.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.common.runtimecatalog; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.Status; +import java.sql.SQLException; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.QueryTimeoutException; + +class RuntimeFamilyCatalogStorageStatusTest { + @Test + void sqlStatesOverrideAdapterFallbackWithoutLeakingDatabaseMessages() { + for (String state : new String[] {"23514", "P0001", "55000"}) + check(state, Status.FAILED_PRECONDITION); + for (String state : new String[] {"40001", "40P01"}) check(state, Status.ABORTED); + for (String state : new String[] {"08006", "57014", "55P03"}) check(state, Status.UNAVAILABLE); + for (String state : new String[] {"22000", "42P01", "XX000"}) check(state, Status.INTERNAL); + } + + @Test + void springAndUnknownAdapterFailuresPreserveTheExistingContract() { + assertThat(classify(new DataIntegrityViolationException("private"))) + .isEqualTo(Status.FAILED_PRECONDITION); + assertThat(classify(new QueryTimeoutException("private"))).isEqualTo(Status.UNAVAILABLE); + assertThat(classify(new DataAccessResourceFailureException("private"))) + .isEqualTo(Status.UNAVAILABLE); + assertThat(classify(new IllegalStateException("private"))).isEqualTo(Status.INTERNAL); + assertThat( + RuntimeFamilyCatalogStorageStatus.classify(new RuntimeException(), Status.UNAVAILABLE)) + .isEqualTo(Status.UNAVAILABLE); + assertThat(classify(new RuntimeException(new SQLException("private", (String) null)))) + .isEqualTo(Status.INTERNAL); + } + + private static Status classify(Throwable failure) { + return RuntimeFamilyCatalogStorageStatus.classify(failure, Status.INTERNAL); + } + + private static void check(String state, Status expected) { + assertThat( + RuntimeFamilyCatalogStorageStatus.classify( + new RuntimeException(new SQLException("private", state)), Status.UNAVAILABLE)) + .isEqualTo(expected); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java index 2868caea1c..8f3959f4a7 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java @@ -2,7 +2,6 @@ import io.grpc.Status; import io.grpc.stub.StreamObserver; -import java.sql.SQLException; import java.util.Objects; import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Request; import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalogCodec; @@ -92,25 +91,12 @@ public void readEntityRuntimeFamilyCatalog( observer.onCompleted(); } - private static Status storageStatus(Throwable failure) { - for (Throwable cause = failure; cause != null; cause = cause.getCause()) { - if (cause instanceof SQLException sql && sql.getSQLState() != null) { - String state = sql.getSQLState(); - if (state.startsWith("23") || state.startsWith("P0") || state.equals("55000")) - return Status.FAILED_PRECONDITION; - if (state.equals("40001") || state.equals("40P01")) return Status.ABORTED; - if (state.startsWith("08") || state.startsWith("57") || state.equals("55P03")) - return Status.UNAVAILABLE; - if (state.startsWith("22") || state.startsWith("42") || state.startsWith("XX")) - return Status.INTERNAL; - } - } - if (failure instanceof org.springframework.dao.DataIntegrityViolationException) - return Status.FAILED_PRECONDITION; - if (failure instanceof org.springframework.dao.TransientDataAccessException - || failure instanceof org.springframework.dao.DataAccessResourceFailureException - || failure instanceof org.jooq.exception.DataAccessException) return Status.UNAVAILABLE; - return Status.INTERNAL; + private static Status storageStatus(RuntimeException failure) { + return net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogStorageStatus.classify( + failure, + failure instanceof org.jooq.exception.DataAccessException + ? Status.UNAVAILABLE + : Status.INTERNAL); } private static void refuse(StreamObserver observer, Status status, String description) { diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcService.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcService.java index 6fb72ac5bd..6aa7d7b6c4 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcService.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcService.java @@ -2,7 +2,6 @@ import io.grpc.Status; import io.grpc.stub.StreamObserver; -import java.sql.SQLException; import java.util.Objects; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; @@ -91,31 +90,12 @@ public void readSocialRuntimeFamilyCatalog( observer.onCompleted(); } - private static Status storageStatus(Throwable failure) { - for (Throwable cause = failure; cause != null; cause = cause.getCause()) { - if (cause instanceof SQLException sql && sql.getSQLState() != null) { - String state = sql.getSQLState(); - if (state.startsWith("23") || state.startsWith("P0") || state.equals("55000")) { - return Status.FAILED_PRECONDITION; - } - if (state.equals("40001") || state.equals("40P01")) return Status.ABORTED; - if (state.startsWith("08") || state.startsWith("57") || state.equals("55P03")) { - return Status.UNAVAILABLE; - } - if (state.startsWith("22") || state.startsWith("42") || state.startsWith("XX")) { - return Status.INTERNAL; - } - } - } - if (failure instanceof org.springframework.dao.DataIntegrityViolationException) { - return Status.FAILED_PRECONDITION; - } - if (failure instanceof org.springframework.dao.TransientDataAccessException - || failure instanceof org.springframework.dao.DataAccessResourceFailureException - || failure instanceof org.jooq.exception.DataAccessException) { - return Status.UNAVAILABLE; - } - return Status.INTERNAL; + private static Status storageStatus(RuntimeException failure) { + return net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogStorageStatus.classify( + failure, + failure instanceof org.jooq.exception.DataAccessException + ? Status.UNAVAILABLE + : Status.INTERNAL); } private static void refuse(StreamObserver observer, Status status, String message) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java index 38ed5142f9..82b74e267e 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java @@ -80,7 +80,11 @@ public void readWorldRuntimeFamilyCatalog( | org.springframework.dao.DataAccessException failure) { refuse( observer, - Status.fromCode(WorldPreparationStorageFailureStatus.from(failure)), + net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogStorageStatus.classify( + failure, + failure instanceof org.jooq.exception.DataAccessException + ? Status.UNAVAILABLE + : Status.INTERNAL), "World catalog storage read failed"); return; } catch (org.springframework.transaction.CannotCreateTransactionException unavailable) { From d0e07ba6c5e38f6479848a0defdb484f2f87270a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:28:41 +1300 Subject: [PATCH 06/11] Strengthen catalog frame and drift regression proof --- .../game-session-service/api-contracts.md | 4 +- .../gameplay-rules-entities-and-effects.md | 2 +- ...eFamilyCatalogPostgresIntegrationTest.java | 166 ++++++++++++++---- ...eFamilyCatalogPostgresIntegrationTest.java | 36 +++- 4 files changed, 168 insertions(+), 40 deletions(-) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 414419ed25..902c0c5fe4 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -82,7 +82,7 @@ For that selector, Game Session reads its current target and launch association The Account client uses a 30-second deadline for this composed read; the nested World client uses its own five-second deadline. The complete published-read response is bounded to exactly 6,422,545 bytes, including the full existing publication response, a 64 KiB target, the current 4 MiB World response allowance, and protobuf framing. The World carrier has no intrinsic evidence-size bound; this method refuses an oversized complete response rather than dropping evidence. These limits and deadlines apply to `GetPublishedRealmAdmissionOwnerRead`, not to `ResolvePublishedRealmAdmissionTarget`. The RPC proves neither current Account authority nor a World hold, issuer/custody qualification, runtime activation, or gameplay admission. Local source and proof status are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#public-bootstrap-worlds-source-preparation). -### Initial `FRESH` playtest lifecycle source preparation +### Owner-local runtime-family catalog clients Game Session may manually consume the [Social & Groups owner-local runtime-family catalog](../social-groups-service/api-contracts.md#owner-local-runtime-family-catalog-read) through its exact same-namespace peer-qualified client with finite request/response and deadline bounds. This is source evidence only; it does not establish row-level classification, initialized target state, owner enrollment, FRESH readiness or protection through a later Game Session commit. Social’s blocking dispositions and unimplemented contracts remain outstanding. @@ -92,6 +92,8 @@ The separate manually composed, unregistered `EntityRuntimeFamilyCatalogClient` Game Session has a manually composed, unregistered Automation runtime-family catalog client that requires file-backed mTLS, pins the exact same-namespace Automation peer, applies finite size/deadline bounds, and validates complete request/snapshot/catalog evidence. Its [Automation API owner contract](../automation-scripting-service/api-contracts.md#owner-local-runtime-family-catalog-read) and [classification/retention owner contract](../automation-scripting-service/runtime-and-data.md#owner-local-runtime-family-catalog) remain authoritative. A successful source read does not resolve blocking families or non-SQL gaps, enroll Automation, establish FRESH completeness/materialization, authorize an actor, or enable runtime admission, CLOSED aggregation or activation; unavailable evidence is never empty-source or initialized-state proof. +### Initial `FRESH` playtest lifecycle source preparation + [ADR 0137](../../decisions/adr-0137-isolated-playtest-state-modes-and-reset.md) owns playtest initialization modes and isolated lifecycle identity; [ADR 0138](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) owns explicit expiry and grant consequences. The local, unregistered `GameSessionInitialPlaytestLifecycleRepository.prepare` boundary supports only an initial `FRESH` preparation. Its exact request binds a stable `requestId`, `targetNamespace`, `tenantId`, `worldSlug`, `realmSlug`, and explicit future `forkExpiresAt`, plus `sourceCatalogRealmId`, `sourceCatalogRequestId`, `sourceCatalogRevision` fixed at `1`, `sourceIntakeOperationId`, `canonicalVersionId`, `publishedReleaseBundleRef`, and `publishedReleaseBundleDigest`. Game Session locks and validates the retained canonical public-production catalog and its complete published policy evidence against the same tenant/world, distinct target realm, source-intake operation, canonical version, and published release bundle; fixture-only source records are excluded. The target must also be an exact visible, non-public, `ISOLATED` realm policy in that complete immutable Human-published policy set. The retained preparation binds its policy identity, canonical bytes, digest and source revision; a public build or catalog alone cannot authorize an arbitrary private target. A new request allocates a fresh non-nil `playtestLifecycleId` and `playableStateNamespaceId` internally and fixes the initial `playtestStateGeneration` at `1`; none is supplied by the request. The canonical original-request preimage and digest are retained: an exact `requestId` retry returns that original allocation, while changed request content conflicts rather than reallocating or extending expiry. The explicit `forkExpiresAt` is stored with the preparation and checked against the database clock for a new allocation. The preparation remains `PREPARING`; an exact lifecycle read returns `INCOMPLETE` before expiry or `EXPIRED` at/after expiry, and every returned snapshot has `admissionAllowed=false`. The internal `GameSessionCurrentPrivatePlaytestRepository` selects one preparation by explicit expected head revision and expected current lifecycle. A new selection retains an immutable request receipt and advances the scoped head once; historical exact replay returns the original selection rather than choosing a newer preparation. Both selection and current reads qualify the exact retained preparation/private policy; this head is not a player-visible catalog or admission pointer. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 7a373cb6b2..6b8e888f4c 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for gameplay rules, entities, and Working source adds the bounded Entity-local catalog prerequisite within the existing private FRESH batch: forward [V1025](../../../services/entity-management-service/src/main/resources/db/migration/V1025__entity_owner_runtime_family_catalog.sql), [capture and independent readback repository](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogRepository.java), [authenticated read handler](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java), [immutable Common value](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java), [closed codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogCodec.java), [purpose-specific proto](../../../protos/entity-management/v1/entity_runtime_family_catalog_read.proto) and [Game Session consumer](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClient.java). Normative semantics belong only to [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md#owner-local-runtime-family-catalog) and [Entity API Contracts](../../architecture/microservices/entity-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). These components remain manually composed/unregistered, with no FRESH coordinator or pointer integration and no capability-rating upgrade. -Focused executable sources are added for [Common value/codec/digest/bounds](../../../services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogTest.java), [workload-before-decode/SQL and positive handler behavior](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcServiceTest.java), [actual combined-migration PostgreSQL census, conditional/unresolved facts, populated retained source, epoch/readback/reconstruction, concurrent exact replay, history names and drift](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java), and [peer-qualified Game Session mTLS identity, correlation, refusals and actual deadline](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClientMtlsTest.java). Existing Entity migration-frontier fixture assertions advance to V1026 without removing their positive cases or changing old migrations. The new PostgreSQL fixture retains the real Entity Testcontainers/Flyway pattern, combined Saga locations, custom history and V1004's nontransactional concurrent-index behavior; it has no unavailable-Docker skip or substitute database. +Focused executable sources are added for [Common value/codec/digest/bounds](../../../services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogTest.java), [workload-before-decode/SQL and positive handler behavior](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcServiceTest.java), [actual combined-migration PostgreSQL census, conditional/unresolved facts, populated retained source, epoch/readback/reconstruction, concurrent exact replay, history names and drift](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java), and [peer-qualified Game Session mTLS identity, correlation, refusals and actual deadline](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClientMtlsTest.java). Forward [V1026](../../../services/entity-management-service/src/main/resources/db/migration/V1026__entity_catalog_snapshot_exact_frames.sql) tightens the production snapshot guard to require exact request and evidence frames while retaining V1025 and every historical epoch and snapshot byte-for-byte; the focused Entity PostgreSQL test covers poisoned-frame refusal and exact retry. Existing Entity migration-frontier fixture assertions advance to V1026 without removing their positive cases or changing old migrations. The new PostgreSQL fixture retains the real Entity Testcontainers/Flyway pattern, combined Saga locations, custom history and V1004's nontransactional concurrent-index behavior; it has no unavailable-Docker skip or substitute database. Receiving proof243/244 passes seven Common value/codec cases, four workload-guard cases, twelve actual PostgreSQL cases and five physical client mTLS cases, with zero failures, errors or skips. Proof242 passes owning generation/formatting. Proof245 passes all 53 cases across the four affected existing Entity migration-fixture suites, affected main/unit/integration static analysis, formatting and documentation checks. Game Session main SpotBugs remains unqualified under the separate JVM investigation. SQL/RPC peer contexts and retained upstream identities are controlled; separate physical mTLS source uses controlled local PKI and catalog bytes, not a coupled SQL-to-mTLS owner chain or genuine issuer/custody evidence. Reconstruction is not process-death proof. The catalog installation markers have the explicit post-transaction checksum limit documented at their owner. Review fixes add forward V1026 and preserve the earlier migration and retained epochs/snapshots; proof271 passes owning generation and fourteen actual catalog PostgreSQL cases, including six direct-SQL poison-frame vectors and genuine V1025 upgrade retention. The four existing latest-frontier suites retain their historical parent targets and advance only their current-version/script assertions. After the view-options correction, proof275 passes fifteen catalog PostgreSQL cases and all fifty-three cases in those existing suites with no failures, errors or skips, including real view-security and materialized-view option drift. Applied predecessors remain unchanged, and the mandatory-Docker contract is explicit; no unavailable-Docker skip is added. diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java index 982e797205..6cb1dac97b 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -31,6 +31,7 @@ import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; import org.jooq.DSLContext; import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -394,23 +395,50 @@ void unknownEmptyTableRefusesInitialInstallAtomicallyAndInvalidatesExistingSeal( } @Test - void columnTableRoutineConstraintAndSequenceDefinitionDriftCannotResample() { + void columnRoutineConstraintAndSequenceDefinitionDriftCannotResample() { for (String change : List.of( "ALTER TABLE npcs ADD COLUMN future_state TEXT", "ALTER TABLE npcs RENAME COLUMN last_defeated_at TO defeated_later", "ALTER TABLE npcs ALTER COLUMN behavior TYPE VARCHAR(120)", "ALTER TABLE npcs ADD CONSTRAINT catalog_probe CHECK(id>0)", - "ALTER TABLE npcs RENAME TO renamed_npcs", "CREATE FUNCTION future_writer() RETURNS INTEGER LANGUAGE SQL AS 'SELECT 1'", "ALTER SEQUENCE entity_runtime_entity_id_sequence INCREMENT BY 2")) { try (var f = fixture(null, HISTORY)) { var read = request(); - f.owner().read(read); + var original = f.owner().read(read); + var retained = + f.dsl + .fetchSingle( + "SELECT evidence_bytes FROM entity_runtime_family_catalog_snapshot WHERE read_request_id=?", + read.readRequestId()) + .get(0, byte[].class); f.dsl.execute(change); - assertThatThrownBy(() -> f.owner().readExact(read)).isInstanceOf(RuntimeException.class); - assertThatThrownBy(() -> f.owner().read(request())).isInstanceOf(RuntimeException.class); + boolean classifiedColumnRemoved = + change.startsWith("ALTER TABLE npcs RENAME COLUMN last_defeated_at"); + Class expectedType = + classifiedColumnRemoved + ? DataAccessException.class + : EntityRuntimeFamilyCatalogRepository.CatalogConflictException.class; + String expectedMessage = + classifiedColumnRemoved + ? "Unclassified or changed" + : "Entity schema/classification drift invalidates its epoch"; + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(expectedType) + .hasMessageContaining(expectedMessage); + assertThatThrownBy(() -> f.owner().read(request())) + .isInstanceOf(expectedType) + .hasMessageContaining(expectedMessage); assertThat(f.count("entity_runtime_family_catalog_snapshot")).isEqualTo(1); + assertThat( + f.dsl + .fetchSingle( + "SELECT evidence_bytes FROM entity_runtime_family_catalog_snapshot WHERE read_request_id=?", + read.readRequestId()) + .get(0, byte[].class)) + .isEqualTo(retained) + .isEqualTo(EntityRuntimeFamilyCatalogCodec.evidenceBytes(original)); } } } @@ -420,7 +448,30 @@ void missingTableClassificationAndMigrationChangesInvalidateWithoutRewritingEvid for (String change : List.of( "DROP TABLE npcs", - "INSERT INTO entity_runtime_family_classification VALUES ('npcs.version_id_extra','npcs','version_id_extra','SOURCE','NOT_PAYLOAD','AUTHORED_SOURCE_ONLY')", + "ALTER TABLE npcs RENAME TO renamed_npcs", + "INSERT INTO entity_runtime_family_classification VALUES ('npcs.version_id_extra','npcs','version_id_extra','SOURCE','NOT_PAYLOAD','AUTHORED_SOURCE_ONLY')")) { + try (var f = fixture(null, HISTORY)) { + var read = request(); + var original = f.owner().read(read); + f.dsl.execute(change); + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Unclassified or changed"); + assertThatThrownBy(() -> f.owner().read(request())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Unclassified or changed"); + assertThat(f.count("entity_runtime_family_catalog_snapshot")).isEqualTo(1); + assertThat( + f.dsl + .fetchSingle( + "SELECT evidence_bytes FROM entity_runtime_family_catalog_snapshot WHERE read_request_id=?", + read.readRequestId()) + .get(0, byte[].class)) + .isEqualTo(EntityRuntimeFamilyCatalogCodec.evidenceBytes(original)); + } + } + for (String change : + List.of( "UPDATE " + HISTORY + " SET checksum=checksum+1 WHERE version='1'", "UPDATE " + HISTORY + " SET success=false WHERE version='1025'", "UPDATE " + HISTORY + " SET success=false WHERE version='1026'", @@ -430,8 +481,17 @@ void missingTableClassificationAndMigrationChangesInvalidateWithoutRewritingEvid var read = request(); var original = f.owner().read(read); f.dsl.execute(change); - assertThatThrownBy(() -> f.owner().readExact(read)).isInstanceOf(RuntimeException.class); - assertThatThrownBy(() -> f.owner().read(request())).isInstanceOf(RuntimeException.class); + String expectedMessage = + change.contains("version='1025'") || change.contains("version='1026'") + ? "No durable Entity catalog epoch" + : "Entity schema/classification drift invalidates its epoch"; + assertThatThrownBy(() -> f.owner().readExact(read)) + .isInstanceOf(EntityRuntimeFamilyCatalogRepository.CatalogConflictException.class) + .hasMessage(expectedMessage); + assertThatThrownBy(() -> f.owner().read(request())) + .isInstanceOf(EntityRuntimeFamilyCatalogRepository.CatalogConflictException.class) + .hasMessage(expectedMessage); + assertThat(f.count("entity_runtime_family_catalog_snapshot")).isEqualTo(1); assertThat( f.dsl .fetchSingle( @@ -536,52 +596,90 @@ void forwardFrameGuardUpgradeRetainsOldEpochSnapshotAndHistoryWithoutResampling( @Test void directSqlPoisonFramesRefuseWithoutConsumingRequestIdentity() { try (var f = fixture(null, HISTORY)) { - var catalog = f.owner().read(request()).catalog(); - for (int mismatch = 0; mismatch < 6; mismatch++) { - var read = request(); - var snapshot = UUID.randomUUID(); - var evidence = new Evidence(read, snapshot, catalog); + var original = f.owner().read(request()); + for (String vector : + List.of( + "request-arbitrary", + "evidence-arbitrary", + "request-id", + "namespace", + "row-namespace", + "request-magic", + "request-trailing", + "request-truncated", + "evidence-request", + "snapshot", + "catalog-digest", + "catalog-bytes", + "evidence-magic", + "evidence-trailing", + "evidence-truncated")) { + Request read = request(); + UUID snapshot = UUID.randomUUID(); + var proposal = new Evidence(read, snapshot, original.catalog()); byte[] requestBytes = EntityRuntimeFamilyCatalogCodec.requestBytes(read); - byte[] evidenceBytes = EntityRuntimeFamilyCatalogCodec.evidenceBytes(evidence); - switch (mismatch) { - case 0 -> requestBytes = "arbitrary".getBytes(StandardCharsets.US_ASCII); - case 1 -> requestBytes = EntityRuntimeFamilyCatalogCodec.requestBytes(request()); - case 2 -> + byte[] evidenceBytes = EntityRuntimeFamilyCatalogCodec.evidenceBytes(proposal); + String namespace = read.targetNamespace(); + switch (vector) { + case "request-id" -> + requestBytes = EntityRuntimeFamilyCatalogCodec.requestBytes(request()); + case "namespace" -> requestBytes = EntityRuntimeFamilyCatalogCodec.requestBytes( new Request(read.readRequestId(), "other")); - case 3 -> evidenceBytes = "arbitrary".getBytes(StandardCharsets.US_ASCII); - case 4 -> + case "row-namespace" -> namespace = "other"; + case "request-arbitrary" -> + requestBytes = "arbitrary".getBytes(StandardCharsets.US_ASCII); + case "evidence-arbitrary" -> + evidenceBytes = "arbitrary".getBytes(StandardCharsets.US_ASCII); + case "request-magic" -> requestBytes[0] ^= 1; + case "request-trailing" -> + requestBytes = java.util.Arrays.copyOf(requestBytes, requestBytes.length + 1); + case "request-truncated" -> + requestBytes = java.util.Arrays.copyOf(requestBytes, requestBytes.length - 1); + case "evidence-request" -> evidenceBytes = EntityRuntimeFamilyCatalogCodec.evidenceBytes( - new Evidence(request(), snapshot, catalog)); - case 5 -> + new Evidence(request(), snapshot, original.catalog())); + case "snapshot" -> evidenceBytes = EntityRuntimeFamilyCatalogCodec.evidenceBytes( - new Evidence(read, UUID.randomUUID(), catalog)); - default -> throw new AssertionError("Unknown poison vector"); + new Evidence(read, UUID.randomUUID(), original.catalog())); + case "catalog-digest" -> + evidenceBytes[Integer.BYTES * 3 + requestBytes.length + Long.BYTES * 2] ^= 1; + case "catalog-bytes" -> evidenceBytes[evidenceBytes.length - 1] ^= 1; + case "evidence-magic" -> evidenceBytes[0] ^= 1; + case "evidence-trailing" -> + evidenceBytes = java.util.Arrays.copyOf(evidenceBytes, evidenceBytes.length + 1); + case "evidence-truncated" -> + evidenceBytes = java.util.Arrays.copyOf(evidenceBytes, evidenceBytes.length - 1); + default -> throw new AssertionError("Unknown poison vector: " + vector); } - byte[] poisonedRequest = requestBytes; - byte[] poisonedEvidence = evidenceBytes; + byte[] insertedRequest = requestBytes; + byte[] insertedEvidence = evidenceBytes; + String insertedNamespace = namespace; long before = f.count("entity_runtime_family_catalog_snapshot"); assertThatThrownBy( () -> f.dsl.execute( "INSERT INTO entity_runtime_family_catalog_snapshot(read_request_id,target_namespace,request_bytes,request_digest,snapshot_id,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)", read.readRequestId(), - read.targetNamespace(), - poisonedRequest, - EntityRuntimeFamilyCatalog.sha256(poisonedRequest), + insertedNamespace, + insertedRequest, + EntityRuntimeFamilyCatalog.sha256(insertedRequest), snapshot, - catalog.catalogEpoch(), - catalog.digest(), - poisonedEvidence, - EntityRuntimeFamilyCatalog.sha256(poisonedEvidence))) + original.catalog().catalogEpoch(), + original.catalog().digest(), + insertedEvidence, + EntityRuntimeFamilyCatalog.sha256(insertedEvidence))) + .as(vector) .hasMessageContaining("complete exact request and evidence"); assertThat(f.count("entity_runtime_family_catalog_snapshot")).isEqualTo(before); var committed = f.owner().read(read); - assertThat(f.owner().readExact(read)).isEqualTo(committed); assertThat(f.count("entity_runtime_family_catalog_snapshot")).isEqualTo(before + 1); + assertThat(f.owner().readExact(read)).isEqualTo(committed); + assertThat(f.owner().read(read)).isEqualTo(committed); + assertThat(f.owner().readExact(original.request())).isEqualTo(original); } } } diff --git a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java index 3b7b1bd403..c769a6767d 100644 --- a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -29,6 +29,7 @@ import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DataSourceTransactionManager; @@ -327,25 +328,52 @@ void schemaColumnConstraintTriggerRoutineAndRemovalChangesCannotResampleUnderSam try (Fixture f = fixture(null)) { Request retained = request(); f.owner().read(retained); + List history = f.historyRows(); + String epochs = f.catalogRows("social_runtime_family_catalog_epoch"); + String snapshots = f.catalogRows("social_runtime_family_catalog_snapshot"); if (change.startsWith("CREATE TRIGGER")) { f.dsl.execute( "CREATE FUNCTION social_runtime_family_immutable_probe() RETURNS trigger" + " LANGUAGE plpgsql AS $$ BEGIN RETURN NEW; END $$"); } f.dsl.execute(change); + boolean classifiedColumnRemoved = + change.startsWith("ALTER TABLE chat_messages RENAME COLUMN effect_id"); + Class expectedType = + classifiedColumnRemoved + ? DataAccessException.class + : SocialRuntimeFamilyCatalogRepository.CatalogConflictException.class; + String expectedMessage = + classifiedColumnRemoved + ? "Unclassified or changed" + : "Social schema/classification drift invalidates its epoch"; assertThatThrownBy(() -> f.owner().readExact(retained)) - .isInstanceOf(RuntimeException.class); - assertThatThrownBy(() -> f.owner().read(request())).isInstanceOf(RuntimeException.class); - assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(3); - assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); + .isInstanceOf(expectedType) + .hasMessageContaining(expectedMessage); + assertThatThrownBy(() -> f.owner().read(request())) + .isInstanceOf(expectedType) + .hasMessageContaining(expectedMessage); + assertThat(f.historyRows()).isEqualTo(history); + assertThat(f.catalogRows("social_runtime_family_catalog_epoch")).isEqualTo(epochs); + assertThat(f.catalogRows("social_runtime_family_catalog_snapshot")).isEqualTo(snapshots); } } try (Fixture f = fixture(null)) { Request retained = request(); f.owner().read(retained); + List history = f.historyRows(); + String epochs = f.catalogRows("social_runtime_family_catalog_epoch"); + String snapshots = f.catalogRows("social_runtime_family_catalog_snapshot"); f.dsl.execute("DROP TABLE guild_storage_items"); assertThatThrownBy(() -> f.owner().readExact(retained)) + .isInstanceOf(DataAccessException.class) .hasMessageContaining("Unclassified or changed"); + assertThatThrownBy(() -> f.owner().read(request())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Unclassified or changed"); + assertThat(f.historyRows()).isEqualTo(history); + assertThat(f.catalogRows("social_runtime_family_catalog_epoch")).isEqualTo(epochs); + assertThat(f.catalogRows("social_runtime_family_catalog_snapshot")).isEqualTo(snapshots); } } From 1a10b28abfdfc2b88099b0dee2b7acf63791cbda Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:22:52 +1300 Subject: [PATCH 07/11] Consolidate closed owner catalog validation and tighten drift proof --- .../realm-routing-and-playable-state.md | 2 + .../AutomationRuntimeFamilyCatalog.java | 232 ++++++----------- .../entity/EntityRuntimeFamilyCatalog.java | 171 ++++--------- .../RuntimeFamilyCatalogValidation.java | 156 ++++++++++++ .../social/SocialRuntimeFamilyCatalog.java | 241 ++++++------------ .../world/WorldRuntimeFamilyCatalog.java | 182 ++++--------- .../RuntimeFamilyCatalogValidationTest.java | 119 +++++++++ ...eFamilyCatalogPostgresIntegrationTest.java | 20 +- 8 files changed, 556 insertions(+), 567 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidation.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidationTest.java diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index c8d49a9035..719d6a3e3f 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -31,6 +31,8 @@ Receiving proof243/244 passes six World [value/codec cases](../../../services/co Review corrections retain the published catalog migrations and add forward owner seals for view definitions and options. World V1047 supplies the exact snapshot-frame and installed-script guard; its normative behavior remains at the linked World data owner. Later Social V1006 is qualified by proof281: all fifteen catalog cases and the full 38-case integration suite pass, including twelve poisoned-frame vectors, same-identity recovery and retained V1005 upgrade evidence, with generation and selected checks. Proof275/276 passes 252 actual PostgreSQL cases across the affected Entity, World, Automation and Social suites, including seventeen World catalog cases, the receipt-digest migration composition and thirteen fixed-preset upgrade cases. World's controlled receipt probe now installs every source World/Saga table before reaching the full census; its predicate-only clone is not production authority. The fixed-preset retention case compares all original row values and `xmin` while separately asserting the three new catalog tables, two retained epochs and empty request snapshots. Proof275 retains that comparison failure; proof276 passes the corrected thirty-one World cases and selected integration static, formatting and documentation checks. The four mandatory-Docker catalog fixtures and combined forward-version checks pass their canonical contracts. Proof273 separately passes twenty-five Common codec cases, five Game Design compositions and eighteen physical mTLS client cases after the shared framing helper adds defensive copies; proof272's earlier mutable-array analysis failure remains recorded. These component proofs do not expand the source or runtime authority boundary. +CLI4 corrections consolidate the four owner values' strict UTF-8, closed JSON, bounded arrays, schema-fact ordering and table/component completeness checks in the existing [shared runtime-catalog package](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidation.java). Owner schemas, enums, disposition rules and exact retained bytes remain local and unchanged. Proof363 passes all33 Common catalog/structural cases and17 actual World PostgreSQL cases, including specific drift failure types/messages rather than arbitrary runtime exceptions. Proof364 passes the other three owner catalog PostgreSQL suites and enabled Common main/test plus World integration static/format checks; these controlled component results do not establish global installation, manifests or FRESH completion. Mandatory Docker proof remains non-skipping. + Remaining batch obligations are the genuine World-owned global enrollment/required-owner-set source, remaining actual owner catalogs/epochs, complete build/lifecycle/namespace/generation-bound FRESH manifest production and immutable authenticated readback, genuine protected private authorization/runtime/materialization, and complete-set aggregation into the existing canonical CLOSED pointer/audit/outcome owner. Current World canonical materialization is still public `SHARED` and original-`StartSession`-only; no private FRESH relabelling is valid. The existing unregistered [canonical CLOSED owner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java) supplies public initial CLOSED persistence, not the missing private aggregate; the registered legacy routing model described elsewhere remains narrower. No second private pointer authority is added. CLOSED-to-OPEN, private first admission, issuer/custody/PKI qualification, runtime/default registration, operational activation, reset and Unit1B remain held. Capability ratings are unchanged; this source batch does not complete FRESH capability. ## Capability Status diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java index fbfae87a80..34affb2a44 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java @@ -1,23 +1,19 @@ package net.firedevops.firemud.common.automation; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.array; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.fields; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.identifier; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.text; + import com.google.protobuf.ByteString; -import java.nio.ByteBuffer; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.ArrayList; -import java.util.HashSet; -import java.util.HexFormat; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.databind.DeserializationFeature; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation; import tools.jackson.databind.JsonNode; -import tools.jackson.databind.json.JsonMapper; /** Exact Automation SQL source classification; neither enrollment nor a FRESH state manifest. */ public final class AutomationRuntimeFamilyCatalog { @@ -27,11 +23,6 @@ public final class AutomationRuntimeFamilyCatalog { public static final int MAX_FAMILIES = 512; public static final int MAX_FACTS = 16384; public static final int MAX_NON_SQL_GAPS = 32; - private static final JsonMapper JSON = - JsonMapper.builder() - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .build(); public enum Role { RUNTIME_PAYLOAD, @@ -153,12 +144,7 @@ public record NonSqlGap(GapId id, GapDisposition disposition, String ownerConseq public record SchemaFact(FactKind kind, String identity, String definitionDigest) { public SchemaFact { Objects.requireNonNull(kind, "kind"); - if (identity == null - || identity.isBlank() - || identity.length() > 8192 - || identity.codePoints().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException("Invalid schema fact identity"); - } + RuntimeFamilyCatalogValidation.factIdentity(identity); requireDigest(definitionDigest); } } @@ -243,123 +229,88 @@ public static AutomationRuntimeFamilyCatalog fromStored(byte[] bytes) { if (bytes == null || bytes.length == 0 || bytes.length > MAX_CATALOG_BYTES) { throw new IllegalArgumentException("Automation catalog exceeds complete-source bound"); } - try { - String decoded = - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(bytes)) - .toString(); - JsonNode root = JSON.readTree(decoded); + JsonNode root = RuntimeFamilyCatalogValidation.decode(bytes, MAX_CATALOG_BYTES); + fields( + root, Set.of("schema", "owner", "catalogEpoch", "families", "schemaFacts", "nonSqlGaps")); + if (!SCHEMA.equals(text(root, "schema")) || !OWNER.equals(text(root, "owner"))) { + throw new IllegalArgumentException("Unsupported Automation schema/owner"); + } + String epochText = text(root, "catalogEpoch"); + if (!epochText.matches("[1-9][0-9]{0,18}")) throw new IllegalArgumentException("Invalid epoch"); + long epoch = Long.parseLong(epochText); + var families = new ArrayList(); + var facts = new ArrayList(); + var gaps = new ArrayList(); + array(root.get("families"), MAX_FAMILIES); + String previous = ""; + for (JsonNode node : root.get("families")) { fields( - root, Set.of("schema", "owner", "catalogEpoch", "families", "schemaFacts", "nonSqlGaps")); - if (!SCHEMA.equals(text(root, "schema")) || !OWNER.equals(text(root, "owner"))) { - throw new IllegalArgumentException("Unsupported Automation schema/owner"); - } - String epochText = text(root, "catalogEpoch"); - if (!epochText.matches("[1-9][0-9]{0,18}")) - throw new IllegalArgumentException("Invalid epoch"); - long epoch = Long.parseLong(epochText); - var families = new ArrayList(); - var facts = new ArrayList(); - var gaps = new ArrayList(); - array(root.get("families"), MAX_FAMILIES); - String previous = ""; - for (JsonNode node : root.get("families")) { - fields( - node, - Set.of( - "familyId", - "relation", - "component", - "role", - "stateClass", - "freshDisposition", - "retentionDisposition", - "ownerConsequence")); - Family family = - new Family( - text(node, "familyId"), - text(node, "relation"), - text(node, "component"), - Role.valueOf(text(node, "role")), - StateClass.valueOf(text(node, "stateClass")), - FreshDisposition.valueOf(text(node, "freshDisposition")), - RetentionDisposition.valueOf(text(node, "retentionDisposition")), - text(node, "ownerConsequence")); - if (previous.compareTo(family.familyId()) >= 0) - throw new IllegalArgumentException("Unordered/duplicate family"); - previous = family.familyId(); - families.add(family); - } - array(root.get("schemaFacts"), MAX_FACTS); - previous = ""; - Set tables = new HashSet<>(); - Set columns = new HashSet<>(); - for (JsonNode node : root.get("schemaFacts")) { - fields(node, Set.of("kind", "identity", "definitionDigest")); - SchemaFact fact = - new SchemaFact( - FactKind.valueOf(text(node, "kind")), - text(node, "identity"), - text(node, "definitionDigest")); - String key = fact.kind().name() + "/" + fact.identity(); - if (previous.compareTo(key) >= 0) - throw new IllegalArgumentException("Unordered/duplicate schema fact"); - previous = key; - if (fact.kind() == FactKind.TABLE) tables.add(fact.identity()); - if (fact.kind() == FactKind.COLUMN) columns.add(fact.identity()); - facts.add(fact); - } - Set declared = new HashSet<>(); - for (Family family : families) { - if (!tables.contains(family.relation())) - throw new IllegalArgumentException("Missing family table"); - if (family.component().isEmpty()) declared.add(family.relation()); - else if (!columns.contains(family.familyId())) - throw new IllegalArgumentException("Missing family component"); - } - if (!tables.equals(declared) || tables.isEmpty()) { - throw new IllegalArgumentException("Every installed table needs an explicit disposition"); - } - array(root.get("nonSqlGaps"), MAX_NON_SQL_GAPS); - previous = ""; - for (JsonNode node : root.get("nonSqlGaps")) { - fields(node, Set.of("id", "disposition", "ownerConsequence")); - NonSqlGap gap = - new NonSqlGap( - GapId.valueOf(text(node, "id")), - GapDisposition.valueOf(text(node, "disposition")), - text(node, "ownerConsequence")); - if (previous.compareTo(gap.id().name()) >= 0) - throw new IllegalArgumentException("Unordered/duplicate non-SQL gap"); - previous = gap.id().name(); - gaps.add(gap); - } - return new AutomationRuntimeFamilyCatalog(epoch, families, facts, gaps, bytes); - } catch (java.io.IOException | tools.jackson.core.JacksonException invalid) { - throw new IllegalArgumentException("Invalid closed Automation catalog", invalid); + node, + Set.of( + "familyId", + "relation", + "component", + "role", + "stateClass", + "freshDisposition", + "retentionDisposition", + "ownerConsequence")); + Family family = + new Family( + text(node, "familyId"), + text(node, "relation"), + text(node, "component"), + Role.valueOf(text(node, "role")), + StateClass.valueOf(text(node, "stateClass")), + FreshDisposition.valueOf(text(node, "freshDisposition")), + RetentionDisposition.valueOf(text(node, "retentionDisposition")), + text(node, "ownerConsequence")); + if (previous.compareTo(family.familyId()) >= 0) + throw new IllegalArgumentException("Unordered/duplicate family"); + previous = family.familyId(); + families.add(family); + } + var structuralFacts = + RuntimeFamilyCatalogValidation.schemaFacts(root.get("schemaFacts"), MAX_FACTS); + for (var fact : structuralFacts) { + facts.add( + new SchemaFact(FactKind.valueOf(fact.kind()), fact.identity(), fact.definitionDigest())); + } + RuntimeFamilyCatalogValidation.requireComplete( + families.stream() + .map( + family -> + new RuntimeFamilyCatalogValidation.FamilyComponent( + family.relation(), family.component())) + .toList(), + structuralFacts); + array(root.get("nonSqlGaps"), MAX_NON_SQL_GAPS); + previous = ""; + for (JsonNode node : root.get("nonSqlGaps")) { + fields(node, Set.of("id", "disposition", "ownerConsequence")); + NonSqlGap gap = + new NonSqlGap( + GapId.valueOf(text(node, "id")), + GapDisposition.valueOf(text(node, "disposition")), + text(node, "ownerConsequence")); + if (previous.compareTo(gap.id().name()) >= 0) + throw new IllegalArgumentException("Unordered/duplicate non-SQL gap"); + previous = gap.id().name(); + gaps.add(gap); } + return new AutomationRuntimeFamilyCatalog(epoch, families, facts, gaps, bytes); } static void requireUuid(UUID value) { - if (value == null || value.equals(new UUID(0, 0))) - throw new IllegalArgumentException("Non-nil UUID required"); + RuntimeFamilyCatalogValidation.requireUuid(value); } static void requireDigest(String value) { - if (value == null || !value.matches("sha256:[0-9a-f]{64}")) - throw new IllegalArgumentException("SHA-256 required"); + RuntimeFamilyCatalogValidation.requireDigest(value); } public static String sha256(byte[] bytes) { - try { - return "sha256:" - + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 required by Java", impossible); - } + return RuntimeFamilyCatalogValidation.sha256(bytes); } private static void consequence(String value) { @@ -370,31 +321,4 @@ private static void consequence(String value) { throw new IllegalArgumentException("Bounded explicit owner consequence required"); } } - - private static void identifier(String value) { - if (value == null || !value.matches("[a-z][a-z0-9_]{0,62}")) - throw new IllegalArgumentException("Schema identifier required"); - } - - private static void fields(JsonNode node, Set expected) { - if (node == null || !node.isObject()) - throw new IllegalArgumentException("Closed object required"); - Set actual = new HashSet<>(); - node.propertyNames().forEach(actual::add); - if (!actual.equals(expected)) - throw new IllegalArgumentException("Unknown or missing catalog field"); - } - - private static String text(JsonNode node, String key) { - JsonNode value = node.get(key); - if (value == null || !value.isTextual()) - throw new IllegalArgumentException("Text field required"); - return value.asText(); - } - - private static void array(JsonNode node, int maximum) { - if (node == null || !node.isArray() || node.isEmpty() || node.size() > maximum) { - throw new IllegalArgumentException("Complete bounded catalog array required"); - } - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java index 5d0c113707..4b78eb3013 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java @@ -1,23 +1,19 @@ package net.firedevops.firemud.common.entity; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.array; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.fields; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.identifier; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.text; + import com.google.protobuf.ByteString; -import java.nio.ByteBuffer; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.ArrayList; -import java.util.HashSet; -import java.util.HexFormat; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.databind.DeserializationFeature; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation; import tools.jackson.databind.JsonNode; -import tools.jackson.databind.json.JsonMapper; /** Exact Entity-local schema facts. Conditional/unresolved entries never qualify runtime state. */ public final class EntityRuntimeFamilyCatalog { @@ -26,11 +22,6 @@ public final class EntityRuntimeFamilyCatalog { public static final int MAX_CATALOG_BYTES = 2 * 1024 * 1024; public static final int MAX_FAMILIES = 512; public static final int MAX_FACTS = 16384; - private static final JsonMapper JSON = - JsonMapper.builder() - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .build(); public enum Role { RUNTIME_PAYLOAD, @@ -241,120 +232,60 @@ public int hashCode() { public static EntityRuntimeFamilyCatalog fromStored(byte[] bytes) { if (bytes == null || bytes.length == 0 || bytes.length > MAX_CATALOG_BYTES) throw new IllegalArgumentException("Entity catalog exceeds complete-source bound"); - try { - String json = - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(bytes)) - .toString(); - JsonNode root = JSON.readTree(json); - fields(root, Set.of("schema", "owner", "catalogEpoch", "families", "schemaFacts")); - if (!SCHEMA.equals(text(root, "schema")) || !OWNER.equals(text(root, "owner"))) - throw new IllegalArgumentException("Unsupported Entity catalog schema/owner"); - String epochText = text(root, "catalogEpoch"); - if (!epochText.matches("[1-9][0-9]{0,18}")) - throw new IllegalArgumentException("Invalid epoch"); - long epoch = Long.parseLong(epochText); - var families = new ArrayList(); - var facts = new ArrayList(); - array(root.get("families"), MAX_FAMILIES); - String previous = ""; - for (JsonNode node : root.get("families")) { - fields( - node, - Set.of("familyId", "relation", "component", "role", "stateClass", "freshDisposition")); - Family family = - new Family( - text(node, "familyId"), - text(node, "relation"), - text(node, "component"), - Role.valueOf(text(node, "role")), - StateClass.valueOf(text(node, "stateClass")), - FreshDisposition.valueOf(text(node, "freshDisposition"))); - if (previous.compareTo(family.familyId()) >= 0) - throw new IllegalArgumentException("Unordered/duplicate family"); - previous = family.familyId(); - families.add(family); - } - array(root.get("schemaFacts"), MAX_FACTS); - previous = ""; - Set tables = new HashSet<>(); - Set columns = new HashSet<>(); - for (JsonNode node : root.get("schemaFacts")) { - fields(node, Set.of("kind", "identity", "definitionDigest")); - SchemaFact fact = - new SchemaFact( - FactKind.valueOf(text(node, "kind")), - text(node, "identity"), - text(node, "definitionDigest")); - String key = fact.kind().name() + "/" + fact.identity(); - if (previous.compareTo(key) >= 0) - throw new IllegalArgumentException("Unordered/duplicate schema fact"); - previous = key; - if (fact.kind() == FactKind.TABLE) tables.add(fact.identity()); - if (fact.kind() == FactKind.COLUMN) columns.add(fact.identity()); - facts.add(fact); - } - Set declaredTables = new HashSet<>(); - for (Family family : families) { - if (!tables.contains(family.relation())) - throw new IllegalArgumentException("Missing family table"); - if (family.component().isEmpty()) declaredTables.add(family.relation()); - else if (!columns.contains(family.familyId())) - throw new IllegalArgumentException("Missing family component"); - } - if (!tables.equals(declaredTables) || tables.isEmpty()) - throw new IllegalArgumentException("Every installed table needs an explicit disposition"); - return new EntityRuntimeFamilyCatalog(epoch, families, facts, bytes); - } catch (java.io.IOException | tools.jackson.core.JacksonException invalid) { - throw new IllegalArgumentException("Invalid closed Entity catalog", invalid); + JsonNode root = RuntimeFamilyCatalogValidation.decode(bytes, MAX_CATALOG_BYTES); + fields(root, Set.of("schema", "owner", "catalogEpoch", "families", "schemaFacts")); + if (!SCHEMA.equals(text(root, "schema")) || !OWNER.equals(text(root, "owner"))) + throw new IllegalArgumentException("Unsupported Entity catalog schema/owner"); + String epochText = text(root, "catalogEpoch"); + if (!epochText.matches("[1-9][0-9]{0,18}")) throw new IllegalArgumentException("Invalid epoch"); + long epoch = Long.parseLong(epochText); + var families = new ArrayList(); + var facts = new ArrayList(); + array(root.get("families"), MAX_FAMILIES); + String previous = ""; + for (JsonNode node : root.get("families")) { + fields( + node, + Set.of("familyId", "relation", "component", "role", "stateClass", "freshDisposition")); + Family family = + new Family( + text(node, "familyId"), + text(node, "relation"), + text(node, "component"), + Role.valueOf(text(node, "role")), + StateClass.valueOf(text(node, "stateClass")), + FreshDisposition.valueOf(text(node, "freshDisposition"))); + if (previous.compareTo(family.familyId()) >= 0) + throw new IllegalArgumentException("Unordered/duplicate family"); + previous = family.familyId(); + families.add(family); + } + var structuralFacts = + RuntimeFamilyCatalogValidation.schemaFacts(root.get("schemaFacts"), MAX_FACTS); + for (var fact : structuralFacts) { + facts.add( + new SchemaFact(FactKind.valueOf(fact.kind()), fact.identity(), fact.definitionDigest())); } + RuntimeFamilyCatalogValidation.requireComplete( + families.stream() + .map( + family -> + new RuntimeFamilyCatalogValidation.FamilyComponent( + family.relation(), family.component())) + .toList(), + structuralFacts); + return new EntityRuntimeFamilyCatalog(epoch, families, facts, bytes); } static void requireUuid(UUID value) { - if (value == null || value.equals(new UUID(0, 0))) - throw new IllegalArgumentException("Non-nil UUID required"); + RuntimeFamilyCatalogValidation.requireUuid(value); } static void requireDigest(String value) { - if (value == null || !value.matches("sha256:[0-9a-f]{64}")) - throw new IllegalArgumentException("SHA-256 required"); + RuntimeFamilyCatalogValidation.requireDigest(value); } public static String sha256(byte[] bytes) { - try { - return "sha256:" - + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 required by Java", impossible); - } - } - - private static void identifier(String value) { - if (value == null || !value.matches("[a-z][a-z0-9_]{0,62}")) - throw new IllegalArgumentException("Schema identifier required"); - } - - private static void fields(JsonNode node, Set expected) { - if (node == null || !node.isObject()) - throw new IllegalArgumentException("Closed object required"); - Set actual = new HashSet<>(); - node.propertyNames().forEach(actual::add); - if (!actual.equals(expected)) - throw new IllegalArgumentException("Unknown or missing catalog field"); - } - - private static String text(JsonNode node, String key) { - JsonNode value = node.get(key); - if (value == null || !value.isTextual()) - throw new IllegalArgumentException("Text field required"); - return value.asText(); - } - - private static void array(JsonNode node, int maximum) { - if (node == null || !node.isArray() || node.isEmpty() || node.size() > maximum) - throw new IllegalArgumentException("Complete bounded catalog array required"); + return RuntimeFamilyCatalogValidation.sha256(bytes); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidation.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidation.java new file mode 100644 index 0000000000..986e1f3e7e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidation.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.runtimecatalog; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Internal structural checks shared by the four foreign-owner catalog values. Public only for their + * separate packages; owner schemas, fact enums and disposition authority remain local. + */ +public final class RuntimeFamilyCatalogValidation { + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private RuntimeFamilyCatalogValidation() {} + + public static JsonNode decode(byte[] bytes, int maximum) { + if (bytes == null || bytes.length == 0 || bytes.length > maximum) + throw new IllegalArgumentException("Catalog exceeds complete-source bound"); + try { + String decoded = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + return JSON.readTree(decoded); + } catch (IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Invalid closed catalog", invalid); + } + } + + public static void fields(JsonNode node, Set expected) { + if (node == null || !node.isObject()) + throw new IllegalArgumentException("Closed object required"); + Set actual = new HashSet<>(); + node.propertyNames().forEach(actual::add); + if (!actual.equals(expected)) + throw new IllegalArgumentException("Unknown or missing catalog field"); + } + + public static String text(JsonNode node, String key) { + JsonNode value = node.get(key); + if (value == null || !value.isTextual()) + throw new IllegalArgumentException("Text field required"); + return value.asText(); + } + + public static void array(JsonNode node, int maximum) { + if (node == null || !node.isArray() || node.isEmpty() || node.size() > maximum) + throw new IllegalArgumentException("Complete bounded catalog array required"); + } + + /** Structural projection only; each owner must still parse kind through its own enum. */ + public record SchemaFact(String kind, String identity, String definitionDigest) { + public SchemaFact { + if (kind == null || kind.isBlank()) throw new IllegalArgumentException("Fact kind required"); + factIdentity(identity); + requireDigest(definitionDigest); + } + } + + public static List schemaFacts(JsonNode node, int maximum) { + array(node, maximum); + var facts = new ArrayList(); + String previous = ""; + for (JsonNode value : node) { + fields(value, Set.of("kind", "identity", "definitionDigest")); + var fact = + new SchemaFact( + text(value, "kind"), text(value, "identity"), text(value, "definitionDigest")); + String key = fact.kind() + "/" + fact.identity(); + if (previous.compareTo(key) >= 0) + throw new IllegalArgumentException("Unordered/duplicate schema fact"); + previous = key; + facts.add(fact); + } + return List.copyOf(facts); + } + + public record FamilyComponent(String relation, String component) { + public FamilyComponent { + identifier(relation); + if (component == null) throw new IllegalArgumentException("Component required"); + if (!component.isEmpty()) identifier(component); + } + } + + public static void requireComplete(List families, List facts) { + Set tables = new HashSet<>(); + Set columns = new HashSet<>(); + for (SchemaFact fact : facts) { + if (fact.kind().equals("TABLE")) tables.add(fact.identity()); + if (fact.kind().equals("COLUMN")) columns.add(fact.identity()); + } + Set declaredTables = new HashSet<>(); + for (FamilyComponent family : families) { + if (!tables.contains(family.relation())) + throw new IllegalArgumentException("Missing family table"); + if (family.component().isEmpty()) declaredTables.add(family.relation()); + else if (!columns.contains(family.relation() + "." + family.component())) + throw new IllegalArgumentException("Missing family component"); + } + if (!tables.equals(declaredTables) || tables.isEmpty()) + throw new IllegalArgumentException("Every installed table needs an explicit disposition"); + } + + public static void factIdentity(String value) { + if (value == null + || value.isBlank() + || value.length() > 8192 + || value.codePoints().anyMatch(Character::isISOControl)) + throw new IllegalArgumentException("Invalid schema fact identity"); + } + + public static void identifier(String value) { + if (value == null || !value.matches("[a-z][a-z0-9_]{0,62}")) + throw new IllegalArgumentException("Schema identifier required"); + } + + public static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) + throw new IllegalArgumentException("Non-nil UUID required"); + } + + public static void requireDigest(String value) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException("SHA-256 required"); + } + + public static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 required by Java", impossible); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalog.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalog.java index d5c1254f72..b9fce906e4 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalog.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalog.java @@ -1,24 +1,21 @@ package net.firedevops.firemud.common.social; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.array; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.fields; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.identifier; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.text; + import com.google.protobuf.ByteString; -import java.nio.ByteBuffer; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashSet; -import java.util.HexFormat; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.databind.DeserializationFeature; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation; import tools.jackson.databind.JsonNode; -import tools.jackson.databind.json.JsonMapper; /** Immutable exact Social-local schema classification, not a row inventory or FRESH manifest. */ public final class SocialRuntimeFamilyCatalog { @@ -28,12 +25,6 @@ public final class SocialRuntimeFamilyCatalog { public static final int MAX_FAMILIES = 512; public static final int MAX_FACTS = 16384; - private static final JsonMapper JSON = - JsonMapper.builder() - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .build(); - public enum Role { GUILD_DEFINITION_ACL, GUILD_MEMBERSHIP_ACL, @@ -150,12 +141,7 @@ public record Family( public record SchemaFact(FactKind kind, String identity, String definitionDigest) { public SchemaFact { Objects.requireNonNull(kind, "kind"); - if (identity == null - || identity.isBlank() - || identity.length() > 8192 - || identity.codePoints().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException("Invalid schema fact identity"); - } + RuntimeFamilyCatalogValidation.factIdentity(identity); requireDigest(definitionDigest); } } @@ -240,159 +226,90 @@ public static SocialRuntimeFamilyCatalog fromStored(byte[] bytes) { if (bytes == null || bytes.length == 0 || bytes.length > MAX_CATALOG_BYTES) { throw new IllegalArgumentException("Social catalog exceeds its complete-source bound"); } - try { - String text = - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(bytes)) - .toString(); - JsonNode root = JSON.readTree(text); + JsonNode root = RuntimeFamilyCatalogValidation.decode(bytes, MAX_CATALOG_BYTES); + fields( + root, + Set.of( + "schema", + "owner", + "catalogEpoch", + "families", + "schemaFacts", + "unimplementedContracts")); + if (!SCHEMA.equals(text(root, "schema")) || !OWNER.equals(text(root, "owner"))) { + throw new IllegalArgumentException("Unsupported Social catalog schema/owner"); + } + String epochText = text(root, "catalogEpoch"); + if (!epochText.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("Invalid Social catalog epoch"); + } + long epoch = Long.parseLong(epochText); + var families = new ArrayList(); + var facts = new ArrayList(); + var gaps = new ArrayList(); + array(root.get("families"), MAX_FAMILIES); + String previous = ""; + Set familyIds = new HashSet<>(); + for (JsonNode node : root.get("families")) { fields( - root, - Set.of( - "schema", - "owner", - "catalogEpoch", - "families", - "schemaFacts", - "unimplementedContracts")); - if (!SCHEMA.equals(text(root, "schema")) || !OWNER.equals(text(root, "owner"))) { - throw new IllegalArgumentException("Unsupported Social catalog schema/owner"); - } - String epochText = text(root, "catalogEpoch"); - if (!epochText.matches("[1-9][0-9]{0,18}")) { - throw new IllegalArgumentException("Invalid Social catalog epoch"); - } - long epoch = Long.parseLong(epochText); - var families = new ArrayList(); - var facts = new ArrayList(); - var gaps = new ArrayList(); - array(root.get("families"), MAX_FAMILIES); - String previous = ""; - Set familyIds = new HashSet<>(); - for (JsonNode node : root.get("families")) { - fields( - node, - Set.of("familyId", "relation", "component", "role", "freshDisposition", "targetOwner")); - Family family = - new Family( - text(node, "familyId"), - text(node, "relation"), - text(node, "component"), - Role.valueOf(text(node, "role")), - FreshDisposition.valueOf(text(node, "freshDisposition")), - TargetOwner.valueOf(text(node, "targetOwner"))); - if (previous.compareTo(family.familyId()) >= 0 || !familyIds.add(family.familyId())) { - throw new IllegalArgumentException("Unordered/duplicate Social family"); - } - previous = family.familyId(); - families.add(family); + node, + Set.of("familyId", "relation", "component", "role", "freshDisposition", "targetOwner")); + Family family = + new Family( + text(node, "familyId"), + text(node, "relation"), + text(node, "component"), + Role.valueOf(text(node, "role")), + FreshDisposition.valueOf(text(node, "freshDisposition")), + TargetOwner.valueOf(text(node, "targetOwner"))); + if (previous.compareTo(family.familyId()) >= 0 || !familyIds.add(family.familyId())) { + throw new IllegalArgumentException("Unordered/duplicate Social family"); } - array(root.get("schemaFacts"), MAX_FACTS); - previous = ""; - Set tables = new HashSet<>(); - Set columns = new HashSet<>(); - for (JsonNode node : root.get("schemaFacts")) { - fields(node, Set.of("kind", "identity", "definitionDigest")); - SchemaFact fact = - new SchemaFact( - FactKind.valueOf(text(node, "kind")), - text(node, "identity"), - text(node, "definitionDigest")); - String key = fact.kind().name() + "/" + fact.identity(); - if (previous.compareTo(key) >= 0) { - throw new IllegalArgumentException("Unordered/duplicate Social schema fact"); - } - previous = key; - if (fact.kind() == FactKind.TABLE) tables.add(fact.identity()); - if (fact.kind() == FactKind.COLUMN) columns.add(fact.identity()); - facts.add(fact); - } - Set declaredTables = new HashSet<>(); - for (Family family : families) { - if (!tables.contains(family.relation())) { - throw new IllegalArgumentException("Missing Social family table fact"); - } - if (family.component().isEmpty()) { - declaredTables.add(family.relation()); - } else if (!columns.contains(family.familyId())) { - throw new IllegalArgumentException("Missing Social family component fact"); - } - } - if (!tables.equals(declaredTables) || tables.isEmpty()) { - throw new IllegalArgumentException("Every installed Social table needs a disposition"); - } - array(root.get("unimplementedContracts"), ContractGap.values().length); - previous = ""; - Set uniqueGaps = EnumSet.noneOf(ContractGap.class); - for (JsonNode node : root.get("unimplementedContracts")) { - if (!node.isTextual()) - throw new IllegalArgumentException("Text Social contract gap required"); - ContractGap gap = ContractGap.valueOf(node.asText()); - if (previous.compareTo(gap.name()) >= 0 || !uniqueGaps.add(gap)) { - throw new IllegalArgumentException("Unordered/duplicate Social contract gap"); - } - previous = gap.name(); - gaps.add(gap); - } - if (!uniqueGaps.equals(EnumSet.allOf(ContractGap.class))) { - throw new IllegalArgumentException( - "Social catalog must retain every known contract blocker"); + previous = family.familyId(); + families.add(family); + } + var structuralFacts = + RuntimeFamilyCatalogValidation.schemaFacts(root.get("schemaFacts"), MAX_FACTS); + for (var fact : structuralFacts) { + facts.add( + new SchemaFact(FactKind.valueOf(fact.kind()), fact.identity(), fact.definitionDigest())); + } + RuntimeFamilyCatalogValidation.requireComplete( + families.stream() + .map( + family -> + new RuntimeFamilyCatalogValidation.FamilyComponent( + family.relation(), family.component())) + .toList(), + structuralFacts); + array(root.get("unimplementedContracts"), ContractGap.values().length); + previous = ""; + Set uniqueGaps = EnumSet.noneOf(ContractGap.class); + for (JsonNode node : root.get("unimplementedContracts")) { + if (!node.isTextual()) + throw new IllegalArgumentException("Text Social contract gap required"); + ContractGap gap = ContractGap.valueOf(node.asText()); + if (previous.compareTo(gap.name()) >= 0 || !uniqueGaps.add(gap)) { + throw new IllegalArgumentException("Unordered/duplicate Social contract gap"); } - return new SocialRuntimeFamilyCatalog(epoch, families, facts, gaps, bytes); - } catch (java.io.IOException | tools.jackson.core.JacksonException invalid) { - throw new IllegalArgumentException("Invalid closed Social catalog", invalid); + previous = gap.name(); + gaps.add(gap); + } + if (!uniqueGaps.equals(EnumSet.allOf(ContractGap.class))) { + throw new IllegalArgumentException("Social catalog must retain every known contract blocker"); } + return new SocialRuntimeFamilyCatalog(epoch, families, facts, gaps, bytes); } static void requireUuid(UUID value) { - if (value == null || value.equals(new UUID(0, 0))) { - throw new IllegalArgumentException("Non-nil UUID required"); - } + RuntimeFamilyCatalogValidation.requireUuid(value); } static void requireDigest(String value) { - if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { - throw new IllegalArgumentException("SHA-256 required"); - } + RuntimeFamilyCatalogValidation.requireDigest(value); } public static String sha256(byte[] bytes) { - try { - return "sha256:" - + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 required by Java", impossible); - } - } - - private static void identifier(String value) { - if (value == null || !value.matches("[a-z][a-z0-9_]{0,62}")) { - throw new IllegalArgumentException("Schema identifier required"); - } - } - - private static void fields(JsonNode node, Set expected) { - if (node == null || !node.isObject()) - throw new IllegalArgumentException("Closed object required"); - Set actual = new HashSet<>(); - node.propertyNames().forEach(actual::add); - if (!actual.equals(expected)) - throw new IllegalArgumentException("Unknown or missing Social field"); - } - - private static String text(JsonNode node, String key) { - JsonNode value = node.get(key); - if (value == null || !value.isTextual()) - throw new IllegalArgumentException("Text field required"); - return value.asText(); - } - - private static void array(JsonNode node, int maximum) { - if (node == null || !node.isArray() || node.isEmpty() || node.size() > maximum) { - throw new IllegalArgumentException("Complete bounded Social catalog array required"); - } + return RuntimeFamilyCatalogValidation.sha256(bytes); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java index bc42b1c1e5..1332a17c4d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java @@ -1,23 +1,19 @@ package net.firedevops.firemud.common.world; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.array; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.fields; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.identifier; +import static net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.text; + import com.google.protobuf.ByteString; -import java.nio.ByteBuffer; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.ArrayList; -import java.util.HashSet; -import java.util.HexFormat; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.databind.DeserializationFeature; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation; import tools.jackson.databind.JsonNode; -import tools.jackson.databind.json.JsonMapper; /** Immutable exact World-local schema classification, not runtime-state or FRESH completeness. */ public final class WorldRuntimeFamilyCatalog { @@ -26,11 +22,6 @@ public final class WorldRuntimeFamilyCatalog { public static final int MAX_CATALOG_BYTES = 2 * 1024 * 1024; public static final int MAX_FAMILIES = 512; public static final int MAX_FACTS = 16384; - private static final JsonMapper JSON = - JsonMapper.builder() - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .build(); public enum Role { RUNTIME_PAYLOAD, @@ -120,12 +111,7 @@ public record Family( public record SchemaFact(FactKind kind, String identity, String definitionDigest) { public SchemaFact { Objects.requireNonNull(kind, "kind"); - if (identity == null - || identity.isBlank() - || identity.length() > 8192 - || identity.codePoints().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException("Invalid schema fact identity"); - } + RuntimeFamilyCatalogValidation.factIdentity(identity); requireDigest(definitionDigest); } } @@ -202,123 +188,61 @@ public static WorldRuntimeFamilyCatalog fromStored(byte[] bytes) { if (bytes == null || bytes.length == 0 || bytes.length > MAX_CATALOG_BYTES) { throw new IllegalArgumentException("World catalog exceeds its complete-source bound"); } - try { - String text = - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(bytes)) - .toString(); - JsonNode root = JSON.readTree(text); - fields(root, Set.of("schema", "owner", "catalogEpoch", "families", "schemaFacts")); - if (!SCHEMA.equals(text(root, "schema")) || !OWNER.equals(text(root, "owner"))) { - throw new IllegalArgumentException("Unsupported World catalog schema/owner"); - } - String epochText = text(root, "catalogEpoch"); - if (!epochText.matches("[1-9][0-9]{0,18}")) - throw new IllegalArgumentException("Invalid epoch"); - long epoch = Long.parseLong(epochText); - var families = new ArrayList(); - var facts = new ArrayList(); - array(root.get("families"), MAX_FAMILIES); - String previous = ""; - for (JsonNode node : root.get("families")) { - fields( - node, - Set.of("familyId", "relation", "component", "role", "stateClass", "freshDisposition")); - Family family = - new Family( - text(node, "familyId"), - text(node, "relation"), - text(node, "component"), - Role.valueOf(text(node, "role")), - StateClass.valueOf(text(node, "stateClass")), - FreshDisposition.valueOf(text(node, "freshDisposition"))); - if (previous.compareTo(family.familyId()) >= 0) - throw new IllegalArgumentException("Unordered/duplicate family"); - previous = family.familyId(); - families.add(family); - } - array(root.get("schemaFacts"), MAX_FACTS); - previous = ""; - Set tables = new HashSet<>(); - Set columns = new HashSet<>(); - for (JsonNode node : root.get("schemaFacts")) { - fields(node, Set.of("kind", "identity", "definitionDigest")); - SchemaFact fact = - new SchemaFact( - FactKind.valueOf(text(node, "kind")), - text(node, "identity"), - text(node, "definitionDigest")); - String key = fact.kind().name() + "/" + fact.identity(); - if (previous.compareTo(key) >= 0) - throw new IllegalArgumentException("Unordered/duplicate schema fact"); - previous = key; - if (fact.kind() == FactKind.TABLE) tables.add(fact.identity()); - if (fact.kind() == FactKind.COLUMN) columns.add(fact.identity()); - facts.add(fact); - } - Set declaredTables = new HashSet<>(); - for (Family family : families) { - if (!tables.contains(family.relation())) - throw new IllegalArgumentException("Missing family table"); - if (family.component().isEmpty()) declaredTables.add(family.relation()); - else if (!columns.contains(family.familyId())) - throw new IllegalArgumentException("Missing family component"); - } - if (!tables.equals(declaredTables) || tables.isEmpty()) { - throw new IllegalArgumentException("Every installed table needs an explicit disposition"); - } - return new WorldRuntimeFamilyCatalog(epoch, families, facts, bytes); - } catch (java.io.IOException | tools.jackson.core.JacksonException invalid) { - throw new IllegalArgumentException("Invalid closed World catalog", invalid); + JsonNode root = RuntimeFamilyCatalogValidation.decode(bytes, MAX_CATALOG_BYTES); + fields(root, Set.of("schema", "owner", "catalogEpoch", "families", "schemaFacts")); + if (!SCHEMA.equals(text(root, "schema")) || !OWNER.equals(text(root, "owner"))) { + throw new IllegalArgumentException("Unsupported World catalog schema/owner"); + } + String epochText = text(root, "catalogEpoch"); + if (!epochText.matches("[1-9][0-9]{0,18}")) throw new IllegalArgumentException("Invalid epoch"); + long epoch = Long.parseLong(epochText); + var families = new ArrayList(); + var facts = new ArrayList(); + array(root.get("families"), MAX_FAMILIES); + String previous = ""; + for (JsonNode node : root.get("families")) { + fields( + node, + Set.of("familyId", "relation", "component", "role", "stateClass", "freshDisposition")); + Family family = + new Family( + text(node, "familyId"), + text(node, "relation"), + text(node, "component"), + Role.valueOf(text(node, "role")), + StateClass.valueOf(text(node, "stateClass")), + FreshDisposition.valueOf(text(node, "freshDisposition"))); + if (previous.compareTo(family.familyId()) >= 0) + throw new IllegalArgumentException("Unordered/duplicate family"); + previous = family.familyId(); + families.add(family); } + var structuralFacts = + RuntimeFamilyCatalogValidation.schemaFacts(root.get("schemaFacts"), MAX_FACTS); + for (var fact : structuralFacts) { + facts.add( + new SchemaFact(FactKind.valueOf(fact.kind()), fact.identity(), fact.definitionDigest())); + } + RuntimeFamilyCatalogValidation.requireComplete( + families.stream() + .map( + family -> + new RuntimeFamilyCatalogValidation.FamilyComponent( + family.relation(), family.component())) + .toList(), + structuralFacts); + return new WorldRuntimeFamilyCatalog(epoch, families, facts, bytes); } static void requireUuid(UUID value) { - if (value == null || value.equals(new UUID(0, 0))) - throw new IllegalArgumentException("Non-nil UUID required"); + RuntimeFamilyCatalogValidation.requireUuid(value); } static void requireDigest(String value) { - if (value == null || !value.matches("sha256:[0-9a-f]{64}")) - throw new IllegalArgumentException("SHA-256 required"); + RuntimeFamilyCatalogValidation.requireDigest(value); } public static String sha256(byte[] bytes) { - try { - return "sha256:" - + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 required by Java", impossible); - } - } - - private static void identifier(String value) { - if (value == null || !value.matches("[a-z][a-z0-9_]{0,62}")) - throw new IllegalArgumentException("Schema identifier required"); - } - - private static void fields(JsonNode node, Set expected) { - if (node == null || !node.isObject()) - throw new IllegalArgumentException("Closed object required"); - Set actual = new HashSet<>(); - node.propertyNames().forEach(actual::add); - if (!actual.equals(expected)) - throw new IllegalArgumentException("Unknown or missing catalog field"); - } - - private static String text(JsonNode node, String key) { - JsonNode value = node.get(key); - if (value == null || !value.isTextual()) - throw new IllegalArgumentException("Text field required"); - return value.asText(); - } - - private static void array(JsonNode node, int maximum) { - if (node == null || !node.isArray() || node.isEmpty() || node.size() > maximum) { - throw new IllegalArgumentException("Complete bounded catalog array required"); - } + return RuntimeFamilyCatalogValidation.sha256(bytes); } } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidationTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidationTest.java new file mode 100644 index 0000000000..a8c7891e4a --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidationTest.java @@ -0,0 +1,119 @@ +package unit.net.firedevops.firemud.common.runtimecatalog; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Set; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.FamilyComponent; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogValidation.SchemaFact; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class RuntimeFamilyCatalogValidationTest { + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @ParameterizedTest + @ValueSource(strings = {"{\"x\":1,\"x\":2}", "{} {}", "{", "null"}) + void malformedDuplicateTrailingAndNonobjectSourcesRefuse(String source) { + assertThatThrownBy(() -> RuntimeFamilyCatalogValidation.fields(decode(source), Set.of())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void malformedUtf8AndCompleteByteBoundsRefuse() { + assertThatThrownBy( + () -> RuntimeFamilyCatalogValidation.decode(new byte[] {(byte) 0xc3, 0x28}, 10)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RuntimeFamilyCatalogValidation.decode(new byte[0], 10)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RuntimeFamilyCatalogValidation.decode(new byte[11], 10)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void closedObjectsTypedTextAndIndependentArrayBoundsRefuse() { + var object = decode("{\"a\":\"ok\",\"b\":1}"); + assertThatThrownBy(() -> RuntimeFamilyCatalogValidation.fields(object, Set.of("a"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RuntimeFamilyCatalogValidation.fields(object, Set.of("a", "b", "c"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RuntimeFamilyCatalogValidation.text(object, "b")) + .isInstanceOf(IllegalArgumentException.class); + for (String invalid : List.of("[]", "{}", "null", "[1,2]")) { + assertThatThrownBy(() -> RuntimeFamilyCatalogValidation.array(decode(invalid), 1)) + .isInstanceOf(IllegalArgumentException.class); + } + RuntimeFamilyCatalogValidation.array(decode("[1]"), 1); + } + + @Test + void schemaFactOrderingAndDuplicateIdentityAreNotSilentlyNormalized() { + String table = fact("TABLE", "runtime"); + String column = fact("COLUMN", "runtime.state"); + var ordered = + RuntimeFamilyCatalogValidation.schemaFacts(decode("[" + column + "," + table + "]"), 2); + assertThat(ordered).extracting(SchemaFact::kind).containsExactly("COLUMN", "TABLE"); + for (String invalid : + List.of("[" + table + "," + column + "]", "[" + table + "," + table + "]")) { + assertThatThrownBy(() -> RuntimeFamilyCatalogValidation.schemaFacts(decode(invalid), 2)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unordered/duplicate"); + } + assertThatThrownBy( + () -> RuntimeFamilyCatalogValidation.schemaFacts(decode("[" + table + "]"), 0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> RuntimeFamilyCatalogValidation.schemaFacts(decode("[{\"kind\":\"TABLE\"}]"), 1)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void everyInstalledTableAndDeclaredComponentNeedsExactFacts() { + var table = new SchemaFact("TABLE", "runtime", DIGEST); + var column = new SchemaFact("COLUMN", "runtime.state", DIGEST); + var root = new FamilyComponent("runtime", ""); + var component = new FamilyComponent("runtime", "state"); + RuntimeFamilyCatalogValidation.requireComplete( + List.of(root, component), List.of(column, table)); + assertThatThrownBy( + () -> + RuntimeFamilyCatalogValidation.requireComplete( + List.of(component), List.of(column, table))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Every installed table"); + assertThatThrownBy( + () -> + RuntimeFamilyCatalogValidation.requireComplete( + List.of(root, component), List.of(table))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Missing family component"); + assertThatThrownBy( + () -> RuntimeFamilyCatalogValidation.requireComplete(List.of(root), List.of(column))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Missing family table"); + assertThatThrownBy( + () -> + RuntimeFamilyCatalogValidation.requireComplete( + List.of(root), List.of(table, new SchemaFact("TABLE", "unknown", DIGEST)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Every installed table"); + } + + private static tools.jackson.databind.JsonNode decode(String value) { + return RuntimeFamilyCatalogValidation.decode(value.getBytes(StandardCharsets.UTF_8), 4096); + } + + private static String fact(String kind, String identity) { + return "{\"kind\":\"" + + kind + + "\",\"identity\":\"" + + identity + + "\",\"definitionDigest\":\"" + + DIGEST + + "\"}"; + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java index b845ff5784..ab6bc31562 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -274,13 +274,29 @@ void schemaColumnRenameConstraintAndRoutineChangesCannotResampleUnderSameEpoch() Request read = request(); f.owner().read(read); f.dsl.execute(change); - assertThatThrownBy(() -> f.owner().readExact(read)).isInstanceOf(RuntimeException.class); - assertThatThrownBy(() -> f.owner().read(request())).isInstanceOf(RuntimeException.class); + assertCatalogDrift(() -> f.owner().readExact(read)); + assertCatalogDrift(() -> f.owner().read(request())); assertThat(f.count("world_runtime_family_catalog_snapshot")).isEqualTo(1); } } } + private static void assertCatalogDrift(Runnable read) { + assertThatThrownBy(read::run) + .satisfies( + failure -> { + if (failure instanceof org.jooq.exception.DataAccessException sql) { + assertThat(sql.sqlState()).isEqualTo("23514"); + assertThat(sql).hasMessageContaining("Unclassified or changed World schema family"); + } else { + assertThat(failure) + .isInstanceOf( + WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class) + .hasMessageContaining("drift invalidates its epoch"); + } + }); + } + @Test void installedViewAndMaterializedViewOptionsInvalidateTheSealWithoutResampling() throws Exception { From c21b8182906990af3c80bce33118cffc1a38a20b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:01:57 +1300 Subject: [PATCH 08/11] Prove exact Automation catalog drift refusals --- .../realm-routing-and-playable-state.md | 2 +- ...eFamilyCatalogPostgresIntegrationTest.java | 22 +++++++++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 719d6a3e3f..a2ffe10a19 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -31,7 +31,7 @@ Receiving proof243/244 passes six World [value/codec cases](../../../services/co Review corrections retain the published catalog migrations and add forward owner seals for view definitions and options. World V1047 supplies the exact snapshot-frame and installed-script guard; its normative behavior remains at the linked World data owner. Later Social V1006 is qualified by proof281: all fifteen catalog cases and the full 38-case integration suite pass, including twelve poisoned-frame vectors, same-identity recovery and retained V1005 upgrade evidence, with generation and selected checks. Proof275/276 passes 252 actual PostgreSQL cases across the affected Entity, World, Automation and Social suites, including seventeen World catalog cases, the receipt-digest migration composition and thirteen fixed-preset upgrade cases. World's controlled receipt probe now installs every source World/Saga table before reaching the full census; its predicate-only clone is not production authority. The fixed-preset retention case compares all original row values and `xmin` while separately asserting the three new catalog tables, two retained epochs and empty request snapshots. Proof275 retains that comparison failure; proof276 passes the corrected thirty-one World cases and selected integration static, formatting and documentation checks. The four mandatory-Docker catalog fixtures and combined forward-version checks pass their canonical contracts. Proof273 separately passes twenty-five Common codec cases, five Game Design compositions and eighteen physical mTLS client cases after the shared framing helper adds defensive copies; proof272's earlier mutable-array analysis failure remains recorded. These component proofs do not expand the source or runtime authority boundary. -CLI4 corrections consolidate the four owner values' strict UTF-8, closed JSON, bounded arrays, schema-fact ordering and table/component completeness checks in the existing [shared runtime-catalog package](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidation.java). Owner schemas, enums, disposition rules and exact retained bytes remain local and unchanged. Proof363 passes all33 Common catalog/structural cases and17 actual World PostgreSQL cases, including specific drift failure types/messages rather than arbitrary runtime exceptions. Proof364 passes the other three owner catalog PostgreSQL suites and enabled Common main/test plus World integration static/format checks; these controlled component results do not establish global installation, manifests or FRESH completion. Mandatory Docker proof remains non-skipping. +CLI4 corrections consolidate the four owner values' strict UTF-8, closed JSON, bounded arrays, schema-fact ordering and table/component completeness checks in the existing [shared runtime-catalog package](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidation.java). Owner schemas, enums, disposition rules and exact retained bytes remain local and unchanged. Proof363 passes all 33 Common catalog/structural cases and 17 actual World PostgreSQL cases, including specific drift failure types/messages rather than arbitrary runtime exceptions. Proof364 passes the other three owner catalog PostgreSQL suites and enabled Common main/test plus World integration static/format checks; these controlled component results do not establish global installation, manifests or FRESH completion. Mandatory Docker proof remains non-skipping. Remaining batch obligations are the genuine World-owned global enrollment/required-owner-set source, remaining actual owner catalogs/epochs, complete build/lifecycle/namespace/generation-bound FRESH manifest production and immutable authenticated readback, genuine protected private authorization/runtime/materialization, and complete-set aggregation into the existing canonical CLOSED pointer/audit/outcome owner. Current World canonical materialization is still public `SHARED` and original-`StartSession`-only; no private FRESH relabelling is valid. The existing unregistered [canonical CLOSED owner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java) supplies public initial CLOSED persistence, not the missing private aggregate; the registered legacy routing model described elsewhere remains narrower. No second private pointer authority is added. CLOSED-to-OPEN, private first admission, issuer/custody/PKI qualification, runtime/default registration, operational activation, reset and Unit1B remain held. Capability ratings are unchanged; this source batch does not complete FRESH capability. diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java index 53daf7fa01..113ea88800 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -282,8 +282,26 @@ void columnAddRemoveRenameConstraintsAndRoutineDriftCannotResampleSameEpoch() th Request read = request(); f.owner().read(read); f.dsl.execute(change); - assertThatThrownBy(() -> f.owner().readExact(read)).isInstanceOf(RuntimeException.class); - assertThatThrownBy(() -> f.owner().read(request())).isInstanceOf(RuntimeException.class); + boolean censusRefusal = change.equals("ALTER TABLE npc_memory RENAME TO renamed_memory"); + for (Runnable operation : + List.of(() -> f.owner().readExact(read), () -> f.owner().read(request()))) { + if (censusRefusal) { + assertThatThrownBy(operation::run) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + sql -> { + assertThat(sql.sqlState()).isEqualTo("23514"); + assertThat(sql) + .hasMessageContaining("Unclassified or changed Automation schema family"); + }); + } else { + assertThatThrownBy(operation::run) + .isInstanceOf( + AutomationRuntimeFamilyCatalogRepository.CatalogConflictException.class) + .hasMessageContaining( + "Automation schema/classification drift invalidates its epoch"); + } + } assertThat(f.count("automation_runtime_family_catalog_snapshot")).isEqualTo(1); } } From 007a5a728cd74eabc8e3d412b63c13c285e5c805 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:57:11 +1300 Subject: [PATCH 09/11] Clarify shared catalog client transport requirements --- .../microservices/game-session-service/api-contracts.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 902c0c5fe4..e8a3ae779f 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -84,7 +84,9 @@ The Account client uses a 30-second deadline for this composed read; the nested ### Owner-local runtime-family catalog clients -Game Session may manually consume the [Social & Groups owner-local runtime-family catalog](../social-groups-service/api-contracts.md#owner-local-runtime-family-catalog-read) through its exact same-namespace peer-qualified client with finite request/response and deadline bounds. This is source evidence only; it does not establish row-level classification, initialized target state, owner enrollment, FRESH readiness or protection through a later Game Session commit. Social’s blocking dispositions and unimplemented contracts remain outstanding. +All four catalog clients in this section are manually composed and unregistered. Each requires file-backed mTLS and authenticates its exact same-namespace owner peer. + +Game Session may consume the [Social & Groups owner-local runtime-family catalog](../social-groups-service/api-contracts.md#owner-local-runtime-family-catalog-read) through `SocialRuntimeFamilyCatalogClient` with finite request/response and deadline bounds. This is source evidence only; it does not establish row-level classification, initialized target state, owner enrollment, FRESH readiness or protection through a later Game Session commit. Social’s blocking dispositions and unimplemented contracts remain outstanding. The manually composed, unregistered `WorldRuntimeFamilyCatalogClient` consumes the [World-owned runtime-family catalog read](../world-management-service/api-contracts.md#owner-local-runtime-family-catalog-read). It authenticates the exact same-namespace World server, preserves the complete typed catalog bytes/digest, durable World epoch, snapshot identity and original read correlation, and refuses malformed, incomplete, stale-catalog, oversized or unavailable source evidence. The finite deadline and wire/source bounds are defined at that World contract owner. It runs outside ambient SQL and supplies only an as-of World-local classification input. It does not invent a complete owner set, wire evidence into FRESH preparation, mutate catalog/pointer authority, produce a FRESH manifest or protect a later Game Session commit. The whole-FRESH batch and focused proof status remain in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#world-owner-local-runtime-family-catalog-prerequisite). From 8967e80c23f392ae0a69881972871eae9971a3d7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:30:43 +1300 Subject: [PATCH 10/11] Clarify sealed catalog maintenance and align classifier tests --- .../system-architecture-database-migrations.md | 8 ++++++++ .../system-architecture-deployment-runbook.md | 1 + .../RuntimeFamilyCatalogStorageStatusTest.java | 3 ++- 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/design/architecture/system-architecture-database-migrations.md b/design/architecture/system-architecture-database-migrations.md index a2b9cbcbb0..374247acb7 100644 --- a/design/architecture/system-architecture-database-migrations.md +++ b/design/architecture/system-architecture-database-migrations.md @@ -49,6 +49,14 @@ This document is the current target authority for SQL persistence, schema owners Shared migration artifacts use a collision-free versioning convention relative to adopter-local migrations. Default Flyway ordering and validation remain enabled. Before allocating a new service-local version, inspect the immutable receiving parent’s complete effective migration set, including every shared location loaded by that service; the new version must be strictly greater than that combined local/shared frontier. A new shared migration must be strictly greater than every adopting service’s effective frontier, so a service-local extension cannot make the next shared migration an ignored lower version. Compare added artifacts against the receiving parent with the existing Flyway version checker, and prove fresh bootstrap and upgrade from the actual installed combined history. A manually dispatched CI run must supply the receiving parent’s full immutable commit SHA; CI fetches that exact commit when needed and fails if it is unavailable so the same parent comparison remains in force. Re-version only never-applied candidate artifacts when correcting allocation; preserve their SQL bytes and every applied artifact’s filename and checksum. An applied shared migration is never renumbered, rewritten, or silently replaced; a shared change is a new compatible migration under that convention. A physical PostgreSQL cluster or database may host multiple service schemas, but that does not permit cross-service DDL, foreign keys, direct table reads, or one service to advance or repair another service's Flyway history. +### Sealed Runtime-Family Catalog Epochs + +The owner-local catalogs for [World](./microservices/world-management-service/api-contracts.md#owner-local-runtime-family-catalog-read), [Entity](./microservices/entity-management-service/api-contracts.md#owner-local-runtime-family-catalog-read), [Automation](./microservices/automation-scripting-service/api-contracts.md#owner-local-runtime-family-catalog-read), and [Social](./microservices/social-groups-service/api-contracts.md#owner-local-runtime-family-catalog-read) seal installed PostgreSQL definitions, classifications and counted Flyway history. Every subsequent owner or adopted shared migration that changes these inputs requires an explicit next owner epoch in its reviewed forward migration batch. End that batch with the owner-local catalog installation and seal after the other definitions are installed; an ordinary new Flyway history row can itself change the catalog even when payload tables are untouched. + +Keep the census function, catalog-installation history exclusions and successful-installation predicate aligned. A catalog installer's own Flyway row is recorded after its SQL runs, so its exact successful installation must be independently qualified as in World V1047; sealing a snapshot before that row appears without the corresponding owner binding is insufficient. Preserve every prior epoch, snapshot, applied migration and checksum. Never edit history or reseal an old epoch to make a failed read pass. + +PostgreSQL upgrades can change rendered routine, view, constraint, trigger, type or sequence definitions. If the upgraded engine changes sealed bytes, reads remain failed closed until a reviewed forward catalog installation explicitly seals the next epoch against that installed engine and migration history. Prove the upgrade and new-epoch readback on disposable PostgreSQL with retained rows before relying on the new catalog, then reacquire dependent snapshots under their owning contracts. Unavailable or contradictory evidence is not an empty catalog or permission to auto-repair history. + ### Objective Compatibility Gates Every shape-changing migration evaluates two independent questions: diff --git a/design/architecture/system-architecture-deployment-runbook.md b/design/architecture/system-architecture-deployment-runbook.md index ae47c6af91..c8200a3375 100644 --- a/design/architecture/system-architecture-deployment-runbook.md +++ b/design/architecture/system-architecture-deployment-runbook.md @@ -103,6 +103,7 @@ The drill evidence may be reused within the configured freshness window only whi 1. **Review Release Notes** - Confirm which services and schema changes are included. - Identify any manual migration or configuration steps called out for operators. + - For an installed owner catalog that drifts after a PostgreSQL upgrade or migration, follow [sealed catalog epoch recovery](./system-architecture-database-migrations.md#sealed-runtime-family-catalog-epochs): keep reads failed closed, apply the reviewed forward owner catalog migration and explicit next epoch, and reacquire dependent evidence. Do not edit Flyway history, historical epochs or snapshots to clear the failure. 2. **Verify CI/CD Status** - Ensure the GitHub Actions pipeline for the target branch and tag is green. - Check that container image digests are available in the configured registry. diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogStorageStatusTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogStorageStatusTest.java index 92156f6eaa..95ff018573 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogStorageStatusTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogStorageStatusTest.java @@ -1,9 +1,10 @@ -package net.firedevops.firemud.common.runtimecatalog; +package unit.net.firedevops.firemud.common.runtimecatalog; import static org.assertj.core.api.Assertions.assertThat; import io.grpc.Status; import java.sql.SQLException; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogStorageStatus; import org.junit.jupiter.api.Test; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.DataIntegrityViolationException; From 31ee0750c2f889730719a05120138da9ea3fbea7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:59:04 +1300 Subject: [PATCH 11/11] Share catalog receiver workload and transaction guard --- ...onRuntimeFamilyCatalogReadGrpcService.java | 34 +++----- .../RuntimeFamilyCatalogReadGuard.java | 52 ++++++++++++ .../RuntimeFamilyCatalogReadGuardTest.java | 85 +++++++++++++++++++ ...tyRuntimeFamilyCatalogReadGrpcService.java | 33 +++---- ...alRuntimeFamilyCatalogReadGrpcService.java | 33 +++---- ...ldRuntimeFamilyCatalogReadGrpcService.java | 33 +++---- 6 files changed, 189 insertions(+), 81 deletions(-) create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogReadGuard.java create mode 100644 services/common-security/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogReadGuardTest.java diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java index 24164ae96c..9e3d718e6b 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogReadGrpcService.java @@ -9,8 +9,7 @@ import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalog.Request; import net.firedevops.firemud.common.automation.AutomationRuntimeFamilyCatalogCodec; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.security.SessionContext; -import org.springframework.transaction.support.TransactionSynchronizationManager; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogReadGuard; /** Manual unregistered producer. Exact Game Session workload authentication precedes decode/SQL. */ public final class AutomationRuntimeFamilyCatalogReadGrpcService @@ -32,24 +31,17 @@ public void readAutomationRuntimeFamilyCatalog( ReadAutomationRuntimeFamilyCatalogRequest wire, StreamObserver observer) { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); - if (peer == null) { - refuse(observer, Status.UNAUTHENTICATED, "Authenticated workload required"); - return; - } - if (!peer.isService("game-session-service") - || !peer.isInNamespace(namespace) - || SessionContext.hasAuthenticatedCallerContext() - || SessionContext.isInternalService()) { - refuse( - observer, - Status.PERMISSION_DENIED, - "Exact same-namespace Game Session workload required without caller context"); - return; - } - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - refuse( - observer, Status.FAILED_PRECONDITION, "Independent Automation owner operation required"); + var refusal = RuntimeFamilyCatalogReadGuard.refuseBeforeDecode(peer, namespace); + if (refusal.isPresent()) { + RuntimeFamilyCatalogReadGuard.Refusal reason = refusal.orElseThrow(); + String description = + switch (reason) { + case UNAUTHENTICATED -> "Authenticated workload required"; + case PERMISSION_DENIED -> + "Exact same-namespace Game Session workload required without caller context"; + case FAILED_PRECONDITION -> "Independent Automation owner operation required"; + }; + refuse(observer, reason.status(), description); return; } Request request; @@ -59,7 +51,7 @@ public void readAutomationRuntimeFamilyCatalog( refuse(observer, Status.INVALID_ARGUMENT, "Complete bounded catalog request required"); return; } - if (!namespace.equals(request.targetNamespace())) { + if (!RuntimeFamilyCatalogReadGuard.matchesNamespace(namespace, request.targetNamespace())) { refuse( observer, Status.PERMISSION_DENIED, diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogReadGuard.java b/services/common-security/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogReadGuard.java new file mode 100644 index 0000000000..df459eb3a5 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogReadGuard.java @@ -0,0 +1,52 @@ +package net.firedevops.firemud.common.runtimecatalog; + +import io.grpc.Status; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Shared catalog receiver security policy; owner messages, codecs and storage types remain local. + */ +public final class RuntimeFamilyCatalogReadGuard { + private RuntimeFamilyCatalogReadGuard() {} + + /** Authentication and caller isolation must be checked before decode or owner storage. */ + public static Optional refuseBeforeDecode(GrpcPeerIdentity peer, String namespace) { + if (peer == null) return Optional.of(Refusal.UNAUTHENTICATED); + if (!peer.isService("game-session-service") + || !peer.isInNamespace(namespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + return Optional.of(Refusal.PERMISSION_DENIED); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + return Optional.of(Refusal.FAILED_PRECONDITION); + } + return Optional.empty(); + } + + /** Compares the already decoded namespace with the receiver's fixed owner configuration. */ + public static boolean matchesNamespace(String expectedNamespace, String requestNamespace) { + return expectedNamespace != null && expectedNamespace.equals(requestNamespace); + } + + /** Owner-specific descriptions must be selected without changing these refusal statuses. */ + public enum Refusal { + UNAUTHENTICATED(Status.UNAUTHENTICATED), + PERMISSION_DENIED(Status.PERMISSION_DENIED), + FAILED_PRECONDITION(Status.FAILED_PRECONDITION); + + private final Status status; + + Refusal(Status status) { + this.status = status; + } + + public Status status() { + return status; + } + } +} diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogReadGuardTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogReadGuardTest.java new file mode 100644 index 0000000000..2b8131e568 --- /dev/null +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogReadGuardTest.java @@ -0,0 +1,85 @@ +package unit.net.firedevops.firemud.common.runtimecatalog; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogReadGuard; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogReadGuard.Refusal; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class RuntimeFamilyCatalogReadGuardTest { + @AfterEach + void clearContext() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void authenticationAndWorkloadRefusalsPrecedeTransactionRefusal() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThat(RuntimeFamilyCatalogReadGuard.refuseBeforeDecode(null, "test")) + .contains(Refusal.UNAUTHENTICATED); + assertThat( + RuntimeFamilyCatalogReadGuard.refuseBeforeDecode( + peer("account-service", "test"), "test")) + .contains(Refusal.PERMISSION_DENIED); + assertThat( + RuntimeFamilyCatalogReadGuard.refuseBeforeDecode( + peer("game-session-service", "other"), "test")) + .contains(Refusal.PERMISSION_DENIED); + assertThat( + RuntimeFamilyCatalogReadGuard.refuseBeforeDecode( + peer("game-session-service", "test"), "test")) + .contains(Refusal.FAILED_PRECONDITION); + } + + @Test + void everyPropagatedAccountRoleOrInternalContextRefusesAnOtherwiseValidPeer() { + var peer = peer("game-session-service", "test"); + SessionContext.setContext(UUID.randomUUID().toString(), List.of(), Map.of()); + assertThat(RuntimeFamilyCatalogReadGuard.refuseBeforeDecode(peer, "test")) + .contains(Refusal.PERMISSION_DENIED); + SessionContext.setContext(null, List.of("platformAdmin"), Map.of()); + assertThat(RuntimeFamilyCatalogReadGuard.refuseBeforeDecode(peer, "test")) + .contains(Refusal.PERMISSION_DENIED); + SessionContext.setContext( + null, List.of(), Map.of(UUID.randomUUID().toString(), List.of("tenantAdmin"))); + assertThat(RuntimeFamilyCatalogReadGuard.refuseBeforeDecode(peer, "test")) + .contains(Refusal.PERMISSION_DENIED); + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-session-service", "controlled"); + assertThat(RuntimeFamilyCatalogReadGuard.refuseBeforeDecode(peer, "test")) + .contains(Refusal.PERMISSION_DENIED); + } + + @Test + void transactionSynchronizationAloneRefusesAndCleanPeerIsAllowed() { + var peer = peer("game-session-service", "test"); + assertThat(RuntimeFamilyCatalogReadGuard.refuseBeforeDecode(peer, "test")).isEmpty(); + TransactionSynchronizationManager.initSynchronization(); + assertThat(RuntimeFamilyCatalogReadGuard.refuseBeforeDecode(peer, "test")) + .contains(Refusal.FAILED_PRECONDITION); + } + + @Test + void requestNamespaceMustMatchTheFixedReceiverExactly() { + assertThat(RuntimeFamilyCatalogReadGuard.matchesNamespace("test", "test")).isTrue(); + assertThat(RuntimeFamilyCatalogReadGuard.matchesNamespace("test", "other")).isFalse(); + assertThat(RuntimeFamilyCatalogReadGuard.matchesNamespace("test", null)).isFalse(); + assertThat(RuntimeFamilyCatalogReadGuard.matchesNamespace(null, "test")).isFalse(); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java index 8f3959f4a7..8b0b91c3bd 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/runtimecatalog/EntityRuntimeFamilyCatalogReadGrpcService.java @@ -6,12 +6,11 @@ import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalog.Request; import net.firedevops.firemud.common.entity.EntityRuntimeFamilyCatalogCodec; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogReadGuard; import net.firedevops.firemud.entitymanagement.repository.EntityRuntimeFamilyCatalogRepository; import net.firedevops.firemud.entitymanagement.v1.EntityRuntimeFamilyCatalogReadServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.ReadEntityRuntimeFamilyCatalogRequest; import net.firedevops.firemud.entitymanagement.v1.ReadEntityRuntimeFamilyCatalogResponse; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** Manually composed and unregistered. Workload guard precedes decoding and every SQL access. */ public final class EntityRuntimeFamilyCatalogReadGrpcService @@ -33,23 +32,17 @@ public void readEntityRuntimeFamilyCatalog( ReadEntityRuntimeFamilyCatalogRequest wire, StreamObserver observer) { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); - if (peer == null) { - refuse(observer, Status.UNAUTHENTICATED, "Authenticated workload required"); - return; - } - if (!peer.isService("game-session-service") - || !peer.isInNamespace(namespace) - || SessionContext.hasAuthenticatedCallerContext() - || SessionContext.isInternalService()) { - refuse( - observer, - Status.PERMISSION_DENIED, - "Exact same-namespace Game Session workload required without caller context"); - return; - } - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - refuse(observer, Status.FAILED_PRECONDITION, "Independent Entity owner operation required"); + var refusal = RuntimeFamilyCatalogReadGuard.refuseBeforeDecode(peer, namespace); + if (refusal.isPresent()) { + RuntimeFamilyCatalogReadGuard.Refusal reason = refusal.orElseThrow(); + String description = + switch (reason) { + case UNAUTHENTICATED -> "Authenticated workload required"; + case PERMISSION_DENIED -> + "Exact same-namespace Game Session workload required without caller context"; + case FAILED_PRECONDITION -> "Independent Entity owner operation required"; + }; + refuse(observer, reason.status(), description); return; } Request request; @@ -59,7 +52,7 @@ public void readEntityRuntimeFamilyCatalog( refuse(observer, Status.INVALID_ARGUMENT, "Complete bounded catalog request required"); return; } - if (!namespace.equals(request.targetNamespace())) { + if (!RuntimeFamilyCatalogReadGuard.matchesNamespace(namespace, request.targetNamespace())) { refuse( observer, Status.PERMISSION_DENIED, diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcService.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcService.java index 6aa7d7b6c4..eaf7a263cc 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcService.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogReadGrpcService.java @@ -4,13 +4,12 @@ import io.grpc.stub.StreamObserver; import java.util.Objects; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogReadGuard; import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalog.Request; import net.firedevops.firemud.common.social.SocialRuntimeFamilyCatalogCodec; import net.firedevops.firemud.socialgroups.v1.ReadSocialRuntimeFamilyCatalogRequest; import net.firedevops.firemud.socialgroups.v1.ReadSocialRuntimeFamilyCatalogResponse; import net.firedevops.firemud.socialgroups.v1.SocialRuntimeFamilyCatalogReadServiceGrpc; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Manual, unregistered, exact Game Session workload read. Authentication precedes decode and SQL. @@ -35,23 +34,17 @@ public void readSocialRuntimeFamilyCatalog( ReadSocialRuntimeFamilyCatalogRequest wire, StreamObserver observer) { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); - if (peer == null) { - refuse(observer, Status.UNAUTHENTICATED, "Authenticated workload required"); - return; - } - if (!peer.isService("game-session-service") - || !peer.isInNamespace(namespace) - || SessionContext.hasAuthenticatedCallerContext() - || SessionContext.isInternalService()) { - refuse( - observer, - Status.PERMISSION_DENIED, - "Exact same-namespace Game Session workload required without caller context"); - return; - } - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - refuse(observer, Status.FAILED_PRECONDITION, "Independent Social owner operation required"); + var refusal = RuntimeFamilyCatalogReadGuard.refuseBeforeDecode(peer, namespace); + if (refusal.isPresent()) { + RuntimeFamilyCatalogReadGuard.Refusal reason = refusal.orElseThrow(); + String description = + switch (reason) { + case UNAUTHENTICATED -> "Authenticated workload required"; + case PERMISSION_DENIED -> + "Exact same-namespace Game Session workload required without caller context"; + case FAILED_PRECONDITION -> "Independent Social owner operation required"; + }; + refuse(observer, reason.status(), description); return; } Request request; @@ -61,7 +54,7 @@ public void readSocialRuntimeFamilyCatalog( refuse(observer, Status.INVALID_ARGUMENT, "Complete bounded Social catalog request required"); return; } - if (!namespace.equals(request.targetNamespace())) { + if (!RuntimeFamilyCatalogReadGuard.matchesNamespace(namespace, request.targetNamespace())) { refuse( observer, Status.PERMISSION_DENIED, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java index 82b74e267e..abc4f6687d 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogReadGrpcService.java @@ -4,13 +4,12 @@ import io.grpc.stub.StreamObserver; import java.util.Objects; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.runtimecatalog.RuntimeFamilyCatalogReadGuard; import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Request; import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalogCodec; import net.firedevops.firemud.worldmanagement.v1.ReadWorldRuntimeFamilyCatalogRequest; import net.firedevops.firemud.worldmanagement.v1.ReadWorldRuntimeFamilyCatalogResponse; import net.firedevops.firemud.worldmanagement.v1.WorldRuntimeFamilyCatalogReadServiceGrpc; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Manual, unregistered, exact Game Session workload read. Authentication precedes decode and SQL. @@ -33,23 +32,17 @@ public void readWorldRuntimeFamilyCatalog( ReadWorldRuntimeFamilyCatalogRequest wire, StreamObserver observer) { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); - if (peer == null) { - refuse(observer, Status.UNAUTHENTICATED, "Authenticated workload required"); - return; - } - if (!peer.isService("game-session-service") - || !peer.isInNamespace(namespace) - || SessionContext.hasAuthenticatedCallerContext() - || SessionContext.isInternalService()) { - refuse( - observer, - Status.PERMISSION_DENIED, - "Exact same-namespace Game Session workload required without caller context"); - return; - } - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - refuse(observer, Status.FAILED_PRECONDITION, "Independent World owner operation required"); + var refusal = RuntimeFamilyCatalogReadGuard.refuseBeforeDecode(peer, namespace); + if (refusal.isPresent()) { + RuntimeFamilyCatalogReadGuard.Refusal reason = refusal.orElseThrow(); + String description = + switch (reason) { + case UNAUTHENTICATED -> "Authenticated workload required"; + case PERMISSION_DENIED -> + "Exact same-namespace Game Session workload required without caller context"; + case FAILED_PRECONDITION -> "Independent World owner operation required"; + }; + refuse(observer, reason.status(), description); return; } Request request; @@ -59,7 +52,7 @@ public void readWorldRuntimeFamilyCatalog( refuse(observer, Status.INVALID_ARGUMENT, "Complete bounded catalog request required"); return; } - if (!namespace.equals(request.targetNamespace())) { + if (!RuntimeFamilyCatalogReadGuard.matchesNamespace(namespace, request.targetNamespace())) { refuse( observer, Status.PERMISSION_DENIED,