diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index ec5eba5173..7f22d35dce 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -28,4 +28,18 @@ The target publication boundary treats object-store export as a durable candidat ## Local Development Notes +### Historical Entity digest baseline migration + +**Current implementation status:** The one-shot Game Design maintenance Job and guarded owner-local v1→v2 baseline transition are implemented, but no retained row set or live certificate/consumer/readback outcome has been verified by this document. The Job is disabled in ordinary Helm releases and must be invoked only from a trusted operator context, using a reviewed immutable Game Design image digest. It is not a public API, a general admin role, or a PR-controlled executor. Its dedicated `game-design-baseline-migrator` Kubernetes service account has no Kubernetes API verbs, and its separate client certificate may read only Entity Management's bound `GetDraftDesignDigest` RPC. No Game Design, Account, or Game Session mutation API is delegated to that identity. The Job only writes Game Design's own baseline and audit tables through its guarded service operation; it never accesses Entity's database. + +Use a controlled pre-v1 publication window for the affected Entity v1 full-version scopes. Drain in-flight publication and prevent new publication on those scopes before comparing rows or deploying the writer. Deploy the migration-capable Game Design reader/reconciler image first so retained stored v1 and v2 baseline shapes can be inspected; its publish gate still requires v2 and never compares v1 content with v2 content. Then deploy Entity's v2 producer image. Because #2872 already has a v2-only gate, deploying it alone may temporarily block affected v1 publication; this is an accepted fail-closed maintenance window, not seamless dual-reader availability. Verify actual service image digests and deployment order before proceeding; if the image topology cannot maintain that sequence, stop instead of relaxing the gate. The current Entity applied-commit token is synthetic `version:` and does not prove durable applied-revision convergence. + +Before invoking a Job, verify the exact Kubernetes context and namespace, the authorized operator identity and approved maintenance window, both current service image digests, database backup/recovery posture, completed in-flight publication drain, and the dedicated migrator certificate's issuer, `Ready` state, URI SAN, trust chain, projected Secret, and actual mTLS acceptance at Entity. The hosted trust/controller admission policy includes a narrow runtime-namespace exception for this identity; it does not make the migrator one of the controller's permanent certificate consumers. A trusted certificate writer must explicitly invoke `ensure-standalone-transport-certificates.sh --migrator `; a separately authorized Secret-read operator then invokes `--verify-migrator ` before the Job is enabled. The certificate writer's service account has no Secret-read permission. These opt-in operations do not alter ordinary preview transport-certificate rollout. A rendered Certificate or Secret name alone is not issuance or served-identity proof. The trusted operator must create an immutable expected-source ConfigMap or Secret from a read-only exact database row, including baseline ID, tenant, `FULL_VERSION`, `ENTITY_MANAGEMENT`, null base version, version scope, applied commit, digest, schema `1`, and both workflow IDs and timestamps. Do not place this manifest, credentials, or raw retained row values in a PR or CI artifact. Check that the source object is immutable before applying the Job. The Job's `targetNamespace`, tenant/version, operation ID, actor identity, and expected-source object are all fixed for that invocation; a changed command gets a new operation ID, never a reinterpretation of the old one. + +The chart's `previewStack.entityDigestBaselineMigration` values are disabled by default. From the trusted operator revision, supply an image pinned as `repository@sha256:`, exact `targetNamespace`, the dedicated `firemud-grpc-game-design-baseline-migrator` Secret, and `mode`. `enumerate` returns at most 500 Entity schema-v1 full-version rows after one baseline ID; repeat with its returned keyset cursor until an empty page proves no more rows at the quiesced snapshot. `preflight` classifies one exact tenant/version as v1, v2, absent, ambiguous, or unsupported, and refuses a missing or script-only Version. `migrate` requires one stable operation ID, exact tenant/version, actor identity, and the immutable expected-source object. The Java runner verifies its namespace, dedicated service account, and certificate URI identity before reading or writing. A missing identity, policy, input, row, version, exact-old match, or v2 Entity response fails closed. Render and inspect the operator overlay before installation; do not leave `enabled: true` in the ordinary chart values or an unattended release upgrade. Completed Jobs are deliberately not Helm hooks, so an unchanged upgrade does not rerun them; a changed immutable Job spec is rejected and needs an explicit trusted disposition. + +For each affected scope, retain the preflight row ID and complete source tuple privately, run `migrate`, and require its reported operation/audit/baseline IDs and disposition. The Game Design transaction conditionally replaces the exact old row and inserts an immutable before/after audit atomically. The live row retains its original and last real publish-workflow IDs and timestamps; only the audit's operation ID and committed time describe the maintenance transition. An exact retry of the same operation reads the existing audit and baseline rather than writing again; a lost acknowledgement is resolved by that same operation identity and exact readback. A changed source, ambiguous scope, different actor/workload binding, mismatched Entity v2 schema/scope/digest/commit, or unproved write outcome is a stop condition. Independently read back `publish_recorded_participant_digest` by baseline ID and `entity_digest_baseline_migration_audit` by operation ID from Game Design's PostgreSQL schema; compare the new schema/digest/commit and preserved publish provenance, complete old tuple, observed v2 tuple, migration operation, actor/workload, outcome, and timestamp exactly. Never count Job completion alone as database proof. Keep the before/after records with the private migration log, excluding secrets and certificate keys. + +If no retained Entity v1 rows exist, record the exact namespace, database/schema, query time, quiescence evidence, and an empty bounded enumeration through its terminal page; separately preflight every affected known tenant/version scope and record its state. This is a no-data boundary, not a claim that migration ran. If a migration fails or proof is incomplete, leave affected publication closed and retain the old row/audit evidence; do not restore a v1 hash over an audited v2 row or weaken the v2 publish gate. Resume only after an exact retry/readback or an explicit database recovery decision with equivalent provenance. Reopen publication only after every enumerated v1 row has a verified v2 baseline and audit (or the scoped no-data proof), the Entity v2 producer and Game Design reader remain healthy, and the normal v2 publish gate succeeds. After the approved work and readback are complete, disable the Helm migration Job and have an authorized `system:masters` operator explicitly retire its exact dedicated Certificate and Secret; the scoped writer cannot delete them. Retain the database audit and private operation evidence. Do not leave the one-shot workload identity provisioned as an ordinary Game Design credential. Live retained data, PostgreSQL readback, certificate bootstrap, served mTLS, and identity retirement proof must be reported separately from local fixtures and static Helm renders. + `TestDataSeeder` populates a demo game, template, revision and version only when explicit smoke/runtime seeding is enabled through deployment config (`FIREMUD_SMOKE_SEED_DEMO_RUNTIME_ENABLED=true` in the local Compose smoke stack). Run `services/game-design-service/smoke-test.sh` to verify both REST and gRPC endpoints. The lightweight maintained application smoke now lives under `src/test/java/integration`; the old disabled GHCR-based cross-service placeholder was removed because it did not prove a meaningful current contract. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 4e534978f5..78e2e19b3f 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -119,7 +119,7 @@ services as the source of truth for the current Draft template graphs: #### Owner-to-owner digest authorization and tenant identity -`GetDraftDesignDigest` is a read-only owner-to-owner publication read across World Management, Entity Management, Game Logic, and Automation & Scripting. Every receiver uses the shared [Security Architecture](../../system-architecture-security.md) and [Authentication & Authorization](../../system-architecture-authentication.md) workload and method-allowlist rules: only the authenticated Game Design workload identity may call the publication method, and other internal workloads plus user/admin JWTs are denied. The invocation binds exact `{tenantId, scope}` (`versionId` for full publish or the complete `{baseVersionId, scriptPatchVersion}` pair for script patch), stable `publishRequestId`, derived workflow identity, and canonical `requestDigest`; missing, changed, or omitted binding evidence fails closed before a digest is returned. This context is owner-authentication and replay evidence, not an end-user role and not part of the content digest. Temporal activities never propagate the human operator JWT; operator authority ends when Game Design starts or attaches to the workflow. Each response's tenant and complete scope tuple must be exact-compared by Game Design before recording or gating the attestation; Game Design remains publication coordinator and each participant remains owner of its digest. +`GetDraftDesignDigest` is a read-only owner-to-owner publication read across World Management, Entity Management, Game Logic, and Automation & Scripting. Every receiver uses the shared [Security Architecture](../../system-architecture-security.md) and [Authentication & Authorization](../../system-architecture-authentication.md) workload and method-allowlist rules: only the authenticated Game Design workload identity may call the publication method, and other internal workloads plus user/admin JWTs are denied. The one narrow exception is the dedicated `game-design-baseline-migrator` certificate identity, which may call only Entity Management's digest-read method during the protected historical-baseline migration; it has no access to the other three publication reads or a public mutation route. The invocation binds exact `{tenantId, scope}` (`versionId` for full publish or the complete `{baseVersionId, scriptPatchVersion}` pair for script patch), stable `publishRequestId`, derived workflow identity, and canonical `requestDigest`; missing, changed, or omitted binding evidence fails closed before a digest is returned. This context is owner-authentication and replay evidence, not an end-user role and not part of the content digest. Temporal activities never propagate the human operator JWT; operator authority ends when Game Design starts or attaches to the workflow. Each response's tenant and complete scope tuple must be exact-compared by Game Design before recording or gating the attestation; Game Design remains publication coordinator and each participant remains owner of its digest. The publication read uses its own `publicationDigestRequest/v1` SHA-256 contract, not ADR 0047's operator-mutation digest. Let `segment(bytes)` be ADR 0047's unsigned canonical ASCII byte count, `:`, then those exact bytes; let `field(name, value) = segment(utf8(name)) + segment(utf8(value))`. The preimage is `segment(utf8("publicationDigestRequest/v1"))` followed, in this fixed order, by fields `tenantId`, `scopeKind`, `versionId`, `baseVersionId`, `scriptPatchVersion`, `publishRequestId`, and `derivedWorkflowIdentity`. `scopeKind` is exactly `FULL_VERSION` or `SCRIPT_PATCH`. A full request has a canonical positive-decimal `versionId` and empty `baseVersionId`/`scriptPatchVersion`; a patch has an empty `versionId`, canonical positive-decimal `baseVersionId`, and nonempty `scriptPatchVersion`. Empty inactive fields are framed, not omitted. Text fields are nonempty Unicode NFC without malformed scalar values or surrounding whitespace, except for the explicitly empty inactive scope fields; tenant and publish-request IDs also reject `:` so the existing workflow-ID derivation cannot alias two tuples. The digest is the lowercase 64-hex-character SHA-256 of the preimage. The derived workflow identity is `publish::publish-request:` for full publish and `publish-script-patch::publish-request:` for script patch; receivers recompute and compare it before comparing the digest. Neither notes nor a digest of content is an input: notes belong to Game Design's separate control-plane content digest. The script-patch command must carry and retain a stable caller-supplied `publishRequestId`, rather than generating one during publication. Shared golden vectors cover both scope branches, non-ASCII and delimiter-bearing patch values, and changed/omitted-field rejection; producers and all four receivers use the same grammar rather than local string joins. @@ -216,6 +216,8 @@ Rules: ### Digest Schema Migration +**Current implementation status:** Entity's digest producer and Game Design's publish gate use schema v2, while retained schema-v1 Entity full-version baselines are not automatically rewritten by an ordinary publish. A protected, one-shot Game Design maintenance operation enumerates those old baselines, obtains exact-scope v2 evidence from Entity, and conditionally replaces one complete expected-old tuple together with an immutable before/after audit in a single database transaction. It changes the digest, schema, and applied-commit evidence while retaining the live row's original and last publish-workflow provenance; the separate audit records the migration operation and time. It reports success only after exact baseline and audit readback. This reader/reconciler understands both stored baseline schemas; it never compares v1 content with v2 content for publication, and the v2-only gate remains fail closed. Deployment requires the controlled publication window and exact operator preflight in [Game Design operations](./operations.md). No live retained-row migration or no-data proof is implied by code or test fixtures. Entity's current `version:` applied-commit token remains synthetic and does not establish an applied-revision ledger. + Digest semantics are part of the publish safety contract. Changing which rows/fields participate in a domain digest, or how they are canonicalized, requires an explicit migration plan: 1. **Introduce the new digest semantics** diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8320c31b83..0a3999801b 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -99,3 +99,8 @@ Entry format: - Context: a Game Session correction rejected unowned or ambiguous `PLAY` actors, while a shared Docker-backed WebSocket integration fixture still returned actor rows with protobuf-default playable scope. - Observation: local integration tests skipped without Docker, but CI executed them and many otherwise unrelated scenarios failed at the first `PLAY` with `PLAY_IDENTITY_UNAVAILABLE`; the fixture's missing scope and bare selection obscured the intended assertions. - Expected pattern: when actor-entry validation changes, update shared fixtures with complete tenant, account, actor, and playable-scope evidence; use explicit selection for success cases and retain a separate ambiguity-denial case. Treat compiled/skipped local tests as unproved until the composed CI cases execute. + +- `2026-09-26`: One-shot certificate issuance and readback require separate proof + - Context: the Entity baseline migrator needs a short-lived dedicated client identity without giving its certificate writer general Secret-read or deletion privileges. + - Observation: a leaf verifying against the CA bundled in the same Secret is only self-consistent; it does not show that the namespace trusts that CA, and static issuance tests do not show the live Entity server accepts the identity. + - Expected pattern: keep issuance opt-in and narrowly admitted, verify the projected leaf and chain against the namespace's independent trust projection under a separately authorized reader, then report live served-mTLS acceptance and later identity retirement as distinct proof. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 129f903030..797da0ac56 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -22,6 +22,8 @@ AR-1.5 full-version publication now reserves its Draft version and PENDING attem The publication proof recorded in this tracker remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams. V28 now corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. It does not prove the end-to-end Temporal activity-to-owner path, database rollback/ambiguous-commit recovery, or live workload-certificate admission. This migration correction is separate from the still-open arbitrary `CompareAndSetVersionState` transition gap recorded below. +`AR-3.2` Entity digest-schema catch-up now has a dedicated historical-baseline migration path in the Game Design owner: bounded v1 full-version enumeration, exact tenant/version and expected-old preflight, v2 Entity recomputation, atomic guarded baseline/audit write, and exact persisted readback/retry. It is a protected one-shot Job, not ordinary publication or a public operator API. This code and its synthetic test rows do not prove that deployed retained v1 rows were migrated or that the live scoped row set is empty. The controlled readers-first publication window, dedicated migrator certificate issuance, live PostgreSQL readback, and later review remain rollout gates; Entity's `version:` commit token still does not prove applied-revision convergence. Keep the capability partial until those boundaries have actual evidence. + Asset lifecycle status remains partial: publication and artifact services provide the current bounded release-bundle and asset-storage seams, but the destructive lifecycle operations (`TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets`) still lack proved durable operation handling and owner-local epoch/CAS protection. `BeginPurgeVersionAssets` currently mints a random workflow identity, and artifact and Version saves lack DB epoch predicates/affected-row proof. The canonical lifecycle and operation contract is owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status), with [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) providing provenance. The live `CompareAndSetVersionState` path has an additional transition-safety gap: it accepts any non-null lifecycle enum after its in-memory epoch check, without requiring a committed release bundle/artifact for `DRAFT -> PUBLISHED` or enforcing active-instance/template/in-flight-activation predicates before retirement. It must not be rated as activation- or retirement-safe until the legal transition matrix, guards, and focused proof are implemented. Purge failure status is likewise not durable today: `FinalizePurgeVersionAssets` saves `PURGE_FAILED`/failed-workflow markers and rethrows inside `@Transactional`, so rollback can discard those markers after object deletion, leaving durable `PURGE_IN_PROGRESS` without reliable resume evidence. Target recovery needs an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused deletion/post-delete-save proof. diff --git a/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh b/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh index 3cc0830460..688ad78618 100755 --- a/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh +++ b/dev-tools/hosted/preview/ensure-standalone-transport-certificates.sh @@ -21,22 +21,37 @@ if [[ $# -eq 1 && "$1" != --wait ]]; then elif [[ $# -eq 2 && "$1" == --wait ]]; then transport_operation='wait' namespace="$2" +elif [[ $# -eq 2 && "$1" == --migrator ]]; then + transport_operation='write-migrator' + namespace="$2" +elif [[ $# -eq 2 && "$1" == --verify-migrator ]]; then + transport_operation='verify-migrator' + namespace="$2" else - echo "usage: $0 [--wait] " >&2 + echo "usage: $0 [--wait|--migrator|--verify-migrator] " >&2 exit 2 fi -if [[ ! "$namespace" =~ ^pr-[1-9][0-9]{0,50}$ ]]; then +if [[ "$transport_operation" == write || "$transport_operation" == wait ]] && + [[ ! "$namespace" =~ ^pr-[1-9][0-9]{0,50}$ ]]; then echo "runtime namespace must be canonical pr-N: ${namespace}" >&2 exit 2 fi +if [[ ! "$namespace" =~ ^(dev|pr-[1-9][0-9]{0,50})$ ]]; then + echo "runtime namespace must be dev or canonical pr-N: ${namespace}" >&2 + exit 2 +fi + telnet_certificate="${namespace}-telnet-tls" gateway_certificate="${namespace}-gateway-internal-ws" bridge_certificate="${namespace}-tcp-proxy-bridge" public_hostname="${namespace}.${PREVIEW_DOMAIN}" gateway_dns_name="spring-cloud-gateway-mtls.${namespace}.svc.cluster.local" bridge_uri_san="spiffe://firemud/ns/${namespace}/sa/tcp-proxy-service" +migrator_certificate="${namespace}-grpc-game-design-baseline-migrator" +migrator_secret='firemud-grpc-game-design-baseline-migrator' +migrator_uri_san="spiffe://firemud/ns/${namespace}/sa/game-design-baseline-migrator" deadline=$((SECONDS + certificate_wait_timeout_seconds)) write_certificates() { @@ -121,6 +136,110 @@ spec: EOF } +write_migrator_certificate() { + cat <&2 + return 1 + fi + printf 'namespace=%s\ncertificate=%s\nready=true\n' "$namespace" "$migrator_certificate" +} + +verify_migrator_secret() { + local secret_json trusted_ca_data temp_dir san_output eku_output + if ! kubectl --namespace "$namespace" wait \ + --for=condition=Ready "certificate/${migrator_certificate}" \ + --timeout="${certificate_wait_timeout_seconds}s"; then + echo "Certificate/${migrator_certificate} is not Ready; refusing migrator identity verification." >&2 + return 1 + fi + if ! secret_json="$(kubectl --namespace "$namespace" get secret "$migrator_secret" -o json)"; then + echo "Unable to read Secret/${migrator_secret}; refusing migrator identity verification." >&2 + return 1 + fi + if ! trusted_ca_data="$(kubectl --namespace "$namespace" get secret firemud-grpc-tls \ + -o 'jsonpath={.data.ca\.crt}')" || [[ -z "$trusted_ca_data" ]]; then + echo "Unable to read the canonical firemud-grpc-tls CA projection; refusing migrator identity verification." >&2 + return 1 + fi + if ! jq -e --arg name "$migrator_secret" ' + .metadata.name == $name and + .type == "kubernetes.io/tls" and + .data["tls.crt"] != null and .data["tls.crt"] != "" and + .data["tls.key"] != null and .data["tls.key"] != "" and + .data["ca.crt"] != null and .data["ca.crt"] != "" + ' <<<"$secret_json" >/dev/null; then + echo "Secret/${migrator_secret} is not a complete dedicated TLS projection." >&2 + return 1 + fi + + temp_dir="$(mktemp -d)" + chmod 700 "$temp_dir" + trap 'rm -rf -- "$temp_dir"' RETURN + jq -r '.data["tls.crt"]' <<<"$secret_json" | base64 --decode >"$temp_dir/tls.crt" + jq -r '.data["ca.crt"]' <<<"$secret_json" | base64 --decode >"$temp_dir/ca.crt" + base64 --decode <<<"$trusted_ca_data" >"$temp_dir/trusted-ca.crt" + if ! openssl verify -CAfile "$temp_dir/ca.crt" "$temp_dir/tls.crt" >/dev/null; then + echo "Secret/${migrator_secret} leaf does not verify against its projected CA." >&2 + return 1 + fi + if ! openssl verify -CAfile "$temp_dir/trusted-ca.crt" -partial_chain \ + "$temp_dir/ca.crt" >/dev/null || + ! openssl verify -CAfile "$temp_dir/trusted-ca.crt" -untrusted "$temp_dir/ca.crt" \ + "$temp_dir/tls.crt" >/dev/null; then + echo "Secret/${migrator_secret} CA chain is not trusted by the namespace firemud-grpc-tls bundle." >&2 + return 1 + fi + san_output="$(openssl x509 -in "$temp_dir/tls.crt" -noout -ext subjectAltName 2>/dev/null | tail -n +2 | xargs)" + if [[ "$san_output" != "URI:${migrator_uri_san}" ]]; then + echo "Secret/${migrator_secret} certificate does not contain only the exact migrator SPIFFE URI SAN." >&2 + return 1 + fi + eku_output="$(openssl x509 -in "$temp_dir/tls.crt" -noout -ext extendedKeyUsage 2>/dev/null | tail -n +2 | xargs)" + if [[ "$eku_output" != 'TLS Web Client Authentication' ]]; then + echo "Secret/${migrator_secret} certificate is not clientAuth-only." >&2 + return 1 + fi + printf 'namespace=%s\nsecret=%s\nleaf-ca-match=true\nnamespace-trust-match=true\nuri-san=%s\nclient-auth-only=true\n' \ + "$namespace" "$migrator_secret" "$migrator_uri_san" +} + wait_for_certificates() { local certificate remaining for certificate in "$telnet_certificate" "$gateway_certificate" "$bridge_certificate"; do @@ -177,7 +296,11 @@ wait_for_secret_projection() { return 1 } -if [[ "$transport_operation" == write ]]; then +if [[ "$transport_operation" == write-migrator ]]; then + write_migrator_certificate +elif [[ "$transport_operation" == verify-migrator ]]; then + verify_migrator_secret +elif [[ "$transport_operation" == write ]]; then write_certificates wait_for_certificates printf 'namespace=%s\ncertificates=ready\n' "$namespace" diff --git a/dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh b/dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh new file mode 100644 index 0000000000..f31ea8c543 --- /dev/null +++ b/dev-tools/tests/helm-entity-digest-baseline-migration-contract.sh @@ -0,0 +1,375 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +CHART_DIR="$ROOT_DIR/k8s/helm/firemud" +TMP_DIR="$(mktemp -d)" +trap 'rm -rf "$TMP_DIR"' EXIT + +if ! command -v helm >/dev/null 2>&1; then + echo "helm is required to render the Entity baseline migration contract" >&2 + exit 1 +fi + +VALUES="$TMP_DIR/preview-values.yaml" +python3 "$ROOT_DIR/dev-tools/hosted/preview/render-preview-values.py" \ + "$CHART_DIR/values-hosted-shared.example.yaml" \ + "$VALUES" \ + 123 \ + pr-123 \ + pr-123 \ + pr-123.preview.firedevops.net \ + pr-123-deadbeef \ + 32000 + +python3 - "$ROOT_DIR" "$CHART_DIR" "$VALUES" "$TMP_DIR" <<'PY' +import copy +import pathlib +import subprocess +import sys + +import yaml + +root = pathlib.Path(sys.argv[1]) +chart = pathlib.Path(sys.argv[2]) +values = pathlib.Path(sys.argv[3]) +tmp = pathlib.Path(sys.argv[4]) +base = yaml.safe_load(values.read_text(encoding="utf-8")) +image = "ghcr.io/benhook1013/game-design-service@sha256:" + "a" * 64 + + +def render(name, override=None): + namespace = base.get("preview", {}).get("namespace", "pr-123") + args = [ + "helm", + "template", + name, + str(chart), + "--namespace", + namespace, + "-f", + str(values), + ] + if override is not None: + override_path = tmp / f"{name}-override.yaml" + override_path.write_text(yaml.safe_dump(override), encoding="utf-8") + args.extend(["-f", str(override_path)]) + return subprocess.run(args, text=True, capture_output=True, check=False) + + +def documents(output): + return [ + item + for item in yaml.safe_load_all(output) + if isinstance(item, dict) + ] + + +def require_failure(case, override, expected_fragment): + result = render(f"invalid-{case}", override) + if result.returncode == 0: + raise SystemExit(f"Helm accepted invalid migration configuration: {case}") + if expected_fragment not in result.stderr: + raise SystemExit( + f"Helm failure for {case} did not explain the invalid value: {result.stderr}" + ) + + +disabled = render("migration-disabled") +if disabled.returncode != 0: + raise SystemExit(f"disabled chart render failed: {disabled.stderr}") +disabled_docs = documents(disabled.stdout) +if any( + item.get("metadata", {}).get("name", "").startswith("game-design-baseline-migrator") + for item in disabled_docs +): + raise SystemExit("disabled configuration rendered migration identity or Job resources") +if any( + item.get("metadata", {}).get("name") == "game-design-baseline-migrator" + for item in disabled_docs + if item.get("kind") == "NetworkPolicy" +): + raise SystemExit("disabled configuration rendered the migration NetworkPolicy") + +migration = { + "enabled": True, + "mode": "migrate", + "targetNamespace": "pr-123", + "operationId": "entity-v1-to-v2-pr123-v42", + "tenantId": "tenant-alpha", + "versionId": "42", + "actorIdentity": "operator:baseline-migration", + "image": image, + "expectedSource": { + "kind": "ConfigMap", + "name": "entity-v1-baseline-source-2872", + "key": "expected-source.json", + }, +} +enabled = render( + "migration-enabled", + {"previewStack": {"entityDigestBaselineMigration": migration}}, +) +if enabled.returncode != 0: + raise SystemExit(f"enabled chart render failed: {enabled.stderr}") +enabled_docs = documents(enabled.stdout) +by_kind_name = { + (item.get("kind"), item.get("metadata", {}).get("name")): item + for item in enabled_docs +} +job_name = "game-design-baseline-migrator-entity-v1-to-v2-pr123-v42" +job = by_kind_name.get(("Job", job_name)) +if job is None: + raise SystemExit("enabled configuration did not render the operation-scoped Job") +if by_kind_name.get(("ServiceAccount", "game-design-baseline-migrator"), {}).get( + "automountServiceAccountToken" +) is not False: + raise SystemExit("migrator service account must not mount a Kubernetes API token") +role = by_kind_name.get(("Role", "game-design-baseline-migrator")) +if role is None or role.get("rules") != []: + raise SystemExit("migrator Role must contain no Kubernetes API permissions") +role_binding = by_kind_name.get(("RoleBinding", "game-design-baseline-migrator")) +if role_binding is None: + raise SystemExit("enabled configuration did not render the dedicated RoleBinding") + +job_template = job.get("spec", {}).get("template", {}) +pod_spec = job_template.get("spec", {}) +if pod_spec.get("serviceAccountName") != "game-design-baseline-migrator": + raise SystemExit("Job does not use the dedicated migrator service account") +if pod_spec.get("automountServiceAccountToken") is not False: + raise SystemExit("Job pod must not mount a Kubernetes API token") +container = pod_spec.get("containers", [])[0] +if container.get("image") != image: + raise SystemExit("Job image does not match the required immutable image digest") +if container.get("imagePullPolicy") != "IfNotPresent": + raise SystemExit("digest-pinned Job image must use IfNotPresent") +if "helm.sh/hook" in job.get("metadata", {}).get("annotations", {}): + raise SystemExit("migration Job must not be a Helm hook") +if job.get("spec", {}).get("backoffLimit") != 0: + raise SystemExit("migration Job must stop after its first failed attempt") +labels = job_template.get("metadata", {}).get("labels", {}) +if labels.get("app") != "game-design-baseline-migrator": + raise SystemExit("migration Job must use a Service-distinct pod label") +game_design_service = next( + ( + item + for item in enabled_docs + if item.get("kind") == "Service" + and item.get("metadata", {}).get("name") == "game-design-service" + ), + None, +) +if game_design_service is None: + raise SystemExit("expected game-design-service ClusterIP Service was not rendered") +if game_design_service.get("spec", {}).get("selector", {}).get("app") == labels["app"]: + raise SystemExit("game-design-service Service would select the migration Job pod") + +env = {entry["name"]: entry for entry in container.get("env", [])} +if any( + name in env + for name in ( + "FIREMUD_AUTH_JWT_SECRET", + "FIREMUD_AUTH_JWT_SECRET_PATH", + ) +): + raise SystemExit("migration Job must not receive the ordinary shared JWT signing secret") +if container.get("envFrom"): + raise SystemExit("migration Job must not import a broad ordinary service environment") +for name, expected in ( + ("FIREMUD_ENTITY_BASELINE_MIGRATION_ENABLED", "true"), + ("FIREMUD_ENTITY_BASELINE_MIGRATION_MODE", "migrate"), + ("FIREMUD_ENTITY_BASELINE_MIGRATION_OPERATION_ID", migration["operationId"]), + ("FIREMUD_ENTITY_BASELINE_MIGRATION_TENANT_ID", migration["tenantId"]), + ("FIREMUD_ENTITY_BASELINE_MIGRATION_VERSION_ID", migration["versionId"]), + ("FIREMUD_ENTITY_BASELINE_MIGRATION_ACTOR_IDENTITY", migration["actorIdentity"]), + ( + "FIREMUD_ENTITY_BASELINE_MIGRATION_EXPECTED_SOURCE_PATH", + "/migration/expected-source.json", + ), + ("FIREMUD_ENTITY_BASELINE_MIGRATION_TARGET_NAMESPACE", "pr-123"), +): + if env.get(name, {}).get("value") != expected: + raise SystemExit(f"Job did not bind {name} to its exact operator input") +for name in ( + "FIREMUD_ENTITY_BASELINE_MIGRATION_POD_NAMESPACE", + "FIREMUD_ENTITY_BASELINE_MIGRATION_POD_SERVICE_ACCOUNT", +): + if "fieldRef" not in env.get(name, {}).get("valueFrom", {}): + raise SystemExit(f"Job must derive {name} from downward API identity") +for name in ( + "FIREMUD_POSTGRES_USER", + "FIREMUD_POSTGRES_PASSWORD", +): + secret_ref = env.get(name, {}).get("valueFrom", {}).get("secretKeyRef", {}) + if secret_ref.get("name") != "firemud-secret": + raise SystemExit(f"Job database credential {name} is not secret-projected") +for name in ( + "FIREMUD_POSTGRES_HOST", + "FIREMUD_POSTGRES_PORT", + "FIREMUD_POSTGRES_DB", +): + config_ref = env.get(name, {}).get("valueFrom", {}).get("configMapKeyRef", {}) + if config_ref.get("name") != "firemud-config": + raise SystemExit(f"Job database setting {name} is not config-projected") + +volumes = {volume["name"]: volume for volume in pod_spec.get("volumes", [])} +if any( + volume.get("secret", {}).get("secretName") == "firemud-secret" + and volume_name not in {"grpc-identity", "grpc-trust"} + for volume_name, volume in volumes.items() +): + raise SystemExit("migration Job must not project the ordinary application Secret as a volume") +if volumes.get("grpc-identity", {}).get("secret", {}).get("secretName") != ( + "firemud-grpc-game-design-baseline-migrator" +): + raise SystemExit("Job must mount its dedicated, separately provisioned gRPC identity") +if volumes.get("grpc-trust", {}).get("secret", {}).get("secretName") != "firemud-grpc-tls": + raise SystemExit("Job must mount the fixed gRPC trust bundle") +source = volumes.get("expected-source", {}).get("configMap", {}) +if source.get("name") != migration["expectedSource"]["name"]: + raise SystemExit("Job does not mount the operator-supplied expected-source snapshot") +if source.get("items", [{}])[0].get("path") != "expected-source.json": + raise SystemExit("expected-source JSON is not projected to the runner's fixed path") + +policy = by_kind_name.get(("NetworkPolicy", "game-design-baseline-migrator")) +if policy is None: + raise SystemExit("enabled configuration did not render the isolated migration policy") +policy_spec = policy.get("spec", {}) +if policy_spec.get("podSelector", {}).get("matchLabels") != { + "app": "game-design-baseline-migrator", + "firemud.dev/workload": "game-design-baseline-migrator", +}: + raise SystemExit("migration NetworkPolicy does not select only the dedicated Job pods") +if policy_spec.get("ingress") != []: + raise SystemExit("migration Job must not accept inbound connections") +allowed = { + ( + rule.get("to", [{}])[0].get("podSelector", {}).get("matchLabels", {}).get("app"), + rule.get("ports", [{}])[0].get("port"), + ) + for rule in policy_spec.get("egress", []) + if rule.get("to") +} +if ("postgres", 5432) not in allowed or ("entity-management-service", 6565) not in allowed: + raise SystemExit("migration Job egress must include only the required DB and Entity ports") +for app, port in allowed: + if (app, port) not in {("postgres", 5432), ("entity-management-service", 6565), (None, 53)}: + raise SystemExit(f"migration Job has unrelated egress permission: {(app, port)}") + +for case, mutation, fragment in ( + ( + "missing-image", + lambda item: item.update(image=""), + "image must be an immutable image reference", + ), + ( + "tagged-image", + lambda item: item.update(image="ghcr.io/benhook1013/game-design-service:latest"), + "must end in @sha256:", + ), + ( + "missing-source", + lambda item: item.update(expectedSource={"kind": "", "name": "", "key": ""}), + "expectedSource.kind to be ConfigMap or Secret", + ), + ( + "invalid-operation-id", + lambda item: item.update(operationId="not a dns label"), + "requires a DNS-label operationId", + ), + ( + "wrong-target-namespace", + lambda item: item.update(targetNamespace="other-namespace"), + "must exactly match the Helm release namespace", + ), +): + bad = copy.deepcopy(migration) + mutation(bad) + require_failure( + case, + {"previewStack": {"entityDigestBaselineMigration": bad}}, + fragment, + ) + +preflight = { + **{key: value for key, value in migration.items() if key != "expectedSource"}, + "mode": "preflight", + "operationId": "", +} +preflight_result = render( + "migration-preflight", + {"previewStack": {"entityDigestBaselineMigration": preflight}}, +) +if preflight_result.returncode != 0: + raise SystemExit(f"scoped preflight render failed: {preflight_result.stderr}") +preflight_docs = documents(preflight_result.stdout) +preflight_job = next( + item for item in preflight_docs if item.get("kind") == "Job" and item.get("metadata", {}).get("name", "").startswith("game-design-baseline-migrator-preflight-") +) +if any(volume.get("name") == "expected-source" for volume in preflight_job["spec"]["template"]["spec"].get("volumes", [])): + raise SystemExit("read-only preflight unexpectedly requires or mounts an expected-source tuple") + +enumerate_values = { + **{key: value for key, value in migration.items() if key not in {"tenantId", "versionId", "expectedSource"}}, + "mode": "enumerate", + "operationId": "", + "afterBaselineId": "0", + "limit": 500, +} +enumerate_result = render( + "migration-enumerate", + {"previewStack": {"entityDigestBaselineMigration": enumerate_values}}, +) +if enumerate_result.returncode != 0: + raise SystemExit(f"bounded enumerate render failed: {enumerate_result.stderr}") +enumerate_docs = documents(enumerate_result.stdout) +enumerate_job = next( + item for item in enumerate_docs if item.get("kind") == "Job" and "-enumerate-" in item.get("metadata", {}).get("name", "") +) +enumerate_env = { + entry["name"]: entry + for entry in enumerate_job["spec"]["template"]["spec"]["containers"][0].get("env", []) +} +if enumerate_env.get("FIREMUD_ENTITY_BASELINE_MIGRATION_LIMIT", {}).get("value") != "500": + raise SystemExit("enumeration Job did not carry the bounded page limit") +if enumerate_env.get("FIREMUD_ENTITY_BASELINE_MIGRATION_AFTER_BASELINE_ID", {}).get("value") != "0": + raise SystemExit("enumeration Job did not start from the canonical baseline ID cursor") + +require_failure( + "enumerate-scope", + { + "previewStack": { + "entityDigestBaselineMigration": { + **enumerate_values, + "tenantId": "tenant-alpha", + } + } + }, + "enumerate mode must not set tenantId or versionId", +) +require_failure( + "excessive-limit", + { + "previewStack": { + "entityDigestBaselineMigration": { + **enumerate_values, + "limit": 501, + } + } + }, + "limit must be between 1 and 500", +) +unguarded_values = copy.deepcopy(migration) +unguarded_result = render( + "migration-network-policy-required", + { + "previewStack": { + "networkPolicies": {"enabled": False}, + "entityDigestBaselineMigration": unguarded_values, + } + }, +) +if unguarded_result.returncode == 0 or "networkPolicies.enabled=true" not in unguarded_result.stderr: + raise SystemExit("migration Job rendered without its egress NetworkPolicy") +print("Entity digest baseline migration Helm contract passed") +PY diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index 7f1daef56d..fdda9794e1 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -1430,6 +1430,28 @@ assert "object.metadata.labels['firemud.dev/role'] == 'grpc-account-service'" in assert "object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service'" in cert_manager_expression assert "object.metadata.name == 'dev-grpc-account-service'" in cert_manager_expression assert "object.metadata.name == 'dev-grpc-game-session-service'" in cert_manager_expression +assert cert_manager_expression.count( + "request.name == 'firemud-grpc-game-design-baseline-migrator'" +) == 1, "migrator Secret admission match must be a single exact branch" +for migration_secret_gate in ( + "request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$')", + "object.metadata.name == 'firemud-grpc-game-design-baseline-migrator'", + "object.metadata.labels['firemud.dev/managed-by'] == 'entity-baseline-migration'", + "object.metadata.labels['firemud.dev/role'] == 'grpc-game-design-baseline-migrator'", + "object.metadata.labels['firemud.dev/retention'] == 'ephemeral'", + "object.metadata.annotations['cert-manager.io/certificate-name'] == request.namespace + '-grpc-game-design-baseline-migrator'", + "object.metadata.annotations['cert-manager.io/issuer-name'] == 'firemud-ca-issuer'", + "ref.name == request.namespace + '-grpc-game-design-baseline-migrator'", +): + assert migration_secret_gate in cert_manager_expression, migration_secret_gate +assert "request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')" not in ( + cert_manager_expression.split( + "object.metadata.name == 'firemud-grpc-game-design-baseline-migrator'", 1 + )[0].rsplit( + "(request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager'", + 1, + )[-1] +), "migrator Secret authorization must not include retained identity namespaces" assert "request.namespace.substring(0, request.namespace.size() - 9) + '-tls'" in cert_manager_expression assert "request.namespace.substring(0, request.namespace.size() - 9) + '-telnet-tls'" in cert_manager_expression assert "request.namespace.substring(0, request.namespace.size() - 9) + '-gateway-internal-ws'" in cert_manager_expression @@ -1451,6 +1473,7 @@ assert "request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')" in certific assert "request.operation == 'DELETE'" in certificate_namespace_match assert "request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-" in certificate_namespace_match assert "request.name.startsWith(" in certificate_namespace_match +assert "request.name == request.namespace + '-grpc-game-design-baseline-migrator'" in certificate_namespace_match assert "request.operation != 'DELETE'" in certificate_namespace_match assert "object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-" in certificate_namespace_match assert "object.metadata.name.startsWith(" in certificate_namespace_match @@ -1485,6 +1508,8 @@ assert "object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gat assert "grpc-publication-" in certificate_match assert "grpc-account-service" in certificate_match assert "grpc-game-session-service" in certificate_match +assert "system:serviceaccount:firemud-system:firemud-standalone-certificate-writer" in certificate_match +assert "object.spec.secretName == 'firemud-grpc-game-design-baseline-migrator'" in certificate_match assert "object.metadata.name == 'firemud-grpc-tls'" not in certificate_match certificate_expressions = [ diff --git a/dev-tools/tests/preview-standalone-transport-certificates-contract.sh b/dev-tools/tests/preview-standalone-transport-certificates-contract.sh index f7fd7c0319..e5adfc7ffd 100755 --- a/dev-tools/tests/preview-standalone-transport-certificates-contract.sh +++ b/dev-tools/tests/preview-standalone-transport-certificates-contract.sh @@ -37,6 +37,13 @@ case " $* " in previous="$argument" done case "$secret_name" in + firemud-grpc-tls) + if [[ -z "${FAKE_KUBECTL_TRUST_CA:-}" ]]; then + echo "canonical CA fixture is required" >&2 + exit 2 + fi + base64 -w0 "$FAKE_KUBECTL_TRUST_CA" + ;; pr-42-telnet-tls) if [[ "${FAKE_KUBECTL_INCOMPLETE:-false}" == true ]]; then printf '%s' '{"metadata":{"name":"pr-42-telnet-tls"},"data":{"tls.crt":"cert"}}' @@ -50,6 +57,13 @@ case " $* " in pr-42-tcp-proxy-bridge) printf '%s' '{"metadata":{"name":"pr-42-tcp-proxy-bridge"},"data":{"tls.crt":"cert","tls.key":"key","ca.crt":"ca"}}' ;; + firemud-grpc-game-design-baseline-migrator) + if [[ -z "${FAKE_KUBECTL_SECRET_JSON:-}" ]]; then + echo "migrator Secret fixture is required" >&2 + exit 2 + fi + cat "$FAKE_KUBECTL_SECRET_JSON" + ;; *) echo "unexpected Secret lookup: $secret_name" >&2 exit 2 @@ -82,6 +96,7 @@ assert_rejected() { assert_rejected 'runtime namespace must be canonical pr-N' pr-0 assert_rejected 'runtime namespace must be canonical pr-N' pr-42-identity assert_rejected 'runtime namespace must be canonical pr-N' dev +assert_rejected 'runtime namespace must be dev or canonical pr-N' --migrator dev-identity assert_rejected 'usage:' pr-42 ignored-override assert_rejected 'usage:' --bogus pr-42 assert_rejected 'usage:' --wait @@ -215,4 +230,110 @@ grep -Fq 'did not become key-complete' "$TEMP_DIR/incomplete.err" || { exit 1 } +runtime_calls_start="$(wc -l <"$STATE_DIR/calls")" +PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + "$SCRIPT" --migrator dev >"$TEMP_DIR/migrator-issued.out" +runtime_calls="$(tail -n +$((runtime_calls_start + 1)) "$STATE_DIR/calls")" +if grep -Fq 'get secret' <<<"$runtime_calls"; then + echo "migrator certificate writer read a Secret" >&2 + exit 1 +fi +python3 - "$STATE_DIR/applied.yaml" <<'PY' +import sys +from pathlib import Path + +import yaml + +document = yaml.safe_load(Path(sys.argv[1]).read_text(encoding="utf-8")) +if document.get("kind") != "Certificate": + raise SystemExit("migrator opt-in did not apply one Certificate") +if document["metadata"].get("name") != "dev-grpc-game-design-baseline-migrator": + raise SystemExit("migrator Certificate name is not namespace-bound") +spec = document["spec"] +if spec.get("secretName") != "firemud-grpc-game-design-baseline-migrator": + raise SystemExit("migrator Certificate does not use the dedicated Secret") +if spec.get("uris") != ["spiffe://firemud/ns/dev/sa/game-design-baseline-migrator"]: + raise SystemExit("migrator Certificate URI SAN is not exact") +if "dnsNames" in spec or spec.get("usages") != ["digital signature", "key encipherment", "client auth"]: + raise SystemExit("migrator Certificate is not URI-only clientAuth") +if spec.get("issuerRef") != { + "name": "firemud-ca-issuer", + "kind": "ClusterIssuer", + "group": "cert-manager.io", +}: + raise SystemExit("migrator Certificate must use the internal ClusterIssuer") +if spec.get("secretTemplate", {}).get("metadata", {}).get("labels") != { + "firemud.dev/managed-by": "entity-baseline-migration", + "firemud.dev/role": "grpc-game-design-baseline-migrator", + "firemud.dev/retention": "ephemeral", +}: + raise SystemExit("migrator Secret labels do not match the exact admission profile") +PY + +openssl req -x509 -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/ca.key" \ + -out "$TEMP_DIR/ca.crt" -subj '/CN=FireMUD test CA' -days 1 >/dev/null 2>&1 +openssl req -new -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/leaf.key" \ + -out "$TEMP_DIR/leaf.csr" -subj '/CN=baseline migrator' \ + -addext 'subjectAltName=URI:spiffe://firemud/ns/dev/sa/game-design-baseline-migrator' \ + -addext 'extendedKeyUsage=clientAuth' \ + -addext 'keyUsage=digitalSignature,keyEncipherment' >/dev/null 2>&1 +openssl x509 -req -in "$TEMP_DIR/leaf.csr" -CA "$TEMP_DIR/ca.crt" \ + -CAkey "$TEMP_DIR/ca.key" -CAcreateserial -days 1 -copy_extensions copy \ + -out "$TEMP_DIR/leaf.crt" >/dev/null 2>&1 +jq -n \ + --arg name firemud-grpc-game-design-baseline-migrator \ + --arg leaf "$(base64 -w0 "$TEMP_DIR/leaf.crt")" \ + --arg ca "$(base64 -w0 "$TEMP_DIR/ca.crt")" \ + '{metadata:{name:$name},type:"kubernetes.io/tls",data:{"tls.crt":$leaf,"tls.key":"c2VjcmV0","ca.crt":$ca}}' \ + >"$TEMP_DIR/migrator-secret.json" +PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + FAKE_KUBECTL_SECRET_JSON="$TEMP_DIR/migrator-secret.json" \ + FAKE_KUBECTL_TRUST_CA="$TEMP_DIR/ca.crt" \ + "$SCRIPT" --verify-migrator dev >"$TEMP_DIR/migrator-verified.out" +grep -Fq 'leaf-ca-match=true' "$TEMP_DIR/migrator-verified.out" +grep -Fq 'namespace-trust-match=true' "$TEMP_DIR/migrator-verified.out" +grep -Fq 'client-auth-only=true' "$TEMP_DIR/migrator-verified.out" +if grep -Fq 'tls.key' "$TEMP_DIR/migrator-verified.out"; then + echo "migrator verification output disclosed a private-key field" >&2 + exit 1 +fi + +openssl req -new -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/wrong-leaf.key" \ + -out "$TEMP_DIR/wrong-leaf.csr" -subj '/CN=wrong migrator' \ + -addext 'subjectAltName=URI:spiffe://firemud/ns/dev/sa/game-design-service' \ + -addext 'extendedKeyUsage=clientAuth' \ + -addext 'keyUsage=digitalSignature,keyEncipherment' >/dev/null 2>&1 +openssl x509 -req -in "$TEMP_DIR/wrong-leaf.csr" -CA "$TEMP_DIR/ca.crt" \ + -CAkey "$TEMP_DIR/ca.key" -CAcreateserial -days 1 -copy_extensions copy \ + -out "$TEMP_DIR/wrong-leaf.crt" >/dev/null 2>&1 +jq -n \ + --arg name firemud-grpc-game-design-baseline-migrator \ + --arg leaf "$(base64 -w0 "$TEMP_DIR/wrong-leaf.crt")" \ + --arg ca "$(base64 -w0 "$TEMP_DIR/ca.crt")" \ + '{metadata:{name:$name},type:"kubernetes.io/tls",data:{"tls.crt":$leaf,"tls.key":"c2VjcmV0","ca.crt":$ca}}' \ + >"$TEMP_DIR/wrong-migrator-secret.json" +if PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + FAKE_KUBECTL_SECRET_JSON="$TEMP_DIR/wrong-migrator-secret.json" \ + FAKE_KUBECTL_TRUST_CA="$TEMP_DIR/ca.crt" \ + "$SCRIPT" --verify-migrator dev >"$TEMP_DIR/wrong-migrator.out" \ + 2>"$TEMP_DIR/wrong-migrator.err"; then + echo "migrator verifier accepted a certificate for another SPIFFE identity" >&2 + exit 1 +fi +grep -Fq 'does not contain only the exact migrator SPIFFE URI SAN' \ + "$TEMP_DIR/wrong-migrator.err" + +openssl req -x509 -newkey rsa:2048 -nodes -keyout "$TEMP_DIR/wrong-ca.key" \ + -out "$TEMP_DIR/wrong-ca.crt" -subj '/CN=Untrusted test CA' -days 1 >/dev/null 2>&1 +if PATH="$FAKE_BIN:$PATH" FAKE_KUBECTL_STATE="$STATE_DIR" \ + FAKE_KUBECTL_SECRET_JSON="$TEMP_DIR/migrator-secret.json" \ + FAKE_KUBECTL_TRUST_CA="$TEMP_DIR/wrong-ca.crt" \ + "$SCRIPT" --verify-migrator dev >"$TEMP_DIR/wrong-ca.out" \ + 2>"$TEMP_DIR/wrong-ca.err"; then + echo "migrator verifier accepted a CA not trusted by firemud-grpc-tls" >&2 + exit 1 +fi +grep -Fq 'CA chain is not trusted by the namespace firemud-grpc-tls bundle' \ + "$TEMP_DIR/wrong-ca.err" + echo "preview standalone transport certificate contract passed" diff --git a/dev-tools/tests/trust-bootstrap-issuance-contract.sh b/dev-tools/tests/trust-bootstrap-issuance-contract.sh index a7f989a065..0662af4c22 100755 --- a/dev-tools/tests/trust-bootstrap-issuance-contract.sh +++ b/dev-tools/tests/trust-bootstrap-issuance-contract.sh @@ -175,6 +175,10 @@ def check_contract(items: list[dict]) -> None: "object.spec.privateKey.rotationPolicy == 'Always'", "object.spec.usages == ['digital signature', 'key encipherment', 'server auth']", "object.spec.usages == ['digital signature', 'key encipherment', 'client auth']", + "object.spec.secretName == 'firemud-grpc-game-design-baseline-migrator'", + "object.spec.secretTemplate.metadata.labels == {", + "object.spec.secretTemplate.metadata.annotations == {", + "object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/game-design-baseline-migrator']", "firemud-hosted-identity-controller", "system:serviceaccount:kube-system:namespace-controller", "object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$')", @@ -205,7 +209,7 @@ def check_contract(items: list[dict]) -> None: fail("Certificate status denial message does not describe the allowed callers") require( certificate_validation, - "^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$", + "^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator))$", "standalone Certificate validation", ) for needle in ( diff --git a/k8s/helm/firemud/templates/entity-digest-baseline-migration-job.yaml b/k8s/helm/firemud/templates/entity-digest-baseline-migration-job.yaml new file mode 100644 index 0000000000..971fe8d792 --- /dev/null +++ b/k8s/helm/firemud/templates/entity-digest-baseline-migration-job.yaml @@ -0,0 +1,304 @@ +{{- $migration := .Values.previewStack.entityDigestBaselineMigration | default (dict) -}} +{{- $enabled := $migration.enabled | default false -}} +{{- if $enabled -}} +{{- if not .Values.previewStack.enabled -}} +{{- fail "previewStack.entityDigestBaselineMigration.enabled requires previewStack.enabled=true" -}} +{{- end -}} +{{- $networkPolicies := .Values.previewStack.networkPolicies | default (dict) -}} +{{- if not ($networkPolicies.enabled | default false) -}} +{{- fail "previewStack.entityDigestBaselineMigration.enabled requires previewStack.networkPolicies.enabled=true" -}} +{{- end -}} +{{- $targetNamespace := required "previewStack.entityDigestBaselineMigration.targetNamespace is required when enabled" $migration.targetNamespace -}} +{{- if ne $targetNamespace $.Release.Namespace -}} +{{- fail "previewStack.entityDigestBaselineMigration.targetNamespace must exactly match the Helm release namespace" -}} +{{- end -}} +{{- $mode := required "previewStack.entityDigestBaselineMigration.mode is required when enabled" $migration.mode -}} +{{- if not (has $mode (list "enumerate" "preflight" "migrate")) -}} +{{- fail "previewStack.entityDigestBaselineMigration.mode must be enumerate, preflight, or migrate" -}} +{{- end -}} +{{- $image := required "previewStack.entityDigestBaselineMigration.image must be an immutable image reference" $migration.image -}} +{{- if not (regexMatch "^.+@sha256:[a-f0-9]{64}$" $image) -}} +{{- fail "previewStack.entityDigestBaselineMigration.image must end in @sha256:<64 lowercase hex characters>" -}} +{{- end -}} +{{- $tenantId := $migration.tenantId | default "" -}} +{{- $versionId := $migration.versionId | default "" -}} +{{- $actorIdentity := required "previewStack.entityDigestBaselineMigration.actorIdentity is required when enabled" $migration.actorIdentity -}} +{{- if or (eq (trim $actorIdentity) "") (ne $actorIdentity (trim $actorIdentity)) -}} +{{- fail "previewStack.entityDigestBaselineMigration.actorIdentity must be non-empty and have no surrounding whitespace" -}} +{{- end -}} +{{- if gt (len $actorIdentity) 128 -}} +{{- fail "previewStack.entityDigestBaselineMigration.actorIdentity must be at most 128 characters" -}} +{{- end -}} +{{- if eq $mode "enumerate" -}} +{{- if or (ne $tenantId "") (ne $versionId "") -}} +{{- fail "enumerate mode must not set tenantId or versionId" -}} +{{- end -}} +{{- else -}} +{{- if or (eq (trim $tenantId) "") (ne $tenantId (trim $tenantId)) -}} +{{- fail "preflight and migrate modes require a non-empty tenantId without surrounding whitespace" -}} +{{- end -}} +{{- if not (regexMatch "^[1-9][0-9]*$" (toString $versionId)) -}} +{{- fail "preflight and migrate modes require a canonical positive-decimal versionId" -}} +{{- end -}} +{{- end -}} +{{- $operationId := $migration.operationId | default "" -}} +{{- if and (eq $mode "migrate") (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $operationId)) -}} +{{- fail "migrate mode requires a DNS-label operationId" -}} +{{- end -}} +{{- if gt (len $operationId) 32 -}} +{{- fail "previewStack.entityDigestBaselineMigration.operationId must be at most 32 characters" -}} +{{- end -}} +{{- $afterBaselineId := $migration.afterBaselineId | default "0" | toString -}} +{{- if not (regexMatch "^(0|[1-9][0-9]*)$" $afterBaselineId) -}} +{{- fail "afterBaselineId must be a canonical non-negative decimal" -}} +{{- end -}} +{{- $limit := $migration.limit | default 100 -}} +{{- if or (lt (int $limit) 1) (gt (int $limit) 500) -}} +{{- fail "previewStack.entityDigestBaselineMigration.limit must be between 1 and 500" -}} +{{- end -}} +{{- $expectedSource := $migration.expectedSource | default (dict) -}} +{{- if eq $mode "migrate" -}} +{{- if not (has $expectedSource.kind (list "ConfigMap" "Secret")) -}} +{{- fail "migrate mode requires expectedSource.kind to be ConfigMap or Secret" -}} +{{- end -}} +{{- $expectedSourceName := required "migrate mode requires expectedSource.name for an immutable operator-applied source tuple" $expectedSource.name -}} +{{- if not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$" $expectedSourceName) -}} +{{- fail "expectedSource.name must be a DNS subdomain" -}} +{{- end -}} +{{- $expectedSourceKey := required "migrate mode requires expectedSource.key" $expectedSource.key -}} +{{- if eq (trim $expectedSourceKey) "" -}} +{{- fail "expectedSource.key must be non-empty" -}} +{{- end -}} +{{- end -}} +{{- $grpcIdentitySecretName := required "previewStack.entityDigestBaselineMigration.grpcIdentitySecretName must name the dedicated migrator identity Secret" $migration.grpcIdentitySecretName -}} +{{- if ne $grpcIdentitySecretName "firemud-grpc-game-design-baseline-migrator" -}} +{{- fail "grpcIdentitySecretName must be firemud-grpc-game-design-baseline-migrator; shared service identities are not accepted" -}} +{{- end -}} +{{- $readScopeName := printf "%s:%s:%s:%s:%s:%s" $mode $tenantId (toString $versionId) $afterBaselineId (toString $limit) $targetNamespace | sha256sum | trunc 12 -}} +{{- $jobSuffix := $operationId -}} +{{- if ne $mode "migrate" -}} +{{- $jobSuffix = printf "%s-%s" $mode $readScopeName -}} +{{- end -}} +{{- $jobName := printf "game-design-baseline-migrator-%s" $jobSuffix -}} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: game-design-baseline-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: game-design-baseline-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +rules: [] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: game-design-baseline-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +subjects: + - kind: ServiceAccount + name: game-design-baseline-migrator + namespace: {{ .Release.Namespace | quote }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: game-design-baseline-migrator +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ $jobName | quote }} + labels: +{{ include "firemud.commonLabels" . | indent 4 }} + annotations: + firemud.dev/migration-mode: {{ $mode | quote }} + firemud.dev/migration-operation-id: {{ $operationId | quote }} +spec: + completions: 1 + parallelism: 1 + backoffLimit: 0 + activeDeadlineSeconds: 900 + template: + metadata: + labels: + app: game-design-baseline-migrator + firemud.dev/workload: game-design-baseline-migrator + spec: + serviceAccountName: game-design-baseline-migrator + automountServiceAccountToken: false + restartPolicy: Never + securityContext: + runAsNonRoot: true + runAsUser: 1000 + runAsGroup: 1000 + fsGroup: 1000 + seccompProfile: + type: RuntimeDefault + {{- with .Values.previewStack.imagePullSecrets }} + imagePullSecrets: + {{- range $secret := . }} + {{- if kindIs "string" $secret }} + - name: {{ $secret }} + {{- else }} +{{ toYaml (list $secret) | indent 8 }} + {{- end }} + {{- end }} + {{- end }} + containers: + - name: migration + image: {{ $image | quote }} + imagePullPolicy: IfNotPresent + command: + - java + args: + - -jar + - /app/app.jar + - --spring.main.web-application-type=none + - --spring.grpc.server.enabled=false + - --firemud.entity-baseline-migration.enabled=true + env: + - name: SPRING_FLYWAY_TABLE + value: flyway_schema_history_game_design_service + - name: SERVICE_SCHEMA + value: game_design_service + - name: FIREMUD_POSTGRES_HOST + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_HOST + - name: FIREMUD_POSTGRES_PORT + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_PORT + - name: FIREMUD_POSTGRES_DB + valueFrom: + configMapKeyRef: + name: firemud-config + key: FIREMUD_POSTGRES_DB + - name: FIREMUD_POSTGRES_USER + valueFrom: + secretKeyRef: + name: firemud-secret + key: FIREMUD_POSTGRES_USER + - name: FIREMUD_POSTGRES_PASSWORD + valueFrom: + secretKeyRef: + name: firemud-secret + key: FIREMUD_POSTGRES_PASSWORD + - name: FIREMUD_REDIS_ENABLED + value: "false" + - name: FIREMUD_TEMPORAL_ENABLED + value: "false" + - name: FIREMUD_TEMPORAL_WORKERS_ENABLED + value: "false" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: FIREMUD_GRPC_CERT_CHAIN_PATH + value: /tls/tls.crt + - name: FIREMUD_GRPC_PRIVATE_KEY_PATH + value: /tls/tls.key + - name: FIREMUD_GRPC_CA_CERT_PATH + value: /grpc-trust/ca.crt + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_ENABLED + value: "true" + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_MODE + value: {{ $mode | quote }} + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_OPERATION_ID + value: {{ $operationId | quote }} + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_TENANT_ID + value: {{ $tenantId | quote }} + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_VERSION_ID + value: {{ toString $versionId | quote }} + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_ACTOR_IDENTITY + value: {{ $actorIdentity | quote }} + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_EXPECTED_SOURCE_PATH + value: /migration/expected-source.json + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_TARGET_NAMESPACE + value: {{ $targetNamespace | quote }} + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_POD_SERVICE_ACCOUNT + valueFrom: + fieldRef: + fieldPath: spec.serviceAccountName + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_AFTER_BASELINE_ID + value: {{ $afterBaselineId | quote }} + - name: FIREMUD_ENTITY_BASELINE_MIGRATION_LIMIT + value: {{ int $limit | quote }} + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsUser: 1000 + runAsGroup: 1000 + capabilities: + drop: + - ALL + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + cpu: 1 + memory: 768Mi + volumeMounts: + - name: grpc-identity + mountPath: /tls + readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true + - name: migration-tmp + mountPath: /tmp + {{- if eq $mode "migrate" }} + - name: expected-source + mountPath: /migration + readOnly: true + {{- end }} + volumes: + - name: grpc-identity + secret: + secretName: {{ $grpcIdentitySecretName | quote }} + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + - name: grpc-trust + secret: + secretName: firemud-grpc-tls + items: + - key: ca.crt + path: ca.crt + - name: migration-tmp + emptyDir: + sizeLimit: 64Mi + {{- if eq $mode "migrate" }} + - name: expected-source + {{- if eq $expectedSource.kind "Secret" }} + secret: + secretName: {{ $expectedSource.name | quote }} + items: + - key: {{ $expectedSource.key | quote }} + path: expected-source.json + {{- else }} + configMap: + name: {{ $expectedSource.name | quote }} + items: + - key: {{ $expectedSource.key | quote }} + path: expected-source.json + {{- end }} + {{- end }} +{{- end -}} diff --git a/k8s/helm/firemud/templates/network-policies.yaml b/k8s/helm/firemud/templates/network-policies.yaml index f40e18b14e..1ad9aec462 100644 --- a/k8s/helm/firemud/templates/network-policies.yaml +++ b/k8s/helm/firemud/templates/network-policies.yaml @@ -26,6 +26,7 @@ {{- if $gatewayWsTls.enabled }} {{- $gatewayWsTlsTargetPort = required "previewStack.gatewayWsTls.targetPort is required when Gateway WebSocket TLS is enabled" $gatewayWsTls.targetPort }} {{- end }} +{{- $entityDigestBaselineMigration := .Values.previewStack.entityDigestBaselineMigration | default (dict) }} --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy @@ -384,4 +385,49 @@ spec: - protocol: TCP port: 9200 {{- end }} +{{- if $entityDigestBaselineMigration.enabled }} +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: game-design-baseline-migrator + labels: +{{ include "firemud.commonLabels" . | indent 4 }} +spec: + podSelector: + matchLabels: + app: game-design-baseline-migrator + firemud.dev/workload: game-design-baseline-migrator + policyTypes: + - Ingress + - Egress + ingress: [] + egress: + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + podSelector: + matchLabels: + k8s-app: kube-dns + ports: + - protocol: UDP + port: 53 + - protocol: TCP + port: 53 + - to: + - podSelector: + matchLabels: + app: postgres + ports: + - protocol: TCP + port: 5432 + - to: + - podSelector: + matchLabels: + app: entity-management-service + ports: + - protocol: TCP + port: 6565 +{{- end }} {{- end }} diff --git a/k8s/helm/firemud/values.yaml b/k8s/helm/firemud/values.yaml index f1e838a333..468a69541b 100644 --- a/k8s/helm/firemud/values.yaml +++ b/k8s/helm/firemud/values.yaml @@ -1,5 +1,25 @@ previewStack: enabled: false + entityDigestBaselineMigration: + # This is an operator-invoked protected maintenance Job. Keep it disabled + # in ordinary chart releases; no Helm hook is used to trigger execution. + enabled: false + mode: "" + targetNamespace: "" + operationId: "" + tenantId: "" + versionId: "" + afterBaselineId: "0" + limit: 100 + actorIdentity: "" + image: "" + expectedSource: + kind: "" + name: "" + key: expected-source.json + # A dedicated identity Secret must be provisioned by the environment's + # trust owner. The chart never falls back to a service certificate. + grpcIdentitySecretName: firemud-grpc-game-design-baseline-migrator # Hosted environments use the HostedEnvironmentIdentity controller for # certificate identity. Local installs retain standalone cert-manager mode. certificateIdentity: diff --git a/k8s/hosted-identity-controller/admission.yaml b/k8s/hosted-identity-controller/admission.yaml index e4783b7e0d..35783a9c55 100644 --- a/k8s/hosted-identity-controller/admission.yaml +++ b/k8s/hosted-identity-controller/admission.yaml @@ -151,19 +151,22 @@ spec: expression: >- (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && request.namespace.matches('^(dev|dev-identity|pr-[1-9][0-9]{0,50}|pr-[1-9][0-9]{0,50}-identity)$')) || + (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + request.name == 'firemud-grpc-game-design-baseline-migrator') || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$')) || ((request.namespace in ['dev', 'dev-identity'] || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && ((request.operation == 'DELETE' && - (request.name == 'firemud-grpc-tls' || request.name == 'firemud-grpc-account-service' || request.name == 'firemud-grpc-game-session-service' || + (request.name == 'firemud-grpc-tls' || request.name == 'firemud-grpc-account-service' || request.name == 'firemud-grpc-game-session-service' || request.name == 'firemud-grpc-game-design-baseline-migrator' || request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') || request.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$') || request.name == 'firemud-grpc-tls-previous' || request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))-previous$'))) || (request.operation != 'DELETE' && - (object.metadata.name == 'firemud-grpc-tls' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-game-session-service' || + (object.metadata.name == 'firemud-grpc-tls' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-game-session-service' || object.metadata.name == 'firemud-grpc-game-design-baseline-migrator' || object.metadata.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$') || object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') || object.metadata.name == 'firemud-grpc-tls-previous' || @@ -179,8 +182,9 @@ spec: (request.namespace in ['dev', 'dev-identity'] || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && - request.name.matches('^(firemud-grpc-tls|firemud-grpc-tls-previous|firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)|firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)-previous|(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))(-previous)?)$') && + request.name.matches('^(firemud-grpc-tls|firemud-grpc-tls-previous|firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)|firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)-previous|firemud-grpc-game-design-baseline-migrator|(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))(-previous)?)$') && (request.name == 'firemud-grpc-tls' || request.name == 'firemud-grpc-tls-previous' || + request.name == 'firemud-grpc-game-design-baseline-migrator' || request.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)(-previous)?$') || request.name.startsWith( ((request.namespace == 'dev' || request.namespace == 'dev-identity') ? 'dev' : @@ -237,6 +241,26 @@ spec: request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$') ? request.namespace.substring(0, request.namespace.size() - 9) : request.namespace) + '-')))))))) || + (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && + request.operation in ['CREATE', 'UPDATE'] && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + object.type == 'kubernetes.io/tls' && + object.metadata.name == 'firemud-grpc-game-design-baseline-migrator' && + has(object.metadata.labels) && + object.metadata.labels['firemud.dev/managed-by'] == 'entity-baseline-migration' && + object.metadata.labels['firemud.dev/role'] == 'grpc-game-design-baseline-migrator' && + object.metadata.labels['firemud.dev/retention'] == 'ephemeral' && + has(object.metadata.annotations) && + object.metadata.annotations['firemud.dev/provenance'] == 'cert-manager' && + object.metadata.annotations['cert-manager.io/certificate-name'] == request.namespace + '-grpc-game-design-baseline-migrator' && + object.metadata.annotations['cert-manager.io/issuer-name'] == 'firemud-ca-issuer' && + object.metadata.annotations['cert-manager.io/issuer-kind'] == 'ClusterIssuer' && + object.metadata.annotations['cert-manager.io/issuer-group'] == 'cert-manager.io' && + ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || + object.metadata.ownerReferences.all(ref, + ref.apiVersion == 'cert-manager.io/v1' && + ref.kind == 'Certificate' && + ref.name == request.namespace + '-grpc-game-design-baseline-migrator'))) || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.operation in ['CREATE', 'UPDATE'] && request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$') && @@ -288,13 +312,20 @@ spec: - expression: >- request.userInfo.username != 'system:serviceaccount:cert-manager:cert-manager' || (request.operation in ['CREATE', 'UPDATE'] && - request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$') && + ((request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + object.metadata.name == 'firemud-grpc-game-design-baseline-migrator' && + ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || + object.metadata.ownerReferences.all(ref, + ref.apiVersion == 'cert-manager.io/v1' && + ref.kind == 'Certificate' && + ref.name == request.namespace + '-grpc-game-design-baseline-migrator'))) || + (request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$') && object.metadata.name != 'firemud-grpc-tls' && ((!has(object.metadata.ownerReferences) || object.metadata.ownerReferences.size() == 0) || object.metadata.ownerReferences.all(ref, ref.apiVersion == 'cert-manager.io/v1' && ref.kind == 'Certificate' && - ref.name == object.metadata.name))) + ref.name == object.metadata.name))))) message: cert-manager may not write a TLS Secret outside its exact Certificate ownership boundary reason: Forbidden --- @@ -327,6 +358,9 @@ spec: - name: hosted-identity-certificate-namespace expression: >- request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' || + (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + request.name == request.namespace + '-grpc-game-design-baseline-migrator') || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.namespace.matches('^(dev-identity|pr-[1-9][0-9]{0,50}-identity)$')) || (request.userInfo.groups.exists(group, group == 'system:masters') && @@ -350,6 +384,13 @@ spec: request.subResource == '' && request.operation == 'DELETE' && (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$'))) || + (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && + request.subResource == '' && + request.operation in ['CREATE', 'UPDATE'] && + request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + request.name == request.namespace + '-grpc-game-design-baseline-migrator' && + object.spec.secretName == 'firemud-grpc-game-design-baseline-migrator' && + object.spec.issuerRef.name == 'firemud-ca-issuer') || (request.userInfo.username == 'system:serviceaccount:kube-system:namespace-controller' && request.subResource == '' && request.operation == 'DELETE' && diff --git a/k8s/trust-bootstrap/issuance-admission.yaml b/k8s/trust-bootstrap/issuance-admission.yaml index a831a48a98..b273c80a6a 100644 --- a/k8s/trust-bootstrap/issuance-admission.yaml +++ b/k8s/trust-bootstrap/issuance-admission.yaml @@ -57,7 +57,9 @@ spec: owner.kind == 'Certificate' && owner.controller == true && owner.blockOwnerDeletion == true && - owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$'))) + (owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') || + (request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + owner.name == request.namespace + '-grpc-game-design-baseline-migrator')))) message: internal CertificateRequests must use the canonical ClusterIssuer and be owned by a canonical Certificate reason: Forbidden - expression: >- @@ -112,7 +114,9 @@ spec: owner.kind == 'Certificate' && owner.controller == true && owner.blockOwnerDeletion == true && - owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$'))) + (owner.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') || + (request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && + owner.name == request.namespace + '-grpc-game-design-baseline-migrator')))) message: internal CertificateRequest approval and status may not alter its canonical spec or ownership reason: Forbidden @@ -149,24 +153,24 @@ spec: (has(oldObject.spec.issuerRef) && oldObject.spec.issuerRef.name == 'firemud-ca-issuer' || ((oldObject.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$') && + (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) || (request.operation == 'CREATE' && (has(object.spec.issuerRef) && object.spec.issuerRef.name == 'firemud-ca-issuer' || ((object.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$') && + (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) || (request.operation == 'UPDATE' && (has(object.spec.issuerRef) && object.spec.issuerRef.name == 'firemud-ca-issuer' || (object.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$') && + (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$')) || (has(oldObject.spec.issuerRef) && oldObject.spec.issuerRef.name == 'firemud-ca-issuer' || (oldObject.metadata.name.matches('^pr-[1-9][0-9]{0,50}-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge)$') && request.namespace.matches('^pr-[1-9][0-9]{0,50}$')) || - (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$') && + (oldObject.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) validations: - expression: >- @@ -174,21 +178,21 @@ spec: (request.operation == 'DELETE' && request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && - request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$')) || + request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator))$')) || (request.operation == 'DELETE' && request.userInfo.username == 'system:serviceaccount:kube-system:namespace-controller' && (request.namespace == 'dev' || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && - request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$')) || + request.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator))$')) || (request.operation != 'DELETE' && ((request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-standalone-certificate-writer' && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$') && (request.namespace.matches('^pr-[1-9][0-9]{0,50}$') || object.metadata.name.contains('-grpc-')) && - object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') && + object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator))$') && object.metadata.name.startsWith(request.namespace + '-') && has(object.spec.secretName) && ((object.metadata.name.contains('-grpc-') && - object.spec.secretName.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)$')) || + object.spec.secretName.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|game-design-baseline-migrator)$')) || (!object.metadata.name.contains('-grpc-') && object.spec.secretName == object.metadata.name)) && has(object.spec.isCA) && @@ -264,7 +268,23 @@ spec: object.spec.issuerRef.name == 'firemud-ca-issuer' && object.spec.dnsNames == ['game-session-service', 'game-session-service.' + request.namespace, 'game-session-service.' + request.namespace + '.svc', 'game-session-service.' + request.namespace + '.svc.cluster.local'] && object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/game-session-service'] && - object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth']))) || + object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth']) || + (object.metadata.name.endsWith('-grpc-game-design-baseline-migrator') && + object.spec.secretName == 'firemud-grpc-game-design-baseline-migrator' && + object.spec.issuerRef.name == 'firemud-ca-issuer' && + has(object.spec.secretTemplate) && + has(object.spec.secretTemplate.metadata) && + object.spec.secretTemplate.metadata.labels == { + 'firemud.dev/managed-by': 'entity-baseline-migration', + 'firemud.dev/role': 'grpc-game-design-baseline-migrator', + 'firemud.dev/retention': 'ephemeral' + } && + object.spec.secretTemplate.metadata.annotations == { + 'firemud.dev/provenance': 'cert-manager' + } && + (!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && + object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/game-design-baseline-migrator'] && + object.spec.usages == ['digital signature', 'key encipherment', 'client auth']))) || (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))$') && diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java index f5515c67b5..3d15d9f402 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentity.java @@ -30,6 +30,7 @@ public record GrpcPeerIdentity(String uri, String namespace, String service) { "account-service", "automation-scripting-service", "entity-management-service", + "game-design-baseline-migrator", "game-design-service", "game-logic-service", "game-session-service", diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java index 512f4fb6ec..cc30881086 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java @@ -30,6 +30,15 @@ void extractsOneAllowedUriSanFromAuthenticatedLeaf() throws Exception { .containsExactly(GAME_DESIGN_URI, "firemud", "game-design-service"); } + @Test + void extractsDedicatedEntityBaselineMigratorIdentity() throws Exception { + String uri = "spiffe://firemud/ns/firemud/sa/game-design-baseline-migrator"; + assertThat(GrpcPeerIdentity.fromSslSession(sessionWithUriSans(uri))) + .get() + .extracting(GrpcPeerIdentity::uri, GrpcPeerIdentity::namespace, GrpcPeerIdentity::service) + .containsExactly(uri, "firemud", "game-design-baseline-migrator"); + } + @Test void normalizesCanonicalEquivalentUriSanBeforeValidatingWorkloadIdentity() { assertThat(GrpcPeerIdentity.parseUri("spiffe://FIREMUD/ns/%66iremud/sa/game-%64esign-service")) diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/PublicationReadGuard.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/PublicationReadGuard.java index 6f8ac466fb..3d17998c71 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/PublicationReadGuard.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/PublicationReadGuard.java @@ -32,6 +32,7 @@ public final class PublicationReadGuard { AUTOMATION_SCRIPTING_DIGEST_METHOD); private static final String GAME_DESIGN_SERVICE = "game-design-service"; + private static final String ENTITY_BASELINE_MIGRATOR = "game-design-baseline-migrator"; private final String trustedNamespace; public PublicationReadGuard(String trustedNamespace) { @@ -59,6 +60,14 @@ public boolean protects(String fullMethodName) { */ public void requirePublicationRead(String fullMethodName) { if (protects(fullMethodName)) { + GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); + if (ENTITY_MANAGEMENT_DIGEST_METHOD.equals(fullMethodName) + && peerIdentity != null + && peerIdentity.isService(ENTITY_BASELINE_MIGRATOR) + && peerIdentity.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return; + } requireGameDesignWorkload(); } } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/PublicationReadGuardTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/PublicationReadGuardTest.java index 62bb1f5f42..884b93fb08 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/PublicationReadGuardTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/PublicationReadGuardTest.java @@ -22,6 +22,11 @@ class PublicationReadGuardTest { "spiffe://firemud/ns/firemud/sa/game-design-service", TRUSTED_NAMESPACE, "game-design-service"); + private static final GrpcPeerIdentity ENTITY_BASELINE_MIGRATOR_PEER = + new GrpcPeerIdentity( + "spiffe://firemud/ns/firemud/sa/game-design-baseline-migrator", + TRUSTED_NAMESPACE, + "game-design-baseline-migrator"); private final PublicationReadGuard guard = new PublicationReadGuard(TRUSTED_NAMESPACE); @@ -61,6 +66,42 @@ void allowsAllFourExactPublicationReadsWithWorkloadOnlyContext() { }); } + @Test + void baselineMigratorCanReadOnlyTheEntityDigestWithoutUserContext() { + withPeer( + ENTITY_BASELINE_MIGRATOR_PEER, + () -> { + guard.requirePublicationRead(PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD); + for (String method : PublicationReadGuard.PUBLICATION_READ_METHODS) { + if (!method.equals(PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD)) { + assertThatThrownBy(() -> guard.requirePublicationRead(method)) + .isInstanceOf(AdminAuthorizationException.class); + } + } + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + assertThatThrownBy( + () -> + guard.requirePublicationRead( + PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD)) + .isInstanceOf(AdminAuthorizationException.class); + }); + } + + @Test + void baselineMigratorFromAnotherNamespaceCannotReadEntityDigest() { + withPeer( + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-design-baseline-migrator", + "other", + "game-design-baseline-migrator"), + () -> + assertThatThrownBy( + () -> + guard.requirePublicationRead( + PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD)) + .isInstanceOf(AdminAuthorizationException.class)); + } + @Test void deniesAuthenticatedUserContextEvenWithGameDesignPeer() { withPeer( diff --git a/services/entity-management-service/src/main/resources/application.yml b/services/entity-management-service/src/main/resources/application.yml index d3b5e99641..72384115b1 100644 --- a/services/entity-management-service/src/main/resources/application.yml +++ b/services/entity-management-service/src/main/resources/application.yml @@ -73,6 +73,8 @@ firemud: grpc: public-methods: - entity_management.v1.EntityManagementService/Ping + # JWT is not authority for this read: its handler requires an exact mTLS workload peer. + - entity_management.v1.EntityManagementService/GetDraftDesignDigest grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/EntityPublicationReadConfigurationTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/EntityPublicationReadConfigurationTest.java new file mode 100644 index 0000000000..c3cafe015c --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/EntityPublicationReadConfigurationTest.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.entitymanagement; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.security.PublicationReadGuard; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.config.YamlMapFactoryBean; +import org.springframework.core.io.FileSystemResource; + +class EntityPublicationReadConfigurationTest { + @Test + void onlyPingAndTheMtlsGuardedDigestBypassJwtAtTheTransport() { + YamlMapFactoryBean yaml = new YamlMapFactoryBean(); + yaml.setResources(new FileSystemResource("src/main/resources/application.yml")); + Map properties = yaml.getObject(); + + assertThat(properties).isNotNull(); + Map firemud = (Map) properties.get("firemud"); + Map auth = (Map) firemud.get("auth"); + Map grpc = (Map) auth.get("grpc"); + List methods = + ((List) grpc.get("public-methods")).stream().map(String::valueOf).toList(); + assertThat(methods) + .containsExactly( + "entity_management.v1.EntityManagementService/Ping", + PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java index d63df1e4df..2e5663f873 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/GameDesignServiceApplication.java @@ -2,8 +2,10 @@ import net.firedevops.firemud.common.GlobalExceptionHandler; import org.springframework.boot.SpringApplication; +import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Import; @SpringBootApplication @@ -11,6 +13,27 @@ @Import(GlobalExceptionHandler.class) public class GameDesignServiceApplication { public static void main(String[] args) { - SpringApplication.run(GameDesignServiceApplication.class, args); + if ("true".equals(System.getenv("FIREMUD_ENTITY_BASELINE_MIGRATION_ENABLED"))) { + if (System.getenv("FIREMUD_AUTH_JWT_SECRET") != null + || System.getenv("FIREMUD_AUTH_JWT_SECRET_PATH") != null) { + throw new IllegalStateException( + "migration Job must not receive the shared JWT signing key"); + } + SpringApplication application = new SpringApplication(GameDesignServiceApplication.class); + application.setWebApplicationType(WebApplicationType.NONE); + application.setDefaultProperties( + java.util.Map.of( + "spring.main.web-application-type", "none", + "spring.grpc.server.enabled", "false", + "firemud.temporal.enabled", "false", + "firemud.auth.jwt-secret", + java.util.UUID.randomUUID().toString().replace("-", "") + + java.util.UUID.randomUUID().toString().replace("-", ""))); + try (ConfigurableApplicationContext ignored = application.run(args)) { + // The conditional migration runner has completed, including exact database readback. + } + } else { + SpringApplication.run(GameDesignServiceApplication.class, args); + } } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/EntityDigestBaselineMigrationAudit.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/EntityDigestBaselineMigrationAudit.java new file mode 100644 index 0000000000..847eadceda --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/EntityDigestBaselineMigrationAudit.java @@ -0,0 +1,37 @@ +package net.firedevops.firemud.gamedesign.entity; + +import java.time.LocalDateTime; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.PublishType; + +/** Immutable before-and-after evidence for one Entity digest baseline schema migration. */ +public record EntityDigestBaselineMigrationAudit( + Long id, + String operationId, + Long recordedParticipantDigestId, + String sourceTenantId, + PublishType sourcePublishType, + PublishParticipantKey sourceParticipantKey, + Long sourceBaseVersionId, + String sourceScopeValue, + String sourceAppliedCommitId, + String sourceContentDigest, + Integer sourceDigestSchemaVersion, + String sourceRecordedFromPublishWorkflowId, + LocalDateTime sourceRecordedAt, + String sourceLastVerifiedPublishWorkflowId, + LocalDateTime sourceLastVerifiedAt, + String observedTenantId, + PublishType observedPublishType, + PublishParticipantKey observedParticipantKey, + Long observedBaseVersionId, + String observedScopeValue, + String observedAppliedCommitId, + String observedContentDigest, + Integer observedDigestSchemaVersion, + String actorIdentity, + String workloadIdentity, + String outcome, + LocalDateTime committedAt) { + public static final String COMMITTED_OUTCOME = "COMMITTED"; +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java new file mode 100644 index 0000000000..cea39c5387 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunner.java @@ -0,0 +1,168 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import com.fasterxml.jackson.databind.ObjectMapper; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.ExpectedSource; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.MigrationCommand; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +/** Trusted, one-shot entry point; no HTTP, gRPC server, or user-JWT mutation route is exposed. */ +@Component +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Spring collaborators are internal to the migration Job.") +@ConditionalOnProperty( + prefix = "firemud.entity-baseline-migration", + name = "enabled", + havingValue = "true") +public class EntityDigestBaselineMigrationJobRunner implements ApplicationRunner { + private static final Logger LOG = + LoggerFactory.getLogger(EntityDigestBaselineMigrationJobRunner.class); + private static final String MIGRATOR_SERVICE = "game-design-baseline-migrator"; + private static final int MAX_BATCH_SIZE = 500; + + private final Environment environment; + private final ObjectMapper objectMapper; + private final EntityDigestBaselineMigrationService migrationService; + + public EntityDigestBaselineMigrationJobRunner( + Environment environment, + ObjectMapper objectMapper, + EntityDigestBaselineMigrationService migrationService) { + this.environment = environment; + this.objectMapper = objectMapper; + this.migrationService = migrationService; + } + + @Override + public void run(ApplicationArguments args) throws Exception { + if (!"true".equals(System.getenv("FIREMUD_ENTITY_BASELINE_MIGRATION_ENABLED")) + || !"none".equalsIgnoreCase(required("spring.main.web-application-type")) + || environment.getProperty("spring.grpc.server.enabled", Boolean.class, true) + || environment.getProperty("firemud.temporal.enabled", Boolean.class, true)) { + throw new IllegalStateException( + "migration Job must not start application listeners or workers"); + } + String namespace = required("firemud.entity-baseline-migration.pod-namespace"); + GrpcPeerIdentity identity = verifiedWorkloadIdentity(); + requireJobAuthority( + namespace, + required("firemud.entity-baseline-migration.target-namespace"), + required("firemud.entity-baseline-migration.pod-service-account"), + identity); + String workloadIdentity = identity.uri(); + + String mode = required("firemud.entity-baseline-migration.mode"); + switch (mode) { + case "enumerate" -> { + long afterId = optionalLong("firemud.entity-baseline-migration.after-baseline-id", 0); + int limit = (int) optionalLong("firemud.entity-baseline-migration.limit", MAX_BATCH_SIZE); + LOG.info( + "Entity v1 baseline enumeration targetNamespace={} result={}", + namespace, + objectMapper.writeValueAsString( + migrationService.enumerateEntityV1Batch(afterId, limit))); + } + case "preflight" -> { + String tenantId = required("firemud.entity-baseline-migration.tenant-id"); + long versionId = requiredPositiveLong("firemud.entity-baseline-migration.version-id"); + LOG.info( + "Entity baseline preflight targetNamespace={} result={}", + namespace, + objectMapper.writeValueAsString(migrationService.preflightScope(tenantId, versionId))); + } + case "migrate" -> { + String operationId = required("firemud.entity-baseline-migration.operation-id"); + String tenantId = required("firemud.entity-baseline-migration.tenant-id"); + long versionId = requiredPositiveLong("firemud.entity-baseline-migration.version-id"); + String actorIdentity = required("firemud.entity-baseline-migration.actor-identity"); + Path expectedSourcePath = + Path.of(required("firemud.entity-baseline-migration.expected-source-path")); + ExpectedSource expectedSource = + objectMapper.readValue(Files.readAllBytes(expectedSourcePath), ExpectedSource.class); + if (expectedSource.baselineId() == null) { + throw new IllegalArgumentException("expected source lacks its baseline id"); + } + MigrationCommand command = + new MigrationCommand( + operationId, + expectedSource.baselineId(), + tenantId, + versionId, + expectedSource, + actorIdentity, + workloadIdentity); + LOG.info( + "Entity baseline migration targetNamespace={} result={}", + namespace, + objectMapper.writeValueAsString(migrationService.migrate(command))); + } + default -> throw new IllegalArgumentException("unsupported migration Job mode"); + } + } + + static void requireJobAuthority( + String podNamespace, + String targetNamespace, + String podServiceAccount, + GrpcPeerIdentity identity) { + if (!podNamespace.equals(targetNamespace)) { + throw new IllegalStateException("migration Job is outside its exact target namespace"); + } + if (!MIGRATOR_SERVICE.equals(podServiceAccount)) { + throw new IllegalStateException("migration Job lacks the dedicated service account"); + } + if (identity == null + || !identity.isService(MIGRATOR_SERVICE) + || !identity.isInNamespace(podNamespace)) { + throw new IllegalStateException( + "migration client certificate has the wrong workload identity"); + } + } + + private GrpcPeerIdentity verifiedWorkloadIdentity() throws Exception { + Path certificatePath = Path.of(required("FIREMUD_GRPC_CERT_CHAIN_PATH")); + X509Certificate leaf; + try (InputStream input = Files.newInputStream(certificatePath)) { + leaf = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + return GrpcPeerIdentity.fromCertificate(leaf) + .orElseThrow( + () -> + new IllegalStateException("migration client certificate lacks one valid URI SAN")); + } + + private long optionalLong(String property, long fallback) { + String value = environment.getProperty(property); + return value == null || value.isBlank() ? fallback : Long.parseLong(value); + } + + private long requiredPositiveLong(String property) { + long value = Long.parseLong(required(property)); + if (value < 1) { + throw new IllegalArgumentException(property + " must be positive"); + } + return value; + } + + private String required(String property) { + String value = environment.getProperty(property); + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(property + " is required"); + } + return value; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/EntityDigestBaselineMigrationAuditRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/EntityDigestBaselineMigrationAuditRepository.java new file mode 100644 index 0000000000..8f8a81b941 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/EntityDigestBaselineMigrationAuditRepository.java @@ -0,0 +1,228 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.Optional; +import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.PublishType; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; + +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class EntityDigestBaselineMigrationAuditRepository { + private static final Table TABLE_REF = + DSL.table(DSL.name("entity_digest_baseline_migration_audit")); + private static final Field ID = DSL.field(DSL.name("id"), Long.class); + private static final Field OPERATION_ID = + DSL.field(DSL.name("operation_id"), String.class); + private static final Field BASELINE_ID = + DSL.field(DSL.name("recorded_participant_digest_id"), Long.class); + private static final Field SOURCE_TENANT_ID = + DSL.field(DSL.name("source_tenant_id"), String.class); + private static final Field SOURCE_PUBLISH_TYPE = + DSL.field(DSL.name("source_publish_type"), String.class); + private static final Field SOURCE_PARTICIPANT_KEY = + DSL.field(DSL.name("source_participant_key"), String.class); + private static final Field SOURCE_BASE_VERSION_ID = + DSL.field(DSL.name("source_base_version_id"), Long.class); + private static final Field SOURCE_SCOPE_VALUE = + DSL.field(DSL.name("source_scope_value"), String.class); + private static final Field SOURCE_APPLIED_COMMIT_ID = + DSL.field(DSL.name("source_applied_commit_id"), String.class); + private static final Field SOURCE_CONTENT_DIGEST = + DSL.field(DSL.name("source_content_digest"), String.class); + private static final Field SOURCE_DIGEST_SCHEMA_VERSION = + DSL.field(DSL.name("source_digest_schema_version"), Integer.class); + private static final Field SOURCE_RECORDED_FROM_WORKFLOW_ID = + DSL.field(DSL.name("source_recorded_from_publish_workflow_id"), String.class); + private static final Field SOURCE_RECORDED_AT = + DSL.field(DSL.name("source_recorded_at"), LocalDateTime.class); + private static final Field SOURCE_LAST_VERIFIED_WORKFLOW_ID = + DSL.field(DSL.name("source_last_verified_publish_workflow_id"), String.class); + private static final Field SOURCE_LAST_VERIFIED_AT = + DSL.field(DSL.name("source_last_verified_at"), LocalDateTime.class); + private static final Field OBSERVED_TENANT_ID = + DSL.field(DSL.name("observed_tenant_id"), String.class); + private static final Field OBSERVED_PUBLISH_TYPE = + DSL.field(DSL.name("observed_publish_type"), String.class); + private static final Field OBSERVED_PARTICIPANT_KEY = + DSL.field(DSL.name("observed_participant_key"), String.class); + private static final Field OBSERVED_BASE_VERSION_ID = + DSL.field(DSL.name("observed_base_version_id"), Long.class); + private static final Field OBSERVED_SCOPE_VALUE = + DSL.field(DSL.name("observed_scope_value"), String.class); + private static final Field OBSERVED_APPLIED_COMMIT_ID = + DSL.field(DSL.name("observed_applied_commit_id"), String.class); + private static final Field OBSERVED_CONTENT_DIGEST = + DSL.field(DSL.name("observed_content_digest"), String.class); + private static final Field OBSERVED_DIGEST_SCHEMA_VERSION = + DSL.field(DSL.name("observed_digest_schema_version"), Integer.class); + private static final Field ACTOR_IDENTITY = + DSL.field(DSL.name("actor_identity"), String.class); + private static final Field WORKLOAD_IDENTITY = + DSL.field(DSL.name("workload_identity"), String.class); + private static final Field OUTCOME = DSL.field(DSL.name("outcome"), String.class); + private static final Field COMMITTED_AT = + DSL.field(DSL.name("committed_at"), LocalDateTime.class); + + private final DSLContext dsl; + + public EntityDigestBaselineMigrationAuditRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Inserts one immutable audit record; operation and baseline uniqueness are enforced by SQL. */ + public EntityDigestBaselineMigrationAudit insert(EntityDigestBaselineMigrationAudit audit) { + validateCommittedAudit(audit); + Record record = + dsl.insertInto(TABLE_REF) + .set(OPERATION_ID, audit.operationId()) + .set(BASELINE_ID, audit.recordedParticipantDigestId()) + .set(SOURCE_TENANT_ID, audit.sourceTenantId()) + .set(SOURCE_PUBLISH_TYPE, audit.sourcePublishType().name()) + .set(SOURCE_PARTICIPANT_KEY, audit.sourceParticipantKey().name()) + .set(SOURCE_BASE_VERSION_ID, audit.sourceBaseVersionId()) + .set(SOURCE_SCOPE_VALUE, audit.sourceScopeValue()) + .set(SOURCE_APPLIED_COMMIT_ID, audit.sourceAppliedCommitId()) + .set(SOURCE_CONTENT_DIGEST, audit.sourceContentDigest()) + .set(SOURCE_DIGEST_SCHEMA_VERSION, audit.sourceDigestSchemaVersion()) + .set(SOURCE_RECORDED_FROM_WORKFLOW_ID, audit.sourceRecordedFromPublishWorkflowId()) + .set(SOURCE_RECORDED_AT, audit.sourceRecordedAt()) + .set(SOURCE_LAST_VERIFIED_WORKFLOW_ID, audit.sourceLastVerifiedPublishWorkflowId()) + .set(SOURCE_LAST_VERIFIED_AT, audit.sourceLastVerifiedAt()) + .set(OBSERVED_TENANT_ID, audit.observedTenantId()) + .set(OBSERVED_PUBLISH_TYPE, audit.observedPublishType().name()) + .set(OBSERVED_PARTICIPANT_KEY, audit.observedParticipantKey().name()) + .set(OBSERVED_BASE_VERSION_ID, audit.observedBaseVersionId()) + .set(OBSERVED_SCOPE_VALUE, audit.observedScopeValue()) + .set(OBSERVED_APPLIED_COMMIT_ID, audit.observedAppliedCommitId()) + .set(OBSERVED_CONTENT_DIGEST, audit.observedContentDigest()) + .set(OBSERVED_DIGEST_SCHEMA_VERSION, audit.observedDigestSchemaVersion()) + .set(ACTOR_IDENTITY, audit.actorIdentity()) + .set(WORKLOAD_IDENTITY, audit.workloadIdentity()) + .set(OUTCOME, audit.outcome()) + .set(COMMITTED_AT, audit.committedAt()) + .returning(ID) + .fetchOne(); + Long id = record == null ? null : record.get(ID); + if (id == null || id < 1) { + throw new IllegalStateException("Entity baseline migration audit insert returned no row ID"); + } + EntityDigestBaselineMigrationAudit persisted = + findByOperationId(audit.operationId()) + .orElseThrow(() -> new IllegalStateException("inserted migration audit is missing")); + if (!id.equals(persisted.id())) { + throw new IllegalStateException("inserted migration audit ID does not match readback"); + } + return persisted; + } + + /** Resolves a prior operation by its stable id for exact retry and readback. */ + public Optional findByOperationId(String operationId) { + if (operationId == null || operationId.isBlank()) { + throw new IllegalArgumentException("operationId must not be blank"); + } + return Optional.ofNullable( + dsl.selectFrom(TABLE_REF).where(OPERATION_ID.eq(operationId)).fetchOne(this::toEntity)); + } + + private void validateCommittedAudit(EntityDigestBaselineMigrationAudit audit) { + if (audit == null) { + throw new IllegalArgumentException("audit is required"); + } + requireNonBlank(audit.operationId(), "operationId"); + requireNonBlank(audit.sourceTenantId(), "sourceTenantId"); + requireNonBlank(audit.sourceScopeValue(), "sourceScopeValue"); + requireNonBlank(audit.sourceAppliedCommitId(), "sourceAppliedCommitId"); + requireNonBlank(audit.sourceContentDigest(), "sourceContentDigest"); + requireNonBlank(audit.sourceRecordedFromPublishWorkflowId(), "sourceRecordedFrom workflow id"); + requireNonBlank(audit.sourceLastVerifiedPublishWorkflowId(), "sourceLastVerified workflow id"); + requireNonBlank(audit.observedTenantId(), "observedTenantId"); + requireNonBlank(audit.observedScopeValue(), "observedScopeValue"); + requireNonBlank(audit.observedAppliedCommitId(), "observedAppliedCommitId"); + requireNonBlank(audit.observedContentDigest(), "observedContentDigest"); + requireNonBlank(audit.actorIdentity(), "actorIdentity"); + requireNonBlank(audit.workloadIdentity(), "workloadIdentity"); + if (audit.recordedParticipantDigestId() == null + || audit.recordedParticipantDigestId() < 1 + || audit.sourcePublishType() != PublishType.FULL_VERSION + || audit.sourceParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || audit.sourceBaseVersionId() != null + || audit.sourceDigestSchemaVersion() != 1 + || audit.sourceRecordedAt() == null + || audit.sourceLastVerifiedAt() == null + || audit.observedPublishType() != PublishType.FULL_VERSION + || audit.observedParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || audit.observedBaseVersionId() != null + || audit.observedDigestSchemaVersion() != 2 + || !audit.sourceTenantId().equals(audit.observedTenantId()) + || !audit.sourceScopeValue().equals(audit.observedScopeValue()) + || !EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME.equals(audit.outcome()) + || audit.committedAt() == null) { + throw new IllegalArgumentException("audit is not a complete Entity v1-to-v2 commit record"); + } + } + + private void requireNonBlank(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(fieldName + " must not be blank"); + } + } + + private EntityDigestBaselineMigrationAudit toEntity(Record record) { + if (record == null) { + return null; + } + return new EntityDigestBaselineMigrationAudit( + record.get(ID), + record.get(OPERATION_ID), + record.get(BASELINE_ID), + record.get(SOURCE_TENANT_ID), + PublishType.valueOf(record.get(SOURCE_PUBLISH_TYPE)), + PublishParticipantKey.valueOf(record.get(SOURCE_PARTICIPANT_KEY)), + record.get(SOURCE_BASE_VERSION_ID), + record.get(SOURCE_SCOPE_VALUE), + record.get(SOURCE_APPLIED_COMMIT_ID), + record.get(SOURCE_CONTENT_DIGEST), + record.get(SOURCE_DIGEST_SCHEMA_VERSION), + record.get(SOURCE_RECORDED_FROM_WORKFLOW_ID), + toLocalDateTime(record, SOURCE_RECORDED_AT), + record.get(SOURCE_LAST_VERIFIED_WORKFLOW_ID), + toLocalDateTime(record, SOURCE_LAST_VERIFIED_AT), + record.get(OBSERVED_TENANT_ID), + PublishType.valueOf(record.get(OBSERVED_PUBLISH_TYPE)), + PublishParticipantKey.valueOf(record.get(OBSERVED_PARTICIPANT_KEY)), + record.get(OBSERVED_BASE_VERSION_ID), + record.get(OBSERVED_SCOPE_VALUE), + record.get(OBSERVED_APPLIED_COMMIT_ID), + record.get(OBSERVED_CONTENT_DIGEST), + record.get(OBSERVED_DIGEST_SCHEMA_VERSION), + record.get(ACTOR_IDENTITY), + record.get(WORKLOAD_IDENTITY), + record.get(OUTCOME), + toLocalDateTime(record, COMMITTED_AT)); + } + + private LocalDateTime toLocalDateTime(Record record, Field field) { + Object value = record.get(field); + if (value == null) { + return null; + } + if (value instanceof LocalDateTime localDateTime) { + return localDateTime; + } + if (value instanceof Timestamp timestamp) { + return timestamp.toLocalDateTime(); + } + throw new IllegalStateException("unexpected timestamp type for " + field.getName()); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java index ea1be7127d..8717c47822 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/RecordedParticipantDigestRepository.java @@ -1,7 +1,9 @@ package net.firedevops.firemud.gamedesign.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Timestamp; import java.time.LocalDateTime; +import java.util.List; import java.util.Optional; import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; @@ -18,6 +20,9 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class RecordedParticipantDigestRepository { + private static final int MAX_ENTITY_BASELINE_MIGRATION_BATCH_SIZE = 500; + private static final int ENTITY_V1_DIGEST_SCHEMA_VERSION = 1; + private static final int ENTITY_V2_DIGEST_SCHEMA_VERSION = 2; private static final Table TABLE_REF = DSL.table(DSL.name("publish_recorded_participant_digest")); private static final Field ID = DSL.field(DSL.name("id"), Long.class); @@ -74,6 +79,144 @@ public RecordedParticipantDigestRepository(DSLContext dsl) { .fetchOne(this::toEntity)); } + /** Returns one ID-keyset page of retained full-version Entity v1 baselines. */ + public List findEntityV1FullVersionBatchAfterId( + long afterId, int limit) { + if (afterId < 0) { + throw new IllegalArgumentException("afterId must be non-negative"); + } + if (limit < 1 || limit > MAX_ENTITY_BASELINE_MIGRATION_BATCH_SIZE) { + throw new IllegalArgumentException( + "limit must be between 1 and " + MAX_ENTITY_BASELINE_MIGRATION_BATCH_SIZE); + } + return dsl.selectFrom(TABLE_REF) + .where( + ID.gt(afterId) + .and(PUBLISH_TYPE.eq(PublishType.FULL_VERSION.name())) + .and(PARTICIPANT_KEY.eq(PublishParticipantKey.ENTITY_MANAGEMENT.name())) + .and(BASE_VERSION_ID.isNull()) + .and(DIGEST_SCHEMA_VERSION.eq(ENTITY_V1_DIGEST_SCHEMA_VERSION))) + .orderBy(ID.asc()) + .limit(limit) + .fetch(this::toEntity); + } + + /** + * Reads at most two Entity full-version baselines for an exact tenant/version scope. Returning + * two rows is enough for callers to reject an ambiguous scope without loading unbounded data. + */ + public List findEntityFullVersionBaselinesByScope( + String tenantId, String versionId) { + requireNonBlank(tenantId, "tenantId"); + requireNonBlank(versionId, "versionId"); + return dsl.selectFrom(TABLE_REF) + .where( + TENANT_ID + .eq(tenantId) + .and(PUBLISH_TYPE.eq(PublishType.FULL_VERSION.name())) + .and(PARTICIPANT_KEY.eq(PublishParticipantKey.ENTITY_MANAGEMENT.name())) + .and(BASE_VERSION_ID.isNull()) + .and(SCOPE_VALUE.eq(versionId))) + .orderBy(ID.asc()) + .limit(2) + .fetch(this::toEntity); + } + + /** Reads a recorded baseline by its stable row identity for exact migration readback. */ + public Optional findById(long id) { + if (id < 1) { + throw new IllegalArgumentException("id must be positive"); + } + return Optional.ofNullable(dsl.selectFrom(TABLE_REF).where(ID.eq(id)).fetchOne(this::toEntity)); + } + + /** + * Replaces only the digest, schema, commit, and provenance when the complete expected v1 row is + * still present. The caller owns the transaction that also inserts the migration audit row. + * + * @return the number of rows changed; callers must require exactly one + */ + public int migrateEntityFullVersionBaselineIfUnchanged( + RecordedParticipantDigest expectedOld, RecordedParticipantDigest replacement) { + validateEntityBaselineMigrationPair(expectedOld, replacement); + return dsl.update(TABLE_REF) + .set(APPLIED_COMMIT_ID, replacement.getAppliedCommitId()) + .set(CONTENT_DIGEST, replacement.getContentDigest()) + .set(DIGEST_SCHEMA_VERSION, replacement.getDigestSchemaVersion()) + .where( + ID.eq(expectedOld.getId()) + .and(TENANT_ID.eq(expectedOld.getTenantId())) + .and(PUBLISH_TYPE.eq(PublishType.FULL_VERSION.name())) + .and(PARTICIPANT_KEY.eq(PublishParticipantKey.ENTITY_MANAGEMENT.name())) + .and(BASE_VERSION_ID.isNull()) + .and(SCOPE_VALUE.eq(expectedOld.getScopeValue())) + .and(APPLIED_COMMIT_ID.eq(expectedOld.getAppliedCommitId())) + .and(CONTENT_DIGEST.eq(expectedOld.getContentDigest())) + .and(DIGEST_SCHEMA_VERSION.eq(ENTITY_V1_DIGEST_SCHEMA_VERSION)) + .and( + RECORDED_FROM_PUBLISH_WORKFLOW_ID.eq( + expectedOld.getRecordedFromPublishWorkflowId())) + .and(RECORDED_AT.eq(expectedOld.getRecordedAt())) + .and( + LAST_VERIFIED_PUBLISH_WORKFLOW_ID.eq( + expectedOld.getLastVerifiedPublishWorkflowId())) + .and(LAST_VERIFIED_AT.eq(expectedOld.getLastVerifiedAt()))) + .execute(); + } + + private void validateEntityBaselineMigrationPair( + RecordedParticipantDigest expectedOld, RecordedParticipantDigest replacement) { + if (expectedOld == null || replacement == null) { + throw new IllegalArgumentException("expected and replacement baselines are required"); + } + requireNonBlank(expectedOld.getTenantId(), "expected tenantId"); + requireNonBlank(expectedOld.getScopeValue(), "expected scopeValue"); + requireNonBlank(expectedOld.getAppliedCommitId(), "expected appliedCommitId"); + requireNonBlank(expectedOld.getContentDigest(), "expected contentDigest"); + requireNonBlank( + expectedOld.getRecordedFromPublishWorkflowId(), "expected recordedFromPublishWorkflowId"); + requireNonBlank( + expectedOld.getLastVerifiedPublishWorkflowId(), "expected lastVerifiedPublishWorkflowId"); + if (expectedOld.getId() == null + || expectedOld.getId() < 1 + || expectedOld.getPublishType() != PublishType.FULL_VERSION + || expectedOld.getParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || expectedOld.getBaseVersionId() != null + || expectedOld.getDigestSchemaVersion() != ENTITY_V1_DIGEST_SCHEMA_VERSION + || expectedOld.getRecordedAt() == null + || expectedOld.getLastVerifiedAt() == null) { + throw new IllegalArgumentException("expected baseline is not a complete Entity v1 row"); + } + + requireNonBlank(replacement.getTenantId(), "replacement tenantId"); + requireNonBlank(replacement.getScopeValue(), "replacement scopeValue"); + requireNonBlank(replacement.getAppliedCommitId(), "replacement appliedCommitId"); + requireNonBlank(replacement.getContentDigest(), "replacement contentDigest"); + requireNonBlank( + replacement.getRecordedFromPublishWorkflowId(), + "replacement recordedFromPublishWorkflowId"); + requireNonBlank( + replacement.getLastVerifiedPublishWorkflowId(), + "replacement lastVerifiedPublishWorkflowId"); + if (!expectedOld.getTenantId().equals(replacement.getTenantId()) + || !expectedOld.getScopeValue().equals(replacement.getScopeValue()) + || (replacement.getId() != null && !expectedOld.getId().equals(replacement.getId())) + || replacement.getPublishType() != PublishType.FULL_VERSION + || replacement.getParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || replacement.getBaseVersionId() != null + || replacement.getDigestSchemaVersion() != ENTITY_V2_DIGEST_SCHEMA_VERSION + || replacement.getRecordedAt() == null + || replacement.getLastVerifiedAt() == null) { + throw new IllegalArgumentException("replacement is not the matching Entity v2 baseline"); + } + } + + private void requireNonBlank(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(fieldName + " must not be blank"); + } + } + public RecordedParticipantDigest save(RecordedParticipantDigest digest) { LocalDateTime recordedAt = digest.getRecordedAt() == null ? LocalDateTime.now() : digest.getRecordedAt(); @@ -94,9 +237,15 @@ public RecordedParticipantDigest save(RecordedParticipantDigest digest) { .set(RECORDED_AT, recordedAt) .set(LAST_VERIFIED_PUBLISH_WORKFLOW_ID, digest.getLastVerifiedPublishWorkflowId()) .set(LAST_VERIFIED_AT, lastVerifiedAt) - .returning() + .returning(ID) .fetchOne(); - return toEntity(record); + Long id = record == null ? null : record.get(ID); + if (id == null || id < 1) { + throw new IllegalStateException("recorded participant digest insert returned no row ID"); + } + return findById(id) + .orElseThrow( + () -> new IllegalStateException("inserted recorded participant digest is missing")); } dsl.update(TABLE_REF) .set(TENANT_ID, digest.getTenantId()) @@ -141,9 +290,23 @@ private RecordedParticipantDigest toEntity(Record record) { digest.setContentDigest(record.get(CONTENT_DIGEST)); digest.setDigestSchemaVersion(record.get(DIGEST_SCHEMA_VERSION)); digest.setRecordedFromPublishWorkflowId(record.get(RECORDED_FROM_PUBLISH_WORKFLOW_ID)); - digest.setRecordedAt(record.get(RECORDED_AT)); + digest.setRecordedAt(toLocalDateTime(record, RECORDED_AT)); digest.setLastVerifiedPublishWorkflowId(record.get(LAST_VERIFIED_PUBLISH_WORKFLOW_ID)); - digest.setLastVerifiedAt(record.get(LAST_VERIFIED_AT)); + digest.setLastVerifiedAt(toLocalDateTime(record, LAST_VERIFIED_AT)); return digest; } + + private LocalDateTime toLocalDateTime(Record record, Field field) { + Object value = record.get(field); + if (value == null) { + return null; + } + if (value instanceof LocalDateTime localDateTime) { + return localDateTime; + } + if (value instanceof Timestamp timestamp) { + return timestamp.toLocalDateTime(); + } + throw new IllegalStateException("unexpected timestamp type for " + field.getName()); + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java new file mode 100644 index 0000000000..e975be9d4d --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationService.java @@ -0,0 +1,646 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.client.EntityManagementClient; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; +import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.repository.EntityDigestBaselineMigrationAuditRepository; +import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.springframework.stereotype.Service; + +/** Bounded enumeration, preflight, and one-scope recomputation for retained Entity v1 baselines. */ +@Service +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Spring repositories and clients are internal collaborators.") +public class EntityDigestBaselineMigrationService { + private static final int SOURCE_SCHEMA_VERSION = 1; + private static final int TARGET_SCHEMA_VERSION = 2; + private static final int MAX_BATCH_SIZE = 500; + private static final int MAX_OPERATION_ID_UTF8_BYTES = 128; + private static final int MAX_AUDIT_IDENTITY_UTF8_BYTES = 256; + private static final String PUBLICATION_REQUEST_PREFIX = "entity-baseline-migration-"; + + private final RecordedParticipantDigestRepository baselineRepository; + private final EntityDigestBaselineMigrationAuditRepository auditRepository; + private final VersionRepository versionRepository; + private final EntityManagementClient entityManagementClient; + private final EntityDigestBaselineMigrationWriteService writeService; + + public EntityDigestBaselineMigrationService( + RecordedParticipantDigestRepository baselineRepository, + EntityDigestBaselineMigrationAuditRepository auditRepository, + VersionRepository versionRepository, + EntityManagementClient entityManagementClient, + EntityDigestBaselineMigrationWriteService writeService) { + this.baselineRepository = baselineRepository; + this.auditRepository = auditRepository; + this.versionRepository = versionRepository; + this.entityManagementClient = entityManagementClient; + this.writeService = writeService; + } + + /** Returns one keyset page of retained Entity full-version schema-v1 rows. */ + public EntityV1Batch enumerateEntityV1Batch(long afterBaselineId, int limit) { + if (afterBaselineId < 0) { + throw new IllegalArgumentException("afterBaselineId must be non-negative"); + } + if (limit < 1 || limit > MAX_BATCH_SIZE) { + throw new IllegalArgumentException("limit must be between 1 and " + MAX_BATCH_SIZE); + } + List rows = + baselineRepository.findEntityV1FullVersionBatchAfterId(afterBaselineId, limit); + if (rows.size() > limit) { + throw new IllegalStateException("baseline batch exceeded the requested bound"); + } + List summaries = rows.stream().map(this::toV1Summary).toList(); + Long nextAfterBaselineId = + summaries.isEmpty() ? null : summaries.get(summaries.size() - 1).baselineId(); + return new EntityV1Batch(afterBaselineId, limit, summaries, nextAfterBaselineId); + } + + /** + * Classifies exactly one tenant/version scope without writing. NO_RECORDED_BASELINE proves only + * this queried scope has no retained Entity full-version baseline at read time. + */ + public ScopePreflight preflightScope(String tenantId, long versionId) { + requireText(tenantId, "tenantId", 36); + requirePositive(versionId, "versionId"); + Version version = + versionRepository + .findByTenantIdAndId(tenantId, versionId) + .orElseThrow(() -> rejected("VERSION_MISSING", "tenant/version does not exist")); + if (!Objects.equals(version.getTenantId(), tenantId) + || !Objects.equals(version.getId(), versionId) + || version.isScriptOnly()) { + throw rejected("VERSION_SCOPE_MISMATCH", "version is outside the tenant or is script-only"); + } + List rows = + baselineRepository.findEntityFullVersionBaselinesByScope( + tenantId, Long.toString(versionId)); + if (rows.size() > 2) { + throw new IllegalStateException("scope preflight exceeded its two-row bound"); + } + for (RecordedParticipantDigest row : rows) { + if (!Objects.equals(row.getTenantId(), tenantId) + || !Objects.equals(row.getScopeValue(), Long.toString(versionId)) + || row.getPublishType() != PublishType.FULL_VERSION + || row.getParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || row.getBaseVersionId() != null) { + throw new IllegalStateException("scope query returned a row outside its exact scope"); + } + } + ScopeStatus status; + if (rows.isEmpty()) { + status = ScopeStatus.NO_RECORDED_BASELINE; + } else if (rows.size() > 1) { + status = ScopeStatus.AMBIGUOUS_BASELINE; + } else if (Objects.equals(rows.get(0).getDigestSchemaVersion(), SOURCE_SCHEMA_VERSION)) { + status = ScopeStatus.V1_REQUIRES_MIGRATION; + } else if (Objects.equals(rows.get(0).getDigestSchemaVersion(), TARGET_SCHEMA_VERSION)) { + status = ScopeStatus.V2_ALREADY_RECORDED; + } else { + status = ScopeStatus.UNSUPPORTED_SCHEMA; + } + return new ScopePreflight( + tenantId, versionId, status, rows.stream().map(this::toSummary).toList()); + } + + /** Recomputes and atomically re-records one exact Entity full-version v1 baseline. */ + public MigrationResult migrate(MigrationCommand command) { + validateCommand(command); + + Optional priorAudit = + auditRepository.findByOperationId(command.operationId()); + if (priorAudit.isPresent()) { + EntityDigestBaselineMigrationAudit audit = priorAudit.orElseThrow(); + assertAuditSourceMatchesCommand(audit, command); + return readBackCommittedResult(command, audit, MigrationDisposition.EXACT_RETRY); + } + + RecordedParticipantDigest current = + baselineRepository + .findById(command.baselineId()) + .orElseThrow(() -> rejected("BASELINE_MISSING", "baseline row does not exist")); + validateCurrentRowIdentity(current, command); + List scopeRows = + baselineRepository.findEntityFullVersionBaselinesByScope( + command.tenantId(), Long.toString(command.versionId())); + if (scopeRows.size() != 1) { + throw rejected( + scopeRows.isEmpty() ? "BASELINE_MISSING" : "BASELINE_SCOPE_AMBIGUOUS", + "the exact tenant/version scope must contain one Entity full-version baseline"); + } + if (!Objects.equals(scopeRows.get(0).getId(), command.baselineId())) { + throw rejected( + "BASELINE_ID_SCOPE_MISMATCH", "baseline id does not own the requested tenant/version"); + } + assertSourceMatchesCommand(current, command.expectedSource()); + + Version version = + versionRepository + .findByTenantIdAndId(command.tenantId(), command.versionId()) + .orElseThrow(() -> rejected("VERSION_MISSING", "tenant/version does not exist")); + if (!Objects.equals(version.getTenantId(), command.tenantId()) + || !Objects.equals(version.getId(), command.versionId()) + || version.isScriptOnly()) { + throw rejected("VERSION_SCOPE_MISMATCH", "version is outside the tenant or is script-only"); + } + + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full( + command.tenantId(), + Long.toString(command.versionId()), + stablePublicationRequestId(command.operationId())); + PublishParticipantDigestDto observed = + entityManagementClient.getDraftDesignDigestForVersion(binding); + validateObservedDigest(observed, command); + + LocalDateTime migrationTime = LocalDateTime.now().truncatedTo(ChronoUnit.MICROS); + RecordedParticipantDigest replacement = replacementFor(current, observed); + EntityDigestBaselineMigrationAudit audit = auditFor(current, observed, command, migrationTime); + try { + writeService.commit(current, replacement, audit); + } catch (RuntimeException uncertainWrite) { + try { + return readBackCommittedResult( + command, audit, MigrationDisposition.RECOVERED_AFTER_WRITE_ERROR); + } catch (RuntimeException readbackFailure) { + uncertainWrite.addSuppressed(readbackFailure); + throw rejected( + "WRITE_OUTCOME_UNPROVEN", + "migration write outcome could not be proven by exact audit and baseline readback", + uncertainWrite); + } + } + return readBackCommittedResult(command, audit, MigrationDisposition.APPLIED); + } + + private void validateCommand(MigrationCommand command) { + if (command == null) { + throw new IllegalArgumentException("migration command is required"); + } + requireText(command.operationId(), "operationId", MAX_OPERATION_ID_UTF8_BYTES); + requireText(command.tenantId(), "tenantId", 36); + requirePositive(command.baselineId(), "baselineId"); + requirePositive(command.versionId(), "versionId"); + requireText(command.actorIdentity(), "actorIdentity", MAX_AUDIT_IDENTITY_UTF8_BYTES); + requireText(command.workloadIdentity(), "workloadIdentity", MAX_AUDIT_IDENTITY_UTF8_BYTES); + ExpectedSource expected = Objects.requireNonNull(command.expectedSource(), "expectedSource"); + requireText(expected.tenantId(), "expected tenantId", 36); + requireText(expected.scopeValue(), "expected scopeValue", 128); + requireText(expected.appliedCommitId(), "expected appliedCommitId", 128); + requireText(expected.contentDigest(), "expected contentDigest", 128); + requireText(expected.recordedFromPublishWorkflowId(), "expected recordedFrom workflow", 1024); + requireText(expected.lastVerifiedPublishWorkflowId(), "expected lastVerified workflow", 1024); + if (expected.digestSchemaVersion() == null + || expected.digestSchemaVersion() != SOURCE_SCHEMA_VERSION + || expected.recordedAt() == null + || expected.lastVerifiedAt() == null + || expected.baselineId() == null + || expected.baselineId() < 1 + || !Objects.equals(expected.baselineId(), command.baselineId()) + || !Objects.equals(expected.tenantId(), command.tenantId()) + || expected.publishType() != PublishType.FULL_VERSION + || expected.participantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || expected.baseVersionId() != null + || !Objects.equals(expected.scopeValue(), Long.toString(command.versionId()))) { + throw rejected( + "SOURCE_SCHEMA_OR_PROVENANCE_INVALID", + "expected source must be a complete schema-v1 baseline with provenance"); + } + } + + private void validateCurrentRowIdentity( + RecordedParticipantDigest current, MigrationCommand command) { + if (!Objects.equals(current.getId(), command.baselineId())) { + throw rejected("BASELINE_ID_MISMATCH", "baseline readback id does not match the command"); + } + if (!Objects.equals(current.getTenantId(), command.tenantId())) { + throw rejected("BASELINE_TENANT_MISMATCH", "baseline belongs to another tenant"); + } + if (current.getPublishType() != PublishType.FULL_VERSION + || current.getParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || current.getBaseVersionId() != null) { + throw rejected( + "BASELINE_PARTICIPANT_OR_SCOPE_INVALID", "baseline is not an Entity full-version record"); + } + if (!Objects.equals(current.getScopeValue(), Long.toString(command.versionId()))) { + throw rejected("BASELINE_VERSION_MISMATCH", "baseline belongs to another version"); + } + if (!Objects.equals(current.getDigestSchemaVersion(), SOURCE_SCHEMA_VERSION)) { + throw rejected( + "SOURCE_SCHEMA_UNSUPPORTED", "migration source must be an Entity schema-v1 row"); + } + } + + private void assertSourceMatchesCommand( + RecordedParticipantDigest current, ExpectedSource expected) { + if (!Objects.equals(current.getId(), expected.baselineId()) + || !Objects.equals(current.getTenantId(), expected.tenantId()) + || current.getPublishType() != expected.publishType() + || current.getParticipantKey() != expected.participantKey() + || !Objects.equals(current.getBaseVersionId(), expected.baseVersionId()) + || !Objects.equals(current.getScopeValue(), expected.scopeValue()) + || !Objects.equals(current.getAppliedCommitId(), expected.appliedCommitId()) + || !Objects.equals(current.getContentDigest(), expected.contentDigest()) + || !Objects.equals(current.getDigestSchemaVersion(), expected.digestSchemaVersion()) + || !Objects.equals( + current.getRecordedFromPublishWorkflowId(), expected.recordedFromPublishWorkflowId()) + || !Objects.equals(current.getRecordedAt(), expected.recordedAt()) + || !Objects.equals( + current.getLastVerifiedPublishWorkflowId(), expected.lastVerifiedPublishWorkflowId()) + || !Objects.equals(current.getLastVerifiedAt(), expected.lastVerifiedAt())) { + throw rejected( + "SOURCE_BASELINE_CHANGED", + "baseline tuple or provenance changed after the expected source was captured"); + } + } + + private void validateObservedDigest( + PublishParticipantDigestDto observed, MigrationCommand command) { + if (observed == null || !observed.succeeded()) { + throw rejected( + "ENTITY_DIGEST_UNAVAILABLE", + observed == null ? "Entity returned no digest response" : observed.errorCode()); + } + if (!PublishParticipantKey.ENTITY_MANAGEMENT.name().equals(observed.participantKey()) + || !Long.toString(command.versionId()).equals(observed.scopeValue()) + || observed.baseVersionId() != null) { + throw rejected( + "ENTITY_DIGEST_SCOPE_MISMATCH", "Entity v2 evidence does not match the exact scope"); + } + if (!Objects.equals(observed.digestSchemaVersion(), TARGET_SCHEMA_VERSION)) { + throw rejected("ENTITY_DIGEST_SCHEMA_UNSUPPORTED", "Entity did not return digest schema 2"); + } + if (observed.contentDigest() == null || observed.contentDigest().isBlank()) { + throw rejected("ENTITY_DIGEST_INCOMPLETE", "Entity returned a blank v2 content digest"); + } + if (observed.contentDigest().getBytes(StandardCharsets.UTF_8).length > 128) { + throw rejected("ENTITY_DIGEST_INCOMPLETE", "Entity v2 content digest exceeds storage bounds"); + } + if (observed.appliedCommitId() == null + || observed.appliedCommitId().isBlank() + || !Objects.equals( + observed.appliedCommitId(), command.expectedSource().appliedCommitId())) { + throw rejected( + "ENTITY_APPLIED_COMMIT_MISMATCH", + "Entity v2 evidence does not preserve the expected applied-commit identity"); + } + } + + private RecordedParticipantDigest replacementFor( + RecordedParticipantDigest current, PublishParticipantDigestDto observed) { + RecordedParticipantDigest replacement = new RecordedParticipantDigest(); + replacement.setId(current.getId()); + replacement.setTenantId(current.getTenantId()); + replacement.setPublishType(current.getPublishType()); + replacement.setParticipantKey(current.getParticipantKey()); + replacement.setScopeValue(current.getScopeValue()); + replacement.setBaseVersionId(null); + replacement.setAppliedCommitId(observed.appliedCommitId()); + replacement.setContentDigest(observed.contentDigest()); + replacement.setDigestSchemaVersion(TARGET_SCHEMA_VERSION); + replacement.setRecordedFromPublishWorkflowId(current.getRecordedFromPublishWorkflowId()); + replacement.setRecordedAt(current.getRecordedAt()); + replacement.setLastVerifiedPublishWorkflowId(current.getLastVerifiedPublishWorkflowId()); + replacement.setLastVerifiedAt(current.getLastVerifiedAt()); + return replacement; + } + + private EntityDigestBaselineMigrationAudit auditFor( + RecordedParticipantDigest source, + PublishParticipantDigestDto observed, + MigrationCommand command, + LocalDateTime migrationTime) { + return new EntityDigestBaselineMigrationAudit( + null, + command.operationId(), + source.getId(), + source.getTenantId(), + source.getPublishType(), + source.getParticipantKey(), + source.getBaseVersionId(), + source.getScopeValue(), + source.getAppliedCommitId(), + source.getContentDigest(), + source.getDigestSchemaVersion(), + source.getRecordedFromPublishWorkflowId(), + source.getRecordedAt(), + source.getLastVerifiedPublishWorkflowId(), + source.getLastVerifiedAt(), + source.getTenantId(), + source.getPublishType(), + source.getParticipantKey(), + null, + source.getScopeValue(), + observed.appliedCommitId(), + observed.contentDigest(), + observed.digestSchemaVersion(), + command.actorIdentity(), + command.workloadIdentity(), + EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME, + migrationTime); + } + + private void assertAuditSourceMatchesCommand( + EntityDigestBaselineMigrationAudit audit, MigrationCommand command) { + ExpectedSource expected = command.expectedSource(); + if (!Objects.equals(audit.operationId(), command.operationId()) + || audit.id() == null + || audit.id() < 1 + || !Objects.equals(audit.recordedParticipantDigestId(), command.baselineId()) + || !Objects.equals(audit.sourceTenantId(), command.tenantId()) + || audit.sourcePublishType() != expected.publishType() + || audit.sourceParticipantKey() != expected.participantKey() + || !Objects.equals(audit.sourceBaseVersionId(), expected.baseVersionId()) + || !Objects.equals(audit.sourceScopeValue(), Long.toString(command.versionId())) + || !Objects.equals(audit.sourceAppliedCommitId(), expected.appliedCommitId()) + || !Objects.equals(audit.sourceContentDigest(), expected.contentDigest()) + || !Objects.equals(audit.sourceDigestSchemaVersion(), expected.digestSchemaVersion()) + || !Objects.equals( + audit.sourceRecordedFromPublishWorkflowId(), expected.recordedFromPublishWorkflowId()) + || !Objects.equals(audit.sourceRecordedAt(), expected.recordedAt()) + || !Objects.equals( + audit.sourceLastVerifiedPublishWorkflowId(), expected.lastVerifiedPublishWorkflowId()) + || !Objects.equals(audit.sourceLastVerifiedAt(), expected.lastVerifiedAt()) + || !Objects.equals(audit.actorIdentity(), command.actorIdentity()) + || !Objects.equals(audit.workloadIdentity(), command.workloadIdentity()) + || !Objects.equals(audit.observedTenantId(), command.tenantId()) + || audit.observedPublishType() != PublishType.FULL_VERSION + || audit.observedParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || audit.observedBaseVersionId() != null + || !Objects.equals(audit.observedScopeValue(), Long.toString(command.versionId())) + || !Objects.equals(audit.observedAppliedCommitId(), expected.appliedCommitId()) + || !Objects.equals(audit.observedDigestSchemaVersion(), TARGET_SCHEMA_VERSION) + || audit.observedContentDigest() == null + || audit.observedContentDigest().isBlank() + || !EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME.equals(audit.outcome())) { + throw rejected( + "OPERATION_ID_CONFLICT", "operation id is already bound to a different source command"); + } + } + + private MigrationResult readBackCommittedResult( + MigrationCommand command, + EntityDigestBaselineMigrationAudit expectedAudit, + MigrationDisposition disposition) { + EntityDigestBaselineMigrationAudit actualAudit = + auditRepository + .findByOperationId(command.operationId()) + .orElseThrow( + () -> + rejected("AUDIT_READBACK_MISSING", "committed migration audit was not found")); + assertAuditSourceMatchesCommand(actualAudit, command); + if (!sameAuditTarget(actualAudit, expectedAudit)) { + throw rejected("AUDIT_READBACK_MISMATCH", "audit target differs from the attempted result"); + } + RecordedParticipantDigest actualBaseline = + baselineRepository + .findById(command.baselineId()) + .orElseThrow( + () -> rejected("BASELINE_READBACK_MISSING", "migrated baseline was not found")); + if (!Objects.equals(actualBaseline.getId(), actualAudit.recordedParticipantDigestId()) + || !Objects.equals(actualBaseline.getTenantId(), actualAudit.observedTenantId()) + || actualBaseline.getPublishType() != actualAudit.observedPublishType() + || actualBaseline.getParticipantKey() != actualAudit.observedParticipantKey() + || !Objects.equals(actualBaseline.getBaseVersionId(), actualAudit.observedBaseVersionId()) + || !Objects.equals(actualBaseline.getScopeValue(), actualAudit.observedScopeValue()) + || !Objects.equals( + actualBaseline.getAppliedCommitId(), actualAudit.observedAppliedCommitId()) + || !Objects.equals(actualBaseline.getContentDigest(), actualAudit.observedContentDigest()) + || !Objects.equals( + actualBaseline.getDigestSchemaVersion(), actualAudit.observedDigestSchemaVersion()) + || !Objects.equals( + actualBaseline.getRecordedFromPublishWorkflowId(), + actualAudit.sourceRecordedFromPublishWorkflowId()) + || !Objects.equals(actualBaseline.getRecordedAt(), actualAudit.sourceRecordedAt()) + || !Objects.equals( + actualBaseline.getLastVerifiedPublishWorkflowId(), + actualAudit.sourceLastVerifiedPublishWorkflowId()) + || !Objects.equals( + actualBaseline.getLastVerifiedAt(), actualAudit.sourceLastVerifiedAt())) { + throw rejected( + "BASELINE_READBACK_MISMATCH", "persisted baseline does not exactly match its audit"); + } + return new MigrationResult( + command.operationId(), + actualAudit.id(), + actualBaseline.getId(), + command.tenantId(), + command.versionId(), + actualBaseline.getAppliedCommitId(), + actualBaseline.getContentDigest(), + actualBaseline.getDigestSchemaVersion(), + disposition); + } + + private boolean sameAuditTarget( + EntityDigestBaselineMigrationAudit actual, EntityDigestBaselineMigrationAudit expected) { + return (expected.id() == null || Objects.equals(actual.id(), expected.id())) + && Objects.equals(actual.operationId(), expected.operationId()) + && Objects.equals( + actual.recordedParticipantDigestId(), expected.recordedParticipantDigestId()) + && Objects.equals(actual.observedTenantId(), expected.observedTenantId()) + && actual.observedPublishType() == expected.observedPublishType() + && actual.observedParticipantKey() == expected.observedParticipantKey() + && Objects.equals(actual.observedBaseVersionId(), expected.observedBaseVersionId()) + && Objects.equals(actual.observedScopeValue(), expected.observedScopeValue()) + && Objects.equals(actual.observedAppliedCommitId(), expected.observedAppliedCommitId()) + && Objects.equals(actual.observedContentDigest(), expected.observedContentDigest()) + && Objects.equals( + actual.observedDigestSchemaVersion(), expected.observedDigestSchemaVersion()) + && Objects.equals(actual.actorIdentity(), expected.actorIdentity()) + && Objects.equals(actual.workloadIdentity(), expected.workloadIdentity()) + && Objects.equals(actual.outcome(), expected.outcome()) + && Objects.equals(actual.committedAt(), expected.committedAt()); + } + + private BaselineSummary toV1Summary(RecordedParticipantDigest row) { + if (row.getDigestSchemaVersion() == null + || row.getDigestSchemaVersion() != SOURCE_SCHEMA_VERSION + || row.getPublishType() != PublishType.FULL_VERSION + || row.getParticipantKey() != PublishParticipantKey.ENTITY_MANAGEMENT + || row.getBaseVersionId() != null) { + throw new IllegalStateException("v1 batch query returned a non-Entity full-version row"); + } + return toSummary(row); + } + + private BaselineSummary toSummary(RecordedParticipantDigest row) { + if (row.getId() == null || row.getId() < 1) { + throw new IllegalStateException("baseline query returned a row without a stable id"); + } + long versionId = parsePositiveVersionId(row.getId(), row.getScopeValue()); + return new BaselineSummary( + row.getId(), + row.getTenantId(), + versionId, + row.getAppliedCommitId(), + row.getContentDigest(), + row.getDigestSchemaVersion(), + row.getRecordedFromPublishWorkflowId(), + row.getRecordedAt(), + row.getLastVerifiedPublishWorkflowId(), + row.getLastVerifiedAt()); + } + + private long parsePositiveVersionId(long baselineId, String scopeValue) { + try { + long id = Long.parseLong(scopeValue); + if (id < 1 || !Long.toString(id).equals(scopeValue)) { + throw new NumberFormatException("non-canonical positive id"); + } + return id; + } catch (RuntimeException invalidScope) { + throw new IllegalStateException( + "Entity full-version baseline " + + baselineId + + " has a non-canonical positive version scope: " + + scopeValue, + invalidScope); + } + } + + private String stablePublicationRequestId(String operationId) { + try { + byte[] hash = + MessageDigest.getInstance("SHA-256").digest(operationId.getBytes(StandardCharsets.UTF_8)); + return PUBLICATION_REQUEST_PREFIX + HexFormat.of().formatHex(hash); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private void requireText(String value, String name, int maxUtf8Bytes) { + if (value == null + || value.isBlank() + || value.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes) { + throw new IllegalArgumentException(name + " must be non-blank and within its storage bound"); + } + } + + private void requirePositive(long value, String name) { + if (value < 1) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private MigrationRejectedException rejected(String code, String message) { + return new MigrationRejectedException(code, message, null); + } + + private MigrationRejectedException rejected(String code, String message, Throwable cause) { + return new MigrationRejectedException(code, message, cause); + } + + public enum ScopeStatus { + V1_REQUIRES_MIGRATION, + V2_ALREADY_RECORDED, + NO_RECORDED_BASELINE, + AMBIGUOUS_BASELINE, + UNSUPPORTED_SCHEMA + } + + public enum MigrationDisposition { + APPLIED, + EXACT_RETRY, + RECOVERED_AFTER_WRITE_ERROR + } + + public record ExpectedSource( + Long baselineId, + String tenantId, + PublishType publishType, + PublishParticipantKey participantKey, + Long baseVersionId, + String scopeValue, + String appliedCommitId, + String contentDigest, + Integer digestSchemaVersion, + String recordedFromPublishWorkflowId, + LocalDateTime recordedAt, + String lastVerifiedPublishWorkflowId, + LocalDateTime lastVerifiedAt) {} + + public record MigrationCommand( + String operationId, + long baselineId, + String tenantId, + long versionId, + ExpectedSource expectedSource, + String actorIdentity, + String workloadIdentity) {} + + public record BaselineSummary( + long baselineId, + String tenantId, + long versionId, + String appliedCommitId, + String contentDigest, + Integer digestSchemaVersion, + String recordedFromPublishWorkflowId, + LocalDateTime recordedAt, + String lastVerifiedPublishWorkflowId, + LocalDateTime lastVerifiedAt) {} + + public record EntityV1Batch( + long scannedAfterBaselineId, + int limit, + List baselines, + Long nextAfterBaselineId) { + public EntityV1Batch { + baselines = List.copyOf(baselines); + } + + public boolean isEmptyAtCursor() { + return baselines.isEmpty(); + } + } + + public record ScopePreflight( + String tenantId, long versionId, ScopeStatus status, List baselines) { + public ScopePreflight { + baselines = List.copyOf(baselines); + } + } + + public record MigrationResult( + String operationId, + Long auditId, + Long baselineId, + String tenantId, + long versionId, + String appliedCommitId, + String contentDigest, + Integer digestSchemaVersion, + MigrationDisposition disposition) {} + + public static final class MigrationRejectedException extends IllegalStateException { + private final String failureCode; + + private MigrationRejectedException(String failureCode, String message, Throwable cause) { + super(message, cause); + this.failureCode = failureCode; + } + + public String failureCode() { + return failureCode; + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java new file mode 100644 index 0000000000..7e2023c47a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteService.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; +import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; +import net.firedevops.firemud.gamedesign.repository.EntityDigestBaselineMigrationAuditRepository; +import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Commits one guarded baseline replacement and its immutable audit row in the same transaction. */ +@Service +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Spring repositories are internal collaborators.") +public class EntityDigestBaselineMigrationWriteService { + private final RecordedParticipantDigestRepository baselineRepository; + private final EntityDigestBaselineMigrationAuditRepository auditRepository; + + public EntityDigestBaselineMigrationWriteService( + RecordedParticipantDigestRepository baselineRepository, + EntityDigestBaselineMigrationAuditRepository auditRepository) { + this.baselineRepository = baselineRepository; + this.auditRepository = auditRepository; + } + + @Transactional + public void commit( + RecordedParticipantDigest expectedOld, + RecordedParticipantDigest replacement, + EntityDigestBaselineMigrationAudit audit) { + validateWriteSet(expectedOld, replacement, audit); + int updated = + baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(expectedOld, replacement); + if (updated != 1) { + throw new IllegalStateException( + "Entity v1 baseline changed before the guarded migration write"); + } + auditRepository.insert(audit); + } + + private void validateWriteSet( + RecordedParticipantDigest expectedOld, + RecordedParticipantDigest replacement, + EntityDigestBaselineMigrationAudit audit) { + Objects.requireNonNull(expectedOld, "expectedOld must not be null"); + Objects.requireNonNull(replacement, "replacement must not be null"); + Objects.requireNonNull(audit, "audit must not be null"); + if (!Objects.equals(expectedOld.getId(), replacement.getId()) + || !Objects.equals(expectedOld.getTenantId(), replacement.getTenantId()) + || expectedOld.getPublishType() != replacement.getPublishType() + || expectedOld.getParticipantKey() != replacement.getParticipantKey() + || !Objects.equals(expectedOld.getScopeValue(), replacement.getScopeValue()) + || !Objects.equals(expectedOld.getAppliedCommitId(), replacement.getAppliedCommitId()) + || !Objects.equals(expectedOld.getBaseVersionId(), replacement.getBaseVersionId()) + || !Objects.equals( + expectedOld.getRecordedFromPublishWorkflowId(), + audit.sourceRecordedFromPublishWorkflowId()) + || !Objects.equals(expectedOld.getRecordedAt(), audit.sourceRecordedAt()) + || !Objects.equals( + expectedOld.getLastVerifiedPublishWorkflowId(), + audit.sourceLastVerifiedPublishWorkflowId()) + || !Objects.equals(expectedOld.getLastVerifiedAt(), audit.sourceLastVerifiedAt()) + || !Objects.equals(expectedOld.getContentDigest(), audit.sourceContentDigest()) + || !Objects.equals(expectedOld.getDigestSchemaVersion(), audit.sourceDigestSchemaVersion()) + || expectedOld.getPublishType() != audit.sourcePublishType() + || expectedOld.getParticipantKey() != audit.sourceParticipantKey() + || !Objects.equals(expectedOld.getBaseVersionId(), audit.sourceBaseVersionId()) + || !Integer.valueOf(1).equals(expectedOld.getDigestSchemaVersion()) + || !Objects.equals(expectedOld.getId(), audit.recordedParticipantDigestId()) + || !Objects.equals(expectedOld.getTenantId(), audit.sourceTenantId()) + || !Objects.equals(expectedOld.getScopeValue(), audit.sourceScopeValue()) + || !Objects.equals(expectedOld.getAppliedCommitId(), audit.sourceAppliedCommitId()) + || !Objects.equals(replacement.getTenantId(), audit.observedTenantId()) + || replacement.getPublishType() != audit.observedPublishType() + || replacement.getParticipantKey() != audit.observedParticipantKey() + || !Objects.equals(replacement.getBaseVersionId(), audit.observedBaseVersionId()) + || !Objects.equals(replacement.getScopeValue(), audit.observedScopeValue()) + || !Objects.equals(replacement.getAppliedCommitId(), audit.observedAppliedCommitId()) + || !Objects.equals(replacement.getContentDigest(), audit.observedContentDigest()) + || !Objects.equals( + replacement.getDigestSchemaVersion(), audit.observedDigestSchemaVersion()) + || !Integer.valueOf(2).equals(replacement.getDigestSchemaVersion()) + || audit.observedContentDigest() == null + || audit.observedContentDigest().isBlank() + || !Objects.equals( + replacement.getRecordedFromPublishWorkflowId(), + expectedOld.getRecordedFromPublishWorkflowId()) + || !Objects.equals(replacement.getRecordedAt(), expectedOld.getRecordedAt()) + || !Objects.equals( + replacement.getLastVerifiedPublishWorkflowId(), + expectedOld.getLastVerifiedPublishWorkflowId()) + || !Objects.equals(replacement.getLastVerifiedAt(), expectedOld.getLastVerifiedAt()) + || !EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME.equals(audit.outcome())) { + throw new IllegalArgumentException( + "migration audit and guarded baseline replacement do not describe one operation"); + } + } +} diff --git a/services/game-design-service/src/main/resources/db/migration/V29__entity_digest_baseline_migration.sql b/services/game-design-service/src/main/resources/db/migration/V29__entity_digest_baseline_migration.sql new file mode 100644 index 0000000000..2e9ec10ac1 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V29__entity_digest_baseline_migration.sql @@ -0,0 +1,53 @@ +CREATE TABLE entity_digest_baseline_migration_audit ( + id BIGSERIAL PRIMARY KEY, + operation_id VARCHAR(128) NOT NULL, + recorded_participant_digest_id BIGINT NOT NULL, + source_tenant_id VARCHAR(36) NOT NULL, + source_publish_type VARCHAR(32) NOT NULL, + source_participant_key VARCHAR(64) NOT NULL, + source_base_version_id BIGINT, + source_scope_value VARCHAR(128) NOT NULL, + source_applied_commit_id VARCHAR(128) NOT NULL, + source_content_digest VARCHAR(128) NOT NULL, + source_digest_schema_version INT NOT NULL, + source_recorded_from_publish_workflow_id VARCHAR(1024) NOT NULL, + source_recorded_at TIMESTAMP NOT NULL, + source_last_verified_publish_workflow_id VARCHAR(1024) NOT NULL, + source_last_verified_at TIMESTAMP NOT NULL, + observed_tenant_id VARCHAR(36) NOT NULL, + observed_publish_type VARCHAR(32) NOT NULL, + observed_participant_key VARCHAR(64) NOT NULL, + observed_base_version_id BIGINT, + observed_scope_value VARCHAR(128) NOT NULL, + observed_applied_commit_id VARCHAR(128) NOT NULL, + observed_content_digest VARCHAR(128) NOT NULL, + observed_digest_schema_version INT NOT NULL, + actor_identity VARCHAR(256) NOT NULL, + workload_identity VARCHAR(256) NOT NULL, + outcome VARCHAR(16) NOT NULL, + committed_at TIMESTAMP NOT NULL, + CONSTRAINT uq_entity_digest_baseline_migration_operation UNIQUE (operation_id), + CONSTRAINT uq_entity_digest_baseline_migration_baseline UNIQUE (recorded_participant_digest_id), + CONSTRAINT fk_entity_digest_baseline_migration_baseline + FOREIGN KEY (recorded_participant_digest_id) + REFERENCES publish_recorded_participant_digest(id) + ON DELETE RESTRICT, + CONSTRAINT chk_entity_digest_baseline_migration_source + CHECK ( + source_publish_type = 'FULL_VERSION' + AND source_participant_key = 'ENTITY_MANAGEMENT' + AND source_base_version_id IS NULL + AND source_digest_schema_version = 1 + ), + CONSTRAINT chk_entity_digest_baseline_migration_observed + CHECK ( + observed_publish_type = 'FULL_VERSION' + AND observed_participant_key = 'ENTITY_MANAGEMENT' + AND observed_base_version_id IS NULL + AND observed_digest_schema_version = 2 + AND observed_tenant_id = source_tenant_id + AND observed_scope_value = source_scope_value + ), + CONSTRAINT chk_entity_digest_baseline_migration_outcome + CHECK (outcome = 'COMMITTED') +); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java new file mode 100644 index 0000000000..9b0713727a --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/EntityDigestBaselineMigrationIntegrationTest.java @@ -0,0 +1,441 @@ +package net.firedevops.firemud.gamedesign.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.client.EntityManagementClient; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.repository.EntityDigestBaselineMigrationAuditRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.BaselineSummary; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.ExpectedSource; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.MigrationCommand; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.MigrationDisposition; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.MigrationResult; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationService.ScopeStatus; +import net.firedevops.firemud.gamedesign.service.impl.EntityDigestBaselineMigrationWriteService; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof for Entity v1 baseline enumeration, guarded migration, audit, and readback. */ +@Testcontainers(disabledWithoutDocker = true) +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.NONE, + classes = GameDesignServiceApplication.class, + properties = { + "spring.profiles.active=test", + "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "firemud.grpc.plaintext=true", + "spring.grpc.server.port=0", + "asset.store.endpoint=http://localhost:9000", + "asset.store.bucket=test-bucket", + "asset.store.region=us-east-1", + "asset.store.access-key=test-access-key", + "asset.store.secret-key=test-secret-key" + }) +@Import(NoGrpcServerTestConfiguration.class) +class EntityDigestBaselineMigrationIntegrationTest { + private static final LocalDateTime SOURCE_RECORDED_AT = + LocalDateTime.of(2025, 1, 2, 3, 4, 5, 123_456_000); + private static final LocalDateTime SOURCE_LAST_VERIFIED_AT = + LocalDateTime.of(2025, 2, 3, 4, 5, 6, 234_567_000); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "game_design_service"); + } + + @Autowired private GameRepository gameRepository; + @Autowired private VersionRepository versionRepository; + @Autowired private RecordedParticipantDigestRepository baselineRepository; + @Autowired private EntityDigestBaselineMigrationAuditRepository auditRepository; + @Autowired private EntityDigestBaselineMigrationService migrationService; + @Autowired private EntityDigestBaselineMigrationWriteService writeService; + + @MockitoBean private EntityManagementClient entityManagementClient; + + @BeforeEach + void returnDeterministicEntityV2Evidence() { + when(entityManagementClient.getDraftDesignDigestForVersion(any())) + .thenAnswer( + invocation -> { + PublicationDigestRequestBinding binding = invocation.getArgument(0); + long versionId = Long.parseLong(binding.versionId()); + return new PublishParticipantDigestDto( + PublishParticipantKey.ENTITY_MANAGEMENT.name(), + binding.versionId(), + null, + "version:" + versionId, + v2Digest(versionId), + 2, + null, + null); + }); + } + + @Test + void insertedBaselineReturnsGeneratedIdAndExactDatabaseRow() { + createGame("9601"); + Version version = createVersion("9601", 1); + + RecordedParticipantDigest inserted = seedEntityBaseline("9601", version, 1); + + assertThat(inserted.getId()).isPositive(); + assertThat(baselineRepository.findById(inserted.getId()).orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(inserted); + assertThat(inserted.getTenantId()).isEqualTo("9601"); + assertThat(inserted.getScopeValue()).isEqualTo(Long.toString(version.getId())); + assertThat(inserted.getContentDigest()).isEqualTo("entity-v1-" + version.getId()); + assertThat(inserted.getDigestSchemaVersion()).isEqualTo(1); + assertThat(inserted.getRecordedAt()).isEqualTo(SOURCE_RECORDED_AT); + assertThat(inserted.getLastVerifiedAt()).isEqualTo(SOURCE_LAST_VERIFIED_AT); + } + + @Test + void enumeratesMixedRowsMigratesOnlyExactTenantVersionAndReadsBackAuditAndBaseline() { + createGame("9201"); + createGame("9202"); + Version targetVersion = createVersion("9201", 1); + Version siblingVersion = createVersion("9201", 2); + Version existingV2Version = createVersion("9201", 3); + Version noDataVersion = createVersion("9201", 4); + Version otherTenantVersion = createVersion("9202", 1); + + RecordedParticipantDigest target = seedEntityBaseline("9201", targetVersion, 1); + RecordedParticipantDigest sibling = seedEntityBaseline("9201", siblingVersion, 1); + RecordedParticipantDigest existingV2 = seedEntityBaseline("9201", existingV2Version, 2); + RecordedParticipantDigest otherTenant = seedEntityBaseline("9202", otherTenantVersion, 1); + RecordedParticipantDigest otherParticipant = + seedBaseline( + "9201", + targetVersion, + PublishParticipantKey.WORLD_MANAGEMENT, + 2, + "world-digest-" + targetVersion.getId()); + + EntityDigestBaselineMigrationService.EntityV1Batch batch = + migrationService.enumerateEntityV1Batch(target.getId() - 1, 50); + assertThat(batch.baselines()) + .extracting(BaselineSummary::baselineId) + .containsExactlyInAnyOrder(target.getId(), sibling.getId(), otherTenant.getId()); + assertThat(migrationService.preflightScope("9201", targetVersion.getId()).status()) + .isEqualTo(ScopeStatus.V1_REQUIRES_MIGRATION); + assertThat(migrationService.preflightScope("9201", noDataVersion.getId()).status()) + .isEqualTo(ScopeStatus.NO_RECORDED_BASELINE); + assertThat( + baselineRepository.findEntityFullVersionBaselinesByScope( + "9202", Long.toString(otherTenantVersion.getId()))) + .extracting(RecordedParticipantDigest::getId) + .containsExactly(otherTenant.getId()); + + MigrationCommand command = command("mixed-scope-operation", "9201", target); + MigrationResult result = migrationService.migrate(command); + + assertThat(result.disposition()).isEqualTo(MigrationDisposition.APPLIED); + assertThat(result.appliedCommitId()).isEqualTo(target.getAppliedCommitId()); + assertThat(result.digestSchemaVersion()).isEqualTo(2); + RecordedParticipantDigest migrated = baselineRepository.findById(target.getId()).orElseThrow(); + EntityDigestBaselineMigrationAudit audit = + auditRepository.findByOperationId(command.operationId()).orElseThrow(); + RecordedParticipantDigest expectedMigrated = + replacement(target, v2Digest(targetVersion.getId())); + assertThat(migrated).usingRecursiveComparison().isEqualTo(expectedMigrated); + EntityDigestBaselineMigrationAudit expectedAudit = + audit( + target, + migrated, + command.operationId(), + command.actorIdentity(), + command.workloadIdentity(), + audit.committedAt()); + assertThat(audit).usingRecursiveComparison().ignoringFields("id").isEqualTo(expectedAudit); + assertThat(migrated.getTenantId()).isEqualTo("9201"); + assertThat(migrated.getScopeValue()).isEqualTo(Long.toString(targetVersion.getId())); + assertThat(migrated.getAppliedCommitId()).isEqualTo("version:" + targetVersion.getId()); + assertThat(migrated.getContentDigest()).isEqualTo(v2Digest(targetVersion.getId())); + assertThat(migrated.getDigestSchemaVersion()).isEqualTo(2); + assertThat(migrated.getRecordedFromPublishWorkflowId()) + .isEqualTo(target.getRecordedFromPublishWorkflowId()); + assertThat(migrated.getLastVerifiedPublishWorkflowId()) + .isEqualTo(target.getLastVerifiedPublishWorkflowId()); + assertThat(migrated.getRecordedAt()).isEqualTo(target.getRecordedAt()); + assertThat(migrated.getLastVerifiedAt()).isEqualTo(target.getLastVerifiedAt()); + assertThat(audit.id()).isEqualTo(result.auditId()); + assertThat(audit.recordedParticipantDigestId()).isEqualTo(target.getId()); + assertThat(audit.sourceContentDigest()).isEqualTo(target.getContentDigest()); + assertThat(audit.sourceDigestSchemaVersion()).isEqualTo(1); + assertThat(audit.sourceRecordedFromPublishWorkflowId()) + .isEqualTo(target.getRecordedFromPublishWorkflowId()); + assertThat(audit.sourceRecordedAt()).isEqualTo(target.getRecordedAt()); + assertThat(audit.sourceLastVerifiedPublishWorkflowId()) + .isEqualTo(target.getLastVerifiedPublishWorkflowId()); + assertThat(audit.sourceLastVerifiedAt()).isEqualTo(target.getLastVerifiedAt()); + assertThat(audit.observedTenantId()).isEqualTo("9201"); + assertThat(audit.observedScopeValue()).isEqualTo(Long.toString(targetVersion.getId())); + assertThat(audit.observedContentDigest()).isEqualTo(v2Digest(targetVersion.getId())); + assertThat(audit.observedDigestSchemaVersion()).isEqualTo(2); + assertThat(audit.actorIdentity()).isEqualTo(command.actorIdentity()); + assertThat(audit.workloadIdentity()).isEqualTo(command.workloadIdentity()); + assertThat(audit.outcome()).isEqualTo(EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME); + + assertBaselineUnchanged(sibling); + assertBaselineUnchanged(otherTenant); + assertBaselineUnchanged(existingV2); + assertBaselineUnchanged(otherParticipant); + } + + @Test + void exactRetryReadsCommittedEvidenceWithoutCallingEntityAgain() { + createGame("9301"); + Version version = createVersion("9301", 1); + RecordedParticipantDigest source = seedEntityBaseline("9301", version, 1); + MigrationCommand command = command("retry-operation", "9301", source); + + MigrationResult first = migrationService.migrate(command); + MigrationResult retry = migrationService.migrate(command); + + assertThat(first.disposition()).isEqualTo(MigrationDisposition.APPLIED); + assertThat(retry.disposition()).isEqualTo(MigrationDisposition.EXACT_RETRY); + assertThat(retry.auditId()).isEqualTo(first.auditId()); + assertThat(retry.baselineId()).isEqualTo(first.baselineId()); + assertThat(retry.contentDigest()).isEqualTo(first.contentDigest()); + assertThat(retry.digestSchemaVersion()).isEqualTo(2); + verify(entityManagementClient, times(1)).getDraftDesignDigestForVersion(any()); + assertThat(auditRepository.findByOperationId(command.operationId())).isPresent(); + assertThat(baselineRepository.findById(source.getId()).orElseThrow().getContentDigest()) + .isEqualTo(v2Digest(version.getId())); + } + + @Test + void compareAndSwapRejectsAChangedV1SourceRow() { + createGame("9401"); + Version version = createVersion("9401", 1); + RecordedParticipantDigest source = seedEntityBaseline("9401", version, 1); + RecordedParticipantDigest expectedOld = + baselineRepository.findById(source.getId()).orElseThrow(); + RecordedParticipantDigest changed = baselineRepository.findById(source.getId()).orElseThrow(); + changed.setContentDigest("changed-after-preflight"); + baselineRepository.save(changed); + + RecordedParticipantDigest replacement = replacement(expectedOld, "v2-new"); + + assertThat( + baselineRepository.migrateEntityFullVersionBaselineIfUnchanged( + expectedOld, replacement)) + .isZero(); + RecordedParticipantDigest readback = baselineRepository.findById(source.getId()).orElseThrow(); + assertThat(readback.getDigestSchemaVersion()).isEqualTo(1); + assertThat(readback.getContentDigest()).isEqualTo("changed-after-preflight"); + assertThat(auditRepository.findByOperationId("cas-test-operation")).isEmpty(); + } + + @Test + void auditInsertFailureRollsBackTheGuardedBaselineReplacement() { + createGame("9501"); + Version firstVersion = createVersion("9501", 1); + Version secondVersion = createVersion("9501", 2); + RecordedParticipantDigest firstSource = seedEntityBaseline("9501", firstVersion, 1); + RecordedParticipantDigest secondSource = seedEntityBaseline("9501", secondVersion, 1); + + MigrationCommand firstCommand = command("duplicate-operation-id", "9501", firstSource); + MigrationResult firstResult = migrationService.migrate(firstCommand); + RecordedParticipantDigest expectedOld = + baselineRepository.findById(secondSource.getId()).orElseThrow(); + LocalDateTime migrationTime = LocalDateTime.now().truncatedTo(ChronoUnit.MICROS); + RecordedParticipantDigest replacement = + replacement(expectedOld, v2Digest(secondVersion.getId())); + replacement.setRecordedAt(migrationTime); + replacement.setLastVerifiedAt(migrationTime); + EntityDigestBaselineMigrationAudit duplicateAudit = + audit( + expectedOld, + replacement, + firstCommand.operationId(), + firstCommand.actorIdentity(), + firstCommand.workloadIdentity(), + migrationTime); + + assertThatThrownBy(() -> writeService.commit(expectedOld, replacement, duplicateAudit)) + .isInstanceOf(RuntimeException.class); + + RecordedParticipantDigest readback = + baselineRepository.findById(secondSource.getId()).orElseThrow(); + assertThat(readback).usingRecursiveComparison().isEqualTo(secondSource); + assertThat(auditRepository.findByOperationId(firstCommand.operationId()).orElseThrow().id()) + .isEqualTo(firstResult.auditId()); + } + + private void createGame(String tenantId) { + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("entity-baseline-migration-" + tenantId); + gameRepository.save(game); + } + + private Version createVersion(String tenantId, int versionNumber) { + Version version = new Version(); + version.setTenantId(tenantId); + version.setVersionNumber(versionNumber); + version.setNotes("Entity baseline migration integration fixture"); + return versionRepository.save(version); + } + + private RecordedParticipantDigest seedEntityBaseline( + String tenantId, Version version, int digestSchemaVersion) { + return seedBaseline( + tenantId, + version, + PublishParticipantKey.ENTITY_MANAGEMENT, + digestSchemaVersion, + "entity-v" + digestSchemaVersion + "-" + version.getId()); + } + + private RecordedParticipantDigest seedBaseline( + String tenantId, + Version version, + PublishParticipantKey participantKey, + int digestSchemaVersion, + String contentDigest) { + RecordedParticipantDigest baseline = new RecordedParticipantDigest(); + baseline.setTenantId(tenantId); + baseline.setPublishType(PublishType.FULL_VERSION); + baseline.setParticipantKey(participantKey); + baseline.setScopeValue(Long.toString(version.getId())); + baseline.setBaseVersionId(null); + baseline.setAppliedCommitId("version:" + version.getId()); + baseline.setContentDigest(contentDigest); + baseline.setDigestSchemaVersion(digestSchemaVersion); + baseline.setRecordedFromPublishWorkflowId("initial-publish-" + version.getId()); + baseline.setRecordedAt(SOURCE_RECORDED_AT); + baseline.setLastVerifiedPublishWorkflowId("last-verified-" + version.getId()); + baseline.setLastVerifiedAt(SOURCE_LAST_VERIFIED_AT); + return baselineRepository.save(baseline); + } + + private MigrationCommand command( + String operationId, String tenantId, RecordedParticipantDigest source) { + return new MigrationCommand( + operationId, + source.getId(), + tenantId, + Long.parseLong(source.getScopeValue()), + expectedSource(source), + "operator:test-actor", + "spiffe://firemud/ns/dev/sa/game-design-baseline-migrator"); + } + + private ExpectedSource expectedSource(RecordedParticipantDigest source) { + return new ExpectedSource( + source.getId(), + source.getTenantId(), + source.getPublishType(), + source.getParticipantKey(), + source.getBaseVersionId(), + source.getScopeValue(), + source.getAppliedCommitId(), + source.getContentDigest(), + source.getDigestSchemaVersion(), + source.getRecordedFromPublishWorkflowId(), + source.getRecordedAt(), + source.getLastVerifiedPublishWorkflowId(), + source.getLastVerifiedAt()); + } + + private RecordedParticipantDigest replacement( + RecordedParticipantDigest source, String contentDigest) { + RecordedParticipantDigest replacement = new RecordedParticipantDigest(); + replacement.setId(source.getId()); + replacement.setTenantId(source.getTenantId()); + replacement.setPublishType(source.getPublishType()); + replacement.setParticipantKey(source.getParticipantKey()); + replacement.setBaseVersionId(null); + replacement.setScopeValue(source.getScopeValue()); + replacement.setAppliedCommitId(source.getAppliedCommitId()); + replacement.setContentDigest(contentDigest); + replacement.setDigestSchemaVersion(2); + replacement.setRecordedFromPublishWorkflowId(source.getRecordedFromPublishWorkflowId()); + replacement.setRecordedAt(source.getRecordedAt()); + replacement.setLastVerifiedPublishWorkflowId(source.getLastVerifiedPublishWorkflowId()); + replacement.setLastVerifiedAt(source.getLastVerifiedAt()); + return replacement; + } + + private EntityDigestBaselineMigrationAudit audit( + RecordedParticipantDigest source, + RecordedParticipantDigest target, + String operationId, + String actorIdentity, + String workloadIdentity, + LocalDateTime committedAt) { + return new EntityDigestBaselineMigrationAudit( + null, + operationId, + source.getId(), + source.getTenantId(), + source.getPublishType(), + source.getParticipantKey(), + source.getBaseVersionId(), + source.getScopeValue(), + source.getAppliedCommitId(), + source.getContentDigest(), + source.getDigestSchemaVersion(), + source.getRecordedFromPublishWorkflowId(), + source.getRecordedAt(), + source.getLastVerifiedPublishWorkflowId(), + source.getLastVerifiedAt(), + target.getTenantId(), + target.getPublishType(), + target.getParticipantKey(), + target.getBaseVersionId(), + target.getScopeValue(), + target.getAppliedCommitId(), + target.getContentDigest(), + target.getDigestSchemaVersion(), + actorIdentity, + workloadIdentity, + EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME, + committedAt); + } + + private void assertBaselineUnchanged(RecordedParticipantDigest expected) { + RecordedParticipantDigest actual = baselineRepository.findById(expected.getId()).orElseThrow(); + assertThat(actual).usingRecursiveComparison().isEqualTo(expected); + } + + private String v2Digest(long versionId) { + return "entity-v2-observed-" + versionId; + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java new file mode 100644 index 0000000000..b20e14109d --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/EntityDigestBaselineMigrationJobRunnerTest.java @@ -0,0 +1,60 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; + +class EntityDigestBaselineMigrationJobRunnerTest { + private static final GrpcPeerIdentity MIGRATOR = + new GrpcPeerIdentity( + "spiffe://firemud/ns/dev/sa/game-design-baseline-migrator", + "dev", + "game-design-baseline-migrator"); + + @Test + void acceptsOnlyExactDedicatedIdentityAndTargetEnvironment() { + assertThatCode( + () -> + EntityDigestBaselineMigrationJobRunner.requireJobAuthority( + "dev", "dev", "game-design-baseline-migrator", MIGRATOR)) + .doesNotThrowAnyException(); + } + + @Test + void rejectsWrongTargetServiceAccountAndCertificateIdentity() { + assertThatThrownBy( + () -> + EntityDigestBaselineMigrationJobRunner.requireJobAuthority( + "dev", "pr-12", "game-design-baseline-migrator", MIGRATOR)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + EntityDigestBaselineMigrationJobRunner.requireJobAuthority( + "dev", "dev", "firemud-app", MIGRATOR)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + EntityDigestBaselineMigrationJobRunner.requireJobAuthority( + "dev", + "dev", + "game-design-baseline-migrator", + new GrpcPeerIdentity( + "spiffe://firemud/ns/dev/sa/game-design-service", + "dev", + "game-design-service"))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + EntityDigestBaselineMigrationJobRunner.requireJobAuthority( + "dev", + "dev", + "game-design-baseline-migrator", + new GrpcPeerIdentity( + "spiffe://firemud/ns/pr-12/sa/game-design-baseline-migrator", + "pr-12", + "game-design-baseline-migrator"))) + .isInstanceOf(IllegalStateException.class); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java new file mode 100644 index 0000000000..1246b2adc4 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationServiceTest.java @@ -0,0 +1,548 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.gamedesign.client.EntityManagementClient; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; +import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.EntityDigestBaselineMigrationAuditRepository; +import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class EntityDigestBaselineMigrationServiceTest { + private static final long BASELINE_ID = 91L; + private static final long VERSION_ID = 42L; + private static final long AUDIT_ID = 701L; + private static final String OPERATION_ID = "migration-op-42"; + private static final String TENANT_ID = "tenant-7"; + private static final LocalDateTime SOURCE_RECORDED_AT = + LocalDateTime.parse("2026-09-20T12:30:00.123456"); + private static final LocalDateTime SOURCE_VERIFIED_AT = + LocalDateTime.parse("2026-09-21T12:30:00.654321"); + + @Mock private RecordedParticipantDigestRepository baselineRepository; + @Mock private EntityDigestBaselineMigrationAuditRepository auditRepository; + @Mock private VersionRepository versionRepository; + @Mock private EntityManagementClient entityManagementClient; + + private RecordedParticipantDigest source; + private EntityDigestBaselineMigrationService.ExpectedSource expectedSource; + private EntityDigestBaselineMigrationService.MigrationCommand command; + + @BeforeEach + void setUp() { + source = sourceBaseline(); + expectedSource = expectedSource(source); + command = command(expectedSource); + } + + @Test + void preflightDistinguishesNoBaselineV2AndMissingVersion() { + EntityDigestBaselineMigrationService service = serviceWithMockWriter(); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(), List.of(v2Baseline())); + + assertEquals( + EntityDigestBaselineMigrationService.ScopeStatus.NO_RECORDED_BASELINE, + service.preflightScope(TENANT_ID, VERSION_ID).status()); + assertEquals( + EntityDigestBaselineMigrationService.ScopeStatus.V2_ALREADY_RECORDED, + service.preflightScope(TENANT_ID, VERSION_ID).status()); + + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)).thenReturn(Optional.empty()); + EntityDigestBaselineMigrationService.MigrationRejectedException missingVersion = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> service.preflightScope(TENANT_ID, VERSION_ID)); + assertEquals("VERSION_MISSING", missingVersion.failureCode()); + } + + @Test + void preflightClassifiesRetainedEntityV1Row() { + EntityDigestBaselineMigrationService service = serviceWithMockWriter(); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(source)); + + EntityDigestBaselineMigrationService.ScopePreflight result = + service.preflightScope(TENANT_ID, VERSION_ID); + + assertEquals( + EntityDigestBaselineMigrationService.ScopeStatus.V1_REQUIRES_MIGRATION, result.status()); + assertEquals(BASELINE_ID, result.baselines().get(0).baselineId()); + assertEquals("version:42", result.baselines().get(0).appliedCommitId()); + } + + @Test + void preflightReportsAmbiguousScopeInsteadOfSelectingARow() { + EntityDigestBaselineMigrationService service = serviceWithMockWriter(); + RecordedParticipantDigest duplicate = sourceBaseline(); + duplicate.setId(BASELINE_ID + 1); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(source, duplicate)); + + EntityDigestBaselineMigrationService.ScopePreflight result = + service.preflightScope(TENANT_ID, VERSION_ID); + + assertEquals( + EntityDigestBaselineMigrationService.ScopeStatus.AMBIGUOUS_BASELINE, result.status()); + assertEquals(2, result.baselines().size()); + } + + @Test + void enumerationReturnsBoundedCursorPageWithExactScopeIdentities() { + EntityDigestBaselineMigrationService service = serviceWithMockWriter(); + when(baselineRepository.findEntityV1FullVersionBatchAfterId(10L, 25)) + .thenReturn(List.of(source)); + + EntityDigestBaselineMigrationService.EntityV1Batch page = + service.enumerateEntityV1Batch(10L, 25); + + assertEquals(10L, page.scannedAfterBaselineId()); + assertEquals(25, page.limit()); + assertEquals(BASELINE_ID, page.nextAfterBaselineId()); + assertEquals(TENANT_ID, page.baselines().get(0).tenantId()); + assertEquals(VERSION_ID, page.baselines().get(0).versionId()); + assertFalse(page.isEmptyAtCursor()); + } + + @Test + void migrationCommitsAndProvesExactV2BaselineAndAuditReadback() { + AtomicReference persistedBaseline = new AtomicReference<>(source); + AtomicReference persistedAudit = new AtomicReference<>(); + EntityDigestBaselineMigrationWriteService writer = + new EntityDigestBaselineMigrationWriteService(baselineRepository, auditRepository); + EntityDigestBaselineMigrationService service = + new EntityDigestBaselineMigrationService( + baselineRepository, auditRepository, versionRepository, entityManagementClient, writer); + stubInitialMigrationReads(persistedBaseline, persistedAudit); + when(entityManagementClient.getDraftDesignDigestForVersion(any())) + .thenReturn(v2Digest("v2-content", "version:42")); + when(baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(any(), any())) + .thenAnswer( + invocation -> { + RecordedParticipantDigest expected = invocation.getArgument(0); + if (!sameSource(persistedBaseline.get(), expected)) { + return 0; + } + persistedBaseline.set(invocation.getArgument(1)); + return 1; + }); + when(auditRepository.insert(any())) + .thenAnswer( + invocation -> { + EntityDigestBaselineMigrationAudit inserted = invocation.getArgument(0); + EntityDigestBaselineMigrationAudit stored = withId(inserted, AUDIT_ID); + persistedAudit.set(stored); + return stored; + }); + + EntityDigestBaselineMigrationService.MigrationResult result = service.migrate(command); + + assertEquals( + EntityDigestBaselineMigrationService.MigrationDisposition.APPLIED, result.disposition()); + assertEquals(AUDIT_ID, result.auditId()); + assertEquals(BASELINE_ID, result.baselineId()); + assertEquals("version:42", result.appliedCommitId()); + assertEquals("v2-content", result.contentDigest()); + assertEquals(2, result.digestSchemaVersion()); + assertEquals( + source.getRecordedFromPublishWorkflowId(), + persistedBaseline.get().getRecordedFromPublishWorkflowId()); + assertEquals(source.getRecordedAt(), persistedBaseline.get().getRecordedAt()); + assertEquals( + source.getLastVerifiedPublishWorkflowId(), + persistedBaseline.get().getLastVerifiedPublishWorkflowId()); + assertEquals(source.getLastVerifiedAt(), persistedBaseline.get().getLastVerifiedAt()); + assertEquals(source.getContentDigest(), persistedAudit.get().sourceContentDigest()); + assertEquals("v2-content", persistedAudit.get().observedContentDigest()); + } + + @Test + void exactRetryReturnsOnlyAfterBaselineAndAuditReadbackWithoutRecomputing() { + RecordedParticipantDigest migrated = migratedBaseline("v2-content", "version:42"); + EntityDigestBaselineMigrationAudit audit = audit(source, migrated, AUDIT_ID, auditTime()); + when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.of(audit)); + when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(migrated)); + + EntityDigestBaselineMigrationService.MigrationResult result = + serviceWithMockWriter().migrate(command); + + assertEquals( + EntityDigestBaselineMigrationService.MigrationDisposition.EXACT_RETRY, + result.disposition()); + assertEquals("v2-content", result.contentDigest()); + verify(entityManagementClient, never()).getDraftDesignDigestForVersion(any()); + verify(versionRepository, never()).findByTenantIdAndId(any(), any()); + } + + @Test + void operationIdReuseWithDifferentSourceIsRejected() { + EntityDigestBaselineMigrationAudit conflicting = + audit(source, migratedBaseline("v2-content", "version:42"), AUDIT_ID, auditTime()); + conflicting = withSourceContentDigest(conflicting, "different-v1-digest"); + when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.of(conflicting)); + + EntityDigestBaselineMigrationService.MigrationRejectedException rejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> serviceWithMockWriter().migrate(command)); + + assertEquals("OPERATION_ID_CONFLICT", rejected.failureCode()); + verify(baselineRepository, never()).findById(BASELINE_ID); + verify(entityManagementClient, never()).getDraftDesignDigestForVersion(any()); + } + + @Test + void changedOldTupleIsRejectedBeforeEntityRecomputation() { + RecordedParticipantDigest changed = sourceBaseline(); + changed.setLastVerifiedAt(SOURCE_VERIFIED_AT.plusSeconds(1)); + when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.empty()); + when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(changed)); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(changed)); + + EntityDigestBaselineMigrationService.MigrationRejectedException rejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> serviceWithMockWriter().migrate(command)); + + assertEquals("SOURCE_BASELINE_CHANGED", rejected.failureCode()); + verify(entityManagementClient, never()).getDraftDesignDigestForVersion(any()); + } + + @Test + void wrongTenantBaselineIsRejectedBeforeScopeOrEntityRead() { + RecordedParticipantDigest wrongTenant = sourceBaseline(); + wrongTenant.setTenantId("tenant-other"); + when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.empty()); + when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(wrongTenant)); + + EntityDigestBaselineMigrationService.MigrationRejectedException rejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> serviceWithMockWriter().migrate(command)); + + assertEquals("BASELINE_TENANT_MISMATCH", rejected.failureCode()); + verify(entityManagementClient, never()).getDraftDesignDigestForVersion(any()); + } + + @Test + void schemaOneSourceCannotBeSilentlyReplacedWhenEntityCommitIdentityChanges() { + when(auditRepository.findByOperationId(OPERATION_ID)).thenReturn(Optional.empty()); + when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(source)); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(source)); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + when(entityManagementClient.getDraftDesignDigestForVersion(any())) + .thenReturn(v2Digest("v2-content", "version:43")); + + EntityDigestBaselineMigrationService.MigrationRejectedException rejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> serviceWithMockWriter().migrate(command)); + + assertEquals("ENTITY_APPLIED_COMMIT_MISMATCH", rejected.failureCode()); + } + + @Test + void uncertainWriterOutcomeSucceedsOnlyWhenExactCommittedReadbackIsFound() { + AtomicReference persistedBaseline = new AtomicReference<>(source); + AtomicReference persistedAudit = new AtomicReference<>(); + EntityDigestBaselineMigrationWriteService writer = + org.mockito.Mockito.mock(EntityDigestBaselineMigrationWriteService.class); + org.mockito.Mockito.doAnswer( + invocation -> { + persistedBaseline.set(invocation.getArgument(1)); + persistedAudit.set(withId(invocation.getArgument(2), AUDIT_ID)); + throw new IllegalStateException("connection lost after commit"); + }) + .when(writer) + .commit(any(), any(), any()); + when(auditRepository.findByOperationId(OPERATION_ID)) + .thenAnswer(invocation -> Optional.ofNullable(persistedAudit.get())); + when(baselineRepository.findById(BASELINE_ID)) + .thenAnswer(invocation -> Optional.ofNullable(persistedBaseline.get())); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(source)); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + when(entityManagementClient.getDraftDesignDigestForVersion(any())) + .thenReturn(v2Digest("v2-content", "version:42")); + + EntityDigestBaselineMigrationService.MigrationResult result = service(writer).migrate(command); + + assertEquals( + EntityDigestBaselineMigrationService.MigrationDisposition.RECOVERED_AFTER_WRITE_ERROR, + result.disposition()); + assertEquals(AUDIT_ID, result.auditId()); + } + + @Test + void uncertainWriterOutcomeFailsWhenReadbackCannotProveBothRows() { + EntityDigestBaselineMigrationWriteService writer = + org.mockito.Mockito.mock(EntityDigestBaselineMigrationWriteService.class); + doThrow(new IllegalStateException("commit acknowledgement lost")) + .when(writer) + .commit(any(), any(), any()); + when(auditRepository.findByOperationId(OPERATION_ID)) + .thenReturn(Optional.empty(), Optional.empty()); + when(baselineRepository.findById(BASELINE_ID)).thenReturn(Optional.of(source)); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenReturn(List.of(source)); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + when(entityManagementClient.getDraftDesignDigestForVersion(any())) + .thenReturn(v2Digest("v2-content", "version:42")); + + EntityDigestBaselineMigrationService.MigrationRejectedException rejected = + assertThrows( + EntityDigestBaselineMigrationService.MigrationRejectedException.class, + () -> service(writer).migrate(command)); + + assertEquals("WRITE_OUTCOME_UNPROVEN", rejected.failureCode()); + assertTrue(rejected.getCause().getSuppressed().length > 0); + } + + private EntityDigestBaselineMigrationService serviceWithMockWriter() { + return service(org.mockito.Mockito.mock(EntityDigestBaselineMigrationWriteService.class)); + } + + private EntityDigestBaselineMigrationService service( + EntityDigestBaselineMigrationWriteService writer) { + return new EntityDigestBaselineMigrationService( + baselineRepository, auditRepository, versionRepository, entityManagementClient, writer); + } + + private void stubInitialMigrationReads( + AtomicReference persistedBaseline, + AtomicReference persistedAudit) { + when(auditRepository.findByOperationId(OPERATION_ID)) + .thenAnswer(invocation -> Optional.ofNullable(persistedAudit.get())); + when(baselineRepository.findById(BASELINE_ID)) + .thenAnswer(invocation -> Optional.ofNullable(persistedBaseline.get())); + when(baselineRepository.findEntityFullVersionBaselinesByScope(TENANT_ID, "42")) + .thenAnswer(invocation -> List.of(persistedBaseline.get())); + when(versionRepository.findByTenantIdAndId(TENANT_ID, VERSION_ID)) + .thenReturn(Optional.of(version())); + } + + private boolean sameSource( + RecordedParticipantDigest current, RecordedParticipantDigest expected) { + return current != null + && current.getId().equals(expected.getId()) + && current.getAppliedCommitId().equals(expected.getAppliedCommitId()) + && current.getContentDigest().equals(expected.getContentDigest()) + && current.getDigestSchemaVersion().equals(expected.getDigestSchemaVersion()) + && current.getLastVerifiedAt().equals(expected.getLastVerifiedAt()); + } + + private RecordedParticipantDigest sourceBaseline() { + RecordedParticipantDigest baseline = new RecordedParticipantDigest(); + baseline.setId(BASELINE_ID); + baseline.setTenantId(TENANT_ID); + baseline.setPublishType(PublishType.FULL_VERSION); + baseline.setParticipantKey(PublishParticipantKey.ENTITY_MANAGEMENT); + baseline.setScopeValue(Long.toString(VERSION_ID)); + baseline.setBaseVersionId(null); + baseline.setAppliedCommitId("version:42"); + baseline.setContentDigest("v1-content"); + baseline.setDigestSchemaVersion(1); + baseline.setRecordedFromPublishWorkflowId("publish:tenant-7:old-request"); + baseline.setRecordedAt(SOURCE_RECORDED_AT); + baseline.setLastVerifiedPublishWorkflowId("publish:tenant-7:old-verification"); + baseline.setLastVerifiedAt(SOURCE_VERIFIED_AT); + return baseline; + } + + private EntityDigestBaselineMigrationService.ExpectedSource expectedSource( + RecordedParticipantDigest baseline) { + return new EntityDigestBaselineMigrationService.ExpectedSource( + baseline.getId(), + baseline.getTenantId(), + baseline.getPublishType(), + baseline.getParticipantKey(), + baseline.getBaseVersionId(), + baseline.getScopeValue(), + baseline.getAppliedCommitId(), + baseline.getContentDigest(), + baseline.getDigestSchemaVersion(), + baseline.getRecordedFromPublishWorkflowId(), + baseline.getRecordedAt(), + baseline.getLastVerifiedPublishWorkflowId(), + baseline.getLastVerifiedAt()); + } + + private EntityDigestBaselineMigrationService.MigrationCommand command( + EntityDigestBaselineMigrationService.ExpectedSource expected) { + return new EntityDigestBaselineMigrationService.MigrationCommand( + OPERATION_ID, + BASELINE_ID, + TENANT_ID, + VERSION_ID, + expected, + "operator:reviewer-1", + "job:entity-baseline"); + } + + private Version version() { + Version version = new Version(); + version.setId(VERSION_ID); + version.setTenantId(TENANT_ID); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setScriptOnly(false); + return version; + } + + private RecordedParticipantDigest v2Baseline() { + RecordedParticipantDigest baseline = sourceBaseline(); + baseline.setDigestSchemaVersion(2); + baseline.setContentDigest("already-v2"); + return baseline; + } + + private PublishParticipantDigestDto v2Digest(String digest, String appliedCommitId) { + return new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", "42", null, appliedCommitId, digest, 2, null, null); + } + + private RecordedParticipantDigest migratedBaseline(String digest, String appliedCommitId) { + RecordedParticipantDigest baseline = sourceBaseline(); + baseline.setAppliedCommitId(appliedCommitId); + baseline.setContentDigest(digest); + baseline.setDigestSchemaVersion(2); + return baseline; + } + + private EntityDigestBaselineMigrationAudit audit( + RecordedParticipantDigest oldBaseline, + RecordedParticipantDigest target, + Long auditId, + LocalDateTime committedAt) { + return new EntityDigestBaselineMigrationAudit( + auditId, + OPERATION_ID, + BASELINE_ID, + oldBaseline.getTenantId(), + oldBaseline.getPublishType(), + oldBaseline.getParticipantKey(), + oldBaseline.getBaseVersionId(), + oldBaseline.getScopeValue(), + oldBaseline.getAppliedCommitId(), + oldBaseline.getContentDigest(), + oldBaseline.getDigestSchemaVersion(), + oldBaseline.getRecordedFromPublishWorkflowId(), + oldBaseline.getRecordedAt(), + oldBaseline.getLastVerifiedPublishWorkflowId(), + oldBaseline.getLastVerifiedAt(), + target.getTenantId(), + target.getPublishType(), + target.getParticipantKey(), + target.getBaseVersionId(), + target.getScopeValue(), + target.getAppliedCommitId(), + target.getContentDigest(), + target.getDigestSchemaVersion(), + "operator:reviewer-1", + "job:entity-baseline", + EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME, + committedAt); + } + + private EntityDigestBaselineMigrationAudit withId( + EntityDigestBaselineMigrationAudit audit, Long id) { + return new EntityDigestBaselineMigrationAudit( + id, + audit.operationId(), + audit.recordedParticipantDigestId(), + audit.sourceTenantId(), + audit.sourcePublishType(), + audit.sourceParticipantKey(), + audit.sourceBaseVersionId(), + audit.sourceScopeValue(), + audit.sourceAppliedCommitId(), + audit.sourceContentDigest(), + audit.sourceDigestSchemaVersion(), + audit.sourceRecordedFromPublishWorkflowId(), + audit.sourceRecordedAt(), + audit.sourceLastVerifiedPublishWorkflowId(), + audit.sourceLastVerifiedAt(), + audit.observedTenantId(), + audit.observedPublishType(), + audit.observedParticipantKey(), + audit.observedBaseVersionId(), + audit.observedScopeValue(), + audit.observedAppliedCommitId(), + audit.observedContentDigest(), + audit.observedDigestSchemaVersion(), + audit.actorIdentity(), + audit.workloadIdentity(), + audit.outcome(), + audit.committedAt()); + } + + private EntityDigestBaselineMigrationAudit withSourceContentDigest( + EntityDigestBaselineMigrationAudit audit, String contentDigest) { + return new EntityDigestBaselineMigrationAudit( + audit.id(), + audit.operationId(), + audit.recordedParticipantDigestId(), + audit.sourceTenantId(), + audit.sourcePublishType(), + audit.sourceParticipantKey(), + audit.sourceBaseVersionId(), + audit.sourceScopeValue(), + audit.sourceAppliedCommitId(), + contentDigest, + audit.sourceDigestSchemaVersion(), + audit.sourceRecordedFromPublishWorkflowId(), + audit.sourceRecordedAt(), + audit.sourceLastVerifiedPublishWorkflowId(), + audit.sourceLastVerifiedAt(), + audit.observedTenantId(), + audit.observedPublishType(), + audit.observedParticipantKey(), + audit.observedBaseVersionId(), + audit.observedScopeValue(), + audit.observedAppliedCommitId(), + audit.observedContentDigest(), + audit.observedDigestSchemaVersion(), + audit.actorIdentity(), + audit.workloadIdentity(), + audit.outcome(), + audit.committedAt()); + } + + private LocalDateTime auditTime() { + return LocalDateTime.parse("2026-09-26T01:02:03.123456"); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java new file mode 100644 index 0000000000..046d2e1396 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/EntityDigestBaselineMigrationWriteServiceTest.java @@ -0,0 +1,121 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.LocalDateTime; +import net.firedevops.firemud.gamedesign.entity.EntityDigestBaselineMigrationAudit; +import net.firedevops.firemud.gamedesign.entity.RecordedParticipantDigest; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.repository.EntityDigestBaselineMigrationAuditRepository; +import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class EntityDigestBaselineMigrationWriteServiceTest { + @Mock private RecordedParticipantDigestRepository baselineRepository; + @Mock private EntityDigestBaselineMigrationAuditRepository auditRepository; + + private EntityDigestBaselineMigrationWriteService service; + private RecordedParticipantDigest source; + private RecordedParticipantDigest replacement; + private EntityDigestBaselineMigrationAudit audit; + + @BeforeEach + void setUp() { + service = new EntityDigestBaselineMigrationWriteService(baselineRepository, auditRepository); + LocalDateTime time = LocalDateTime.parse("2026-09-26T01:02:03.123456"); + source = baseline(1, "old", time.minusDays(1), "publish:old", "verify:old"); + replacement = baseline(2, "new", time.minusDays(1), "publish:old", "verify:old"); + audit = audit(time); + } + + @Test + void compareAndSetAndAuditAreBothRequiredForCommit() { + when(baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(source, replacement)) + .thenReturn(1); + + service.commit(source, replacement, audit); + + verify(baselineRepository).migrateEntityFullVersionBaselineIfUnchanged(source, replacement); + verify(auditRepository).insert(audit); + } + + @Test + void changedRowPreventsAuditInsert() { + when(baselineRepository.migrateEntityFullVersionBaselineIfUnchanged(source, replacement)) + .thenReturn(0); + + assertThrows(IllegalStateException.class, () -> service.commit(source, replacement, audit)); + + verify(auditRepository, never()).insert(any()); + } + + @Test + void maintenanceOperationCannotReplacePublishProvenance() { + replacement.setRecordedFromPublishWorkflowId("migration-op"); + + assertThrows(IllegalArgumentException.class, () -> service.commit(source, replacement, audit)); + + verify(baselineRepository, never()).migrateEntityFullVersionBaselineIfUnchanged(any(), any()); + verify(auditRepository, never()).insert(any()); + } + + private RecordedParticipantDigest baseline( + int schema, String digest, LocalDateTime time, String recordedFrom, String lastVerified) { + RecordedParticipantDigest baseline = new RecordedParticipantDigest(); + baseline.setId(91L); + baseline.setTenantId("tenant-7"); + baseline.setPublishType(PublishType.FULL_VERSION); + baseline.setParticipantKey(PublishParticipantKey.ENTITY_MANAGEMENT); + baseline.setScopeValue("42"); + baseline.setBaseVersionId(null); + baseline.setAppliedCommitId("version:42"); + baseline.setContentDigest(digest); + baseline.setDigestSchemaVersion(schema); + baseline.setRecordedFromPublishWorkflowId(recordedFrom); + baseline.setRecordedAt(time); + baseline.setLastVerifiedPublishWorkflowId(lastVerified); + baseline.setLastVerifiedAt(time); + return baseline; + } + + private EntityDigestBaselineMigrationAudit audit(LocalDateTime time) { + return new EntityDigestBaselineMigrationAudit( + null, + "migration-op", + 91L, + "tenant-7", + PublishType.FULL_VERSION, + PublishParticipantKey.ENTITY_MANAGEMENT, + null, + "42", + "version:42", + "old", + 1, + "publish:old", + time.minusDays(1), + "verify:old", + time.minusDays(1), + "tenant-7", + PublishType.FULL_VERSION, + PublishParticipantKey.ENTITY_MANAGEMENT, + null, + "42", + "version:42", + "new", + 2, + "operator:reviewer-1", + "job:entity-baseline", + EntityDigestBaselineMigrationAudit.COMMITTED_OUTCOME, + time); + } +}