From aa8a029c630809bd4136a6e383c14b1b250ddb10 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 10:45:40 +1200 Subject: [PATCH 01/75] Add distinct Account and Game Session gRPC workload identities --- dev-tools/certs/generate-dev-certs.sh | 6 +- .../preview/validate-preview-artifact.py | 38 +++++++- .../preview/wait-for-hosted-identity.sh | 4 + .../hosted/shared/ensure-grpc-tls-secret.sh | 8 +- dev-tools/tests/dev-demo-workflow-contract.sh | 4 + ...d-identity-controller-manifest-contract.sh | 50 ++++++----- ...d-identity-controller-workflow-contract.sh | 23 +++-- .../test_validate_preview_artifact.py | 36 +++++++- k8s/base/account-service.yaml | 10 ++- k8s/base/game-session-service.yaml | 10 ++- k8s/helm/firemud/templates/_helpers.tpl | 2 +- k8s/hosted-identity-controller/admission.yaml | 80 ++++++++++------- .../contract/HostedIdentityContract.java | 10 +++ .../CertificateMaterialService.java | 83 ++++++++++++++--- .../CertificateResourceFactory.java | 45 +++++++++- .../kubernetes/DeploymentRolloutService.java | 31 +++++-- .../HostedIdentityScopeService.java | 10 +++ .../model/EnvironmentIdentityPlan.java | 63 +++++++++---- .../reconcile/HostedIdentityReconciler.java | 90 ++++++++++++------- .../security/EnvironmentIdentityPlanner.java | 18 ++++ .../CertificateMaterialServiceTest.java | 43 ++++++++- .../CertificateResourceFactoryTest.java | 64 ++++++++++++- .../DeploymentRolloutServiceTest.java | 34 +++++-- .../HostedIdentityScopeServiceTest.java | 6 +- .../HostedIdentityTestFixtures.java | 42 ++++++++- .../SecretProjectionServiceTest.java | 12 +++ .../HostedIdentityReconcilerSafetyTest.java | 24 +++-- .../EnvironmentIdentityPlannerTest.java | 14 +++ 28 files changed, 697 insertions(+), 163 deletions(-) diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index 6465cbb5ec..7509305799 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -27,10 +27,10 @@ if [[ "${1:-}" == "--workload" ]]; then exit 1 } case "$workload" in - game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service) + account-service|game-session-service|game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service) ;; *) - echo "unsupported gRPC publication workload: $workload" >&2 + echo "unsupported gRPC workload identity: $workload" >&2 exit 1 ;; esac @@ -70,7 +70,7 @@ EOF openssl x509 -req -in "$workload_request" -CA "$ca_cert" -CAkey "$ca_key" \ -CAserial "$workload_serial" -out "$output_cert" -days 365 -sha256 \ -extensions v3_req -extfile "$workload_config" >/dev/null || { - echo "failed to sign publication workload certificate: $workload" >&2 + echo "failed to sign gRPC workload identity certificate: $workload" >&2 exit 1 } chmod 644 "$output_cert" diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index 0e0a3666d9..573e389463 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -66,6 +66,11 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: "game-logic-service", "automation-scripting-service", } +ACCOUNT_GRPC_WORKLOADS = {"account-service"} +GAME_SESSION_GRPC_WORKLOADS = {"game-session-service"} +DISTINCT_GRPC_WORKLOADS = ( + PUBLICATION_GRPC_WORKLOADS | ACCOUNT_GRPC_WORKLOADS | GAME_SESSION_GRPC_WORKLOADS +) EXPECTED_NAMES = { "Deployment": SERVICE_IMAGES | {"postgres", "redis-coord", "redis-cache", "minio"}, "Service": SERVICE_IMAGES @@ -132,7 +137,7 @@ def walk(value: object, path: str = "object"): "jwt-signing-keys", "minio-credentials", "firemud-grpc-tls", -} | {f"firemud-grpc-{service}" for service in PUBLICATION_GRPC_WORKLOADS} +} | {f"firemud-grpc-{service}" for service in DISTINCT_GRPC_WORKLOADS} CANONICAL_INGRESS_ISSUER = "letsencrypt-prod" ALLOCATED_TELNET_PORT_ANNOTATION = "firemud.dev/allocated-telnet-port" CERTIFICATE_IDENTITY_MODES = {"standalone", "hosted-controller"} @@ -1496,7 +1501,7 @@ def validate_service_consumers( "FIREMUD_GRPC_PRIVATE_KEY_PATH": "/tls/tls.key", "FIREMUD_GRPC_CA_CERT_PATH": "/tls/ca.crt", } - if service in PUBLICATION_GRPC_WORKLOADS + if service in DISTINCT_GRPC_WORKLOADS else { "FIREMUD_GRPC_CERT_CHAIN_PATH": "/tls/client.crt", "FIREMUD_GRPC_PRIVATE_KEY_PATH": "/tls/client.key", @@ -1508,6 +1513,24 @@ def validate_service_consumers( for entry in container.get("env", []) if isinstance(entry, dict) } + if service in DISTINCT_GRPC_WORKLOADS: + namespace_identity = next( + ( + entry + for entry in container.get("env", []) + if isinstance(entry, dict) + and entry.get("name") == "FIREMUD_GRPC_WORKLOAD_NAMESPACE" + ), + None, + ) + if namespace_identity != { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, + }: + fail( + f"Deployment/{service} must derive FIREMUD_GRPC_WORKLOAD_NAMESPACE " + "from metadata.namespace" + ) for env_name, expected_path in expected_grpc_paths.items(): if declared_grpc_paths.get(env_name) != expected_path: fail( @@ -1516,7 +1539,7 @@ def validate_service_consumers( grpc_secret_name = ( f"firemud-grpc-{service}" - if service in PUBLICATION_GRPC_WORKLOADS + if service in DISTINCT_GRPC_WORKLOADS else "firemud-grpc-tls" ) expected_mounts = { @@ -1586,6 +1609,15 @@ def validate_service_consumers( f"Deployment/{service}.spec.template.spec.volumes[{volume_name}].secret", ) if source.get("secretName") != source_name: + if ( + service in DISTINCT_GRPC_WORKLOADS + and volume_name == "grpc-tls" + and source.get("secretName") == "firemud-grpc-tls" + ): + fail( + f"Deployment/{service} distinct workload falls back to " + "shared firemud-grpc-tls" + ) fail(f"Deployment/{service} has an unexpected {volume_name} source") if volume_name in {"gateway-ws-server-tls", "gateway-ws-client-tls"}: expected_source = { diff --git a/dev-tools/hosted/preview/wait-for-hosted-identity.sh b/dev-tools/hosted/preview/wait-for-hosted-identity.sh index 7f3b3d3819..285caea1f5 100644 --- a/dev-tools/hosted/preview/wait-for-hosted-identity.sh +++ b/dev-tools/hosted/preview/wait-for-hosted-identity.sh @@ -150,6 +150,10 @@ if [[ "${1:-}" == "--projections" ]]; then "firemud-grpc-${workload}|grpc-publication-${workload}|tls.crt,tls.key,ca.crt" ) done + projections+=( + "firemud-grpc-account-service|grpc-account-service|tls.crt,tls.key,ca.crt" + "firemud-grpc-game-session-service|grpc-game-session-service|tls.crt,tls.key,ca.crt" + ) initialize_wait_state "$timeout_seconds" all_projections_ready=true for projection in "${projections[@]}"; do diff --git a/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh b/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh index 0c0aaba438..395a534cfa 100644 --- a/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh +++ b/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh @@ -41,6 +41,8 @@ if [[ "$temporary_cert_dir" == true ]]; then fi workloads=( + account-service + game-session-service game-design-service world-management-service entity-management-service @@ -239,8 +241,8 @@ else fi # Keep the legacy shared leaf and CA intact. A separate, stable CA signs the - # five distinct publication leaves; the CA key is retained only in this - # unmounted source Secret so it can be reused for future missing projections. + # five publication leaves plus the Account and Game Session workload leaves. + # The CA key is retained only in this unmounted source Secret for reuse. openssl genrsa -out "$source_key" 2048 >/dev/null 2>&1 openssl req -x509 -new -nodes -key "$source_key" -sha256 -days 365 \ -subj "/CN=FireMUD-Standalone-gRPC-CA" \ @@ -332,4 +334,4 @@ for workload in "${workloads[@]}"; do --from-file=tls.key="$workload_key" done -echo "Stable standalone gRPC TLS material is ready in namespace ${namespace}: shared leaf plus ${#workloads[@]} distinct publication leaves" +echo "Stable standalone gRPC TLS material is ready in namespace ${namespace}: shared leaf plus ${#workloads[@]} distinct workload leaves" diff --git a/dev-tools/tests/dev-demo-workflow-contract.sh b/dev-tools/tests/dev-demo-workflow-contract.sh index 9189463013..cab7021ce9 100644 --- a/dev-tools/tests/dev-demo-workflow-contract.sh +++ b/dev-tools/tests/dev-demo-workflow-contract.sh @@ -60,6 +60,8 @@ for required in \ ' world-management-service' \ ' entity-management-service' \ ' game-logic-service' \ + ' account-service' \ + ' game-session-service' \ ' automation-scripting-service'; do contains_literal "$standalone_grpc_tls" "$required" done @@ -1041,6 +1043,8 @@ for required in ( '"firemud-grpc-tls|grpc|tls.crt,tls.key,ca.crt,client.crt,client.key"', 'publication_workloads=(', 'firemud-grpc-${workload}|grpc-publication-${workload}|tls.crt,tls.key,ca.crt', + 'firemud-grpc-account-service|grpc-account-service|tls.crt,tls.key,ca.crt', + 'firemud-grpc-game-session-service|grpc-game-session-service|tls.crt,tls.key,ca.crt', ' game-design-service', ' world-management-service', ' entity-management-service', diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index 82561a61d1..2cc5163dc2 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -1193,7 +1193,11 @@ controller_secret_expression = next( ) normalized_controller_secret_expression = " ".join(controller_secret_expression.split()) assert "object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')" in controller_secret_expression +assert "'grpc-account-service'" in controller_secret_expression +assert "'grpc-game-session-service'" in controller_secret_expression assert "object.metadata.name == 'firemud-grpc-tls'" in controller_secret_expression +assert "object.metadata.name == 'firemud-grpc-account-service'" in controller_secret_expression +assert "object.metadata.name == 'firemud-grpc-game-session-service'" in controller_secret_expression assert normalized_controller_secret_expression.count("request.name.startsWith(") == 3 assert normalized_controller_secret_expression.count("object.metadata.name.startsWith(") == 2 assert "request.namespace.size() - 9" in normalized_controller_secret_expression @@ -1219,6 +1223,8 @@ def canonical_primary_name(namespace, name): "grpc-entity-management-service", "grpc-game-logic-service", "grpc-automation-scripting-service", + "grpc-account-service", + "grpc-game-session-service", } @@ -1244,6 +1250,10 @@ assert "object.metadata.name == 'dev-telnet-tls'" in cert_manager_expression assert "object.metadata.name == 'dev-gateway-internal-ws'" in cert_manager_expression assert "object.metadata.name == 'dev-tcp-proxy-bridge'" in cert_manager_expression assert "object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')" in cert_manager_expression +assert "object.metadata.labels['firemud.dev/role'] == 'grpc-account-service'" in cert_manager_expression +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 "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 @@ -1295,8 +1305,10 @@ assert "firemud-grpc-tls" not in controller_delete_expression assert "request.name.startsWith(" in controller_delete_expression assert "(request.operation != 'DELETE' && has(object.metadata.labels)" in certificate_match assert "object.metadata.labels['firemud.dev/identity-name'] == ((request.namespace == 'dev-identity') ? 'dev-demo' : request.namespace.substring(0, request.namespace.size() - 9))" in certificate_match -assert "object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge']" in certificate_match +assert "object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service']" in certificate_match assert "grpc-publication-" in certificate_match +assert "grpc-account-service" in certificate_match +assert "grpc-game-session-service" in certificate_match assert "object.metadata.name == 'firemud-grpc-tls'" not in certificate_match certificate_expressions = [ @@ -1312,6 +1324,7 @@ controller_non_delete_expression = certificate_expressions[0].split( assert "firemud-grpc-tls" not in controller_non_delete_expression assert "'grpc'" not in controller_non_delete_expression assert "grpc-publication-" in controller_non_delete_expression +assert "grpc-account-service" in controller_non_delete_expression assert "has(object.spec.isCA)" in controller_non_delete_expression assert "object.spec.isCA == false" in controller_non_delete_expression assert "(!has(object.spec.commonName) || object.spec.commonName == '')" in controller_non_delete_expression @@ -1336,6 +1349,9 @@ profile_expression = next( normalized_profile_expression = " ".join(profile_expression.split()) assert "spring-cloud-gateway-mtls." in profile_expression assert ".svc.cluster.local" in profile_expression +assert "object.spec.uris == ['spiffe://firemud/ns/'" in profile_expression +assert "object.spec.dnsNames == ['account-service'" in profile_expression +assert "object.spec.dnsNames == ['game-session-service'" in profile_expression assert "spiffe://firemud/ns/" in profile_expression assert "/sa/tcp-proxy-service" in profile_expression assert "has(object.spec.encodeUsagesInRequest)" in profile_expression @@ -1772,7 +1788,10 @@ for portable_render_fragment in \ require_literal "$BOOTSTRAP" "$portable_render_fragment" done require_literal "$ADMISSION" "'firemud-grpc-tls-previous', " -require_literal "$ADMISSION" "'-grpc-automation-scripting-service-previous')] &&" +require_literal "$ADMISSION" "'firemud-grpc-account-service'" +require_literal "$ADMISSION" "'firemud-grpc-game-session-service'" +require_literal "$ADMISSION" "'-grpc-account-service-previous'), " +require_literal "$ADMISSION" "'-grpc-game-session-service-previous')] &&" require_literal "$ADMISSION" "request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' ||" require_literal "$BOOTSTRAP" "crd_deadline=\$((SECONDS + WAIT_SECONDS))" # shellcheck disable=SC2016 # Match the literal bootstrap default. @@ -3450,13 +3469,7 @@ def service_consumer_documents(): "/tls", "secret", f"firemud-grpc-{service}" - if service in { - "game-design-service", - "world-management-service", - "entity-management-service", - "game-logic-service", - "automation-scripting-service", - } + if service in validator.DISTINCT_GRPC_WORKLOADS else "firemud-grpc-tls", ), "jwt-signing-keys": ( @@ -3507,14 +3520,12 @@ def service_consumer_documents(): "name": service, "volumeMounts": mounts, } - if service in { - "game-design-service", - "world-management-service", - "entity-management-service", - "game-logic-service", - "automation-scripting-service", - }: + if service in validator.DISTINCT_GRPC_WORKLOADS: container["env"] = [ + { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, + }, { "name": "FIREMUD_GRPC_CERT_CHAIN_PATH", "value": "/tls/tls.crt", @@ -4051,9 +4062,8 @@ publication_services = ( "game-logic-service", "automation-scripting-service", ) +distinct_workload_services = publication_services + ("account-service", "game-session-service") shared_services = ( - "account-service", - "game-session-service", "logging-admin-service", "social-groups-service", "spring-cloud-gateway", @@ -4118,7 +4128,7 @@ def assert_paths_and_mount(container, service, cert_path, key_path): fail(f"Deployment/{service} grpc-tls must mount read-only at /tls") -for service in publication_services: +for service in distinct_workload_services: deployment = deployment_for(service) container, pod_spec = workload_container(deployment, service) assert_paths_and_mount(container, service, "/tls/tls.crt", "/tls/tls.key") @@ -4142,7 +4152,7 @@ for service in publication_services: if secret_name != expected_secret: if secret_name == "firemud-grpc-tls": fail( - f"Deployment/{service} publication workload falls back to " + f"Deployment/{service} distinct workload falls back to " "shared firemud-grpc-tls" ) fail( diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 168acf9591..c38691e95a 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -626,6 +626,7 @@ contains "$waiter" 'tls.crt,tls.key,ca.crt,client.crt,client.key' contains "$waiter" 'publication_workloads=(' # shellcheck disable=SC2016 # Match literal shell source in the waiter. contains "$waiter" 'firemud-grpc-${workload}|grpc-publication-${workload}|tls.crt,tls.key,ca.crt' +contains "$waiter" 'firemud-grpc-account-service|grpc-account-service|tls.crt,tls.key,ca.crt' for workload in \ game-design-service \ world-management-service \ @@ -5467,6 +5468,12 @@ if [[ "$1" == -n && "$2" == pr-42 && "$3" == get && "$4" == secret ]]; then firemud-grpc-automation-scripting-service) printf '%s' '{"metadata":{"name":"firemud-grpc-automation-scripting-service","labels":{"firemud.dev/managed-by":"hosted-identity-controller","firemud.dev/identity-name":"pr-42","firemud.dev/role":"grpc-publication-automation-scripting-service","firemud.dev/retention":"retained"}},"data":{"tls.crt":"cert","tls.key":"key","ca.crt":"ca"}}' ;; + firemud-grpc-account-service) + printf '%s' '{"metadata":{"name":"firemud-grpc-account-service","labels":{"firemud.dev/managed-by":"hosted-identity-controller","firemud.dev/identity-name":"pr-42","firemud.dev/role":"grpc-account-service","firemud.dev/retention":"retained"}},"data":{"tls.crt":"cert","tls.key":"key","ca.crt":"ca"}}' + ;; + firemud-grpc-game-session-service) + printf '%s' '{"metadata":{"name":"firemud-grpc-game-session-service","labels":{"firemud.dev/managed-by":"hosted-identity-controller","firemud.dev/identity-name":"pr-42","firemud.dev/role":"grpc-game-session-service","firemud.dev/retention":"retained"}},"data":{"tls.crt":"cert","tls.key":"key","ca.crt":"ca"}}' + ;; *) printf 'unexpected projection Secret: %s\n' "$secret_name" >&2 exit 2 @@ -5582,19 +5589,19 @@ run_projection_waiter_fixture() { fi } -run_projection_waiter_fixture projection-absence 0 12 2 +run_projection_waiter_fixture projection-absence 0 14 2 run_projection_waiter_fixture projection-command-failure 42 1 0 'Error from server (Forbidden)' run_projection_waiter_fixture projection-command-not-found 46 1 0 'Error from server (NotFound)' run_projection_waiter_fixture projection-command-unauthorized 47 1 0 'Error from server (Unauthorized)' run_projection_waiter_fixture projection-command-usage-error 2 1 0 'error: unknown flag' -run_projection_waiter_fixture projection-transport-recovery 0 12 2 +run_projection_waiter_fixture projection-transport-recovery 0 14 2 run_projection_waiter_fixture projection-transport-exhaustion 45 3 2 'Unable to connect to the server' -run_projection_waiter_fixture projection-etcd-timeout-recovery 0 12 2 -run_projection_waiter_fixture projection-etcd-leader-recovery 0 12 2 -run_projection_waiter_fixture projection-overload-recovery 0 12 2 -run_projection_waiter_fixture projection-unavailable-recovery 0 12 2 -run_projection_waiter_fixture projection-currently-unavailable-recovery 0 12 2 -run_projection_waiter_fixture projection-apiserver-shutdown-recovery 0 12 2 +run_projection_waiter_fixture projection-etcd-timeout-recovery 0 14 2 +run_projection_waiter_fixture projection-etcd-leader-recovery 0 14 2 +run_projection_waiter_fixture projection-overload-recovery 0 14 2 +run_projection_waiter_fixture projection-unavailable-recovery 0 14 2 +run_projection_waiter_fixture projection-currently-unavailable-recovery 0 14 2 +run_projection_waiter_fixture projection-apiserver-shutdown-recovery 0 14 2 run_active_waiter_fixture() { local scenario="$1" diff --git a/dev-tools/validation/test_validate_preview_artifact.py b/dev-tools/validation/test_validate_preview_artifact.py index a7793fb4d2..61465e7cce 100644 --- a/dev-tools/validation/test_validate_preview_artifact.py +++ b/dev-tools/validation/test_validate_preview_artifact.py @@ -612,13 +612,19 @@ def test_consumer_validation_rejects_non_mapping_mounts_and_volumes(self): { "name": "account-service", "env": [ + { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": { + "fieldRef": {"fieldPath": "metadata.namespace"} + }, + }, { "name": "FIREMUD_GRPC_CERT_CHAIN_PATH", - "value": "/tls/client.crt", + "value": "/tls/tls.crt", }, { "name": "FIREMUD_GRPC_PRIVATE_KEY_PATH", - "value": "/tls/client.key", + "value": "/tls/tls.key", }, { "name": "FIREMUD_GRPC_CA_CERT_PATH", @@ -632,15 +638,24 @@ def test_consumer_validation_rejects_non_mapping_mounts_and_volumes(self): "mountPath": "/var/run/secrets/firemud/jwt", "readOnly": True, }, + { + "name": "jwt-jwks", + "mountPath": "/var/run/secrets/firemud/jwks", + "readOnly": True, + }, ], } ], "volumes": [ - {"name": "grpc-tls", "secret": {"secretName": "firemud-grpc-tls"}}, + { + "name": "grpc-tls", + "secret": {"secretName": "firemud-grpc-account-service"}, + }, { "name": "jwt-signing-keys", "secret": {"secretName": "jwt-signing-keys"}, }, + {"name": "jwt-jwks", "configMap": {"name": "jwt-jwks"}}, ], } document = { @@ -648,6 +663,21 @@ def test_consumer_validation_rejects_non_mapping_mounts_and_volumes(self): "metadata": {"name": "account-service"}, "spec": {"template": {"spec": pod}}, } + with patch.object(self.validator, "SERVICE_IMAGES", {"account-service"}): + self.validator.validate_service_consumers( + [document], "pr-42", "standalone", "public" + ) + fallback = copy.deepcopy(document) + fallback["spec"]["template"]["spec"]["volumes"][0]["secret"][ + "secretName" + ] = "firemud-grpc-tls" + with self.assertRaisesRegex( + ValueError, + "Deployment/account-service distinct workload falls back to shared firemud-grpc-tls", + ): + self.validator.validate_service_consumers( + [fallback], "pr-42", "standalone", "public" + ) for field, malformed in ( ("volumeMounts", ["not-a-mapping"]), ("volumes", ["not-a-mapping"]), diff --git a/k8s/base/account-service.yaml b/k8s/base/account-service.yaml index 29b8af8695..712a4af4a2 100644 --- a/k8s/base/account-service.yaml +++ b/k8s/base/account-service.yaml @@ -24,10 +24,14 @@ spec: env: - name: SPRING_PROFILES_ACTIVE value: "prod" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace - name: FIREMUD_GRPC_CERT_CHAIN_PATH - value: /tls/client.crt + value: /tls/tls.crt - name: FIREMUD_GRPC_PRIVATE_KEY_PATH - value: /tls/client.key + value: /tls/tls.key - name: FIREMUD_GRPC_CA_CERT_PATH value: /tls/ca.crt envFrom: @@ -109,7 +113,7 @@ spec: volumes: - name: grpc-tls secret: - secretName: firemud-grpc-tls + secretName: firemud-grpc-account-service - name: jwt-signing-keys secret: secretName: jwt-signing-keys diff --git a/k8s/base/game-session-service.yaml b/k8s/base/game-session-service.yaml index 61760b6b23..0b652dbbc9 100644 --- a/k8s/base/game-session-service.yaml +++ b/k8s/base/game-session-service.yaml @@ -24,10 +24,14 @@ spec: env: - name: SPRING_PROFILES_ACTIVE value: "prod" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace - name: FIREMUD_GRPC_CERT_CHAIN_PATH - value: /tls/client.crt + value: /tls/tls.crt - name: FIREMUD_GRPC_PRIVATE_KEY_PATH - value: /tls/client.key + value: /tls/tls.key - name: FIREMUD_GRPC_CA_CERT_PATH value: /tls/ca.crt envFrom: @@ -106,7 +110,7 @@ spec: volumes: - name: grpc-tls secret: - secretName: firemud-grpc-tls + secretName: firemud-grpc-game-session-service - name: jwt-signing-keys secret: secretName: jwt-signing-keys diff --git a/k8s/helm/firemud/templates/_helpers.tpl b/k8s/helm/firemud/templates/_helpers.tpl index 9d387b1bae..488f4af532 100644 --- a/k8s/helm/firemud/templates/_helpers.tpl +++ b/k8s/helm/firemud/templates/_helpers.tpl @@ -32,7 +32,7 @@ helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }} {{- end -}} {{- define "firemud.grpcWorkloadNames" -}} -{{- list "game-design-service" "world-management-service" "entity-management-service" "game-logic-service" "automation-scripting-service" | toJson -}} +{{- list "account-service" "game-session-service" "game-design-service" "world-management-service" "entity-management-service" "game-logic-service" "automation-scripting-service" | toJson -}} {{- end -}} {{- define "firemud.grpcSecretName" -}} diff --git a/k8s/hosted-identity-controller/admission.yaml b/k8s/hosted-identity-controller/admission.yaml index 5ed2cf7e57..c911612ba1 100644 --- a/k8s/hosted-identity-controller/admission.yaml +++ b/k8s/hosted-identity-controller/admission.yaml @@ -157,17 +157,17 @@ spec: 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.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))$') || - request.name.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service)$') || + (request.name == 'firemud-grpc-tls' || request.name == 'firemud-grpc-account-service' || request.name == 'firemud-grpc-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))$') || + 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))-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.matches('^firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-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))$') || + (object.metadata.name == 'firemud-grpc-tls' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-game-session-service' || + 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' || - 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))-previous$'))))) + object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))-previous$'))))) validations: # Namespace deletion also deletes the exact retained material. Allow # only the built-in kube-system namespace controller, DELETE, managed @@ -179,7 +179,7 @@ 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)|firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-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))(-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|(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.startsWith( ((request.namespace == 'dev' || request.namespace == 'dev-identity') ? 'dev' : @@ -189,7 +189,7 @@ spec: (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && ((request.operation == 'DELETE' && (request.name == 'firemud-grpc-tls' || - (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))$') && + (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.startsWith( ((request.namespace == 'dev' || request.namespace == 'dev-identity') ? 'dev' : request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$') ? @@ -197,7 +197,7 @@ spec: request.namespace) + '-')) || ((request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && (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))-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.name.startsWith( ((request.namespace == 'dev' || request.namespace == 'dev-identity') ? 'dev' : request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$') ? @@ -206,10 +206,10 @@ spec: (request.operation != 'DELETE' && has(object.metadata.labels) && object.metadata.labels['firemud.dev/managed-by'] == 'hosted-identity-controller' && - (object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && + (object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc', 'grpc-account-service', 'grpc-game-session-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && object.metadata.labels['firemud.dev/retention'] == 'retained' && - (object.metadata.name == 'firemud-grpc-tls' || - (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))$') && + (object.metadata.name == 'firemud-grpc-tls' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-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.startsWith( ((request.namespace == 'dev' || request.namespace == 'dev-identity') ? 'dev' : request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$') ? @@ -217,7 +217,7 @@ spec: request.namespace) + '-')) || ((request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && (object.metadata.name == 'firemud-grpc-tls-previous' || - (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service))-previous$') && + (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))-previous$') && object.metadata.name.startsWith( ((request.namespace == 'dev' || request.namespace == 'dev-identity') ? 'dev' : request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$') ? @@ -236,7 +236,7 @@ spec: object.metadata.annotations['cert-manager.io/certificate-name'] == object.metadata.name && ((object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet'] && object.metadata.annotations['cert-manager.io/issuer-name'] == 'letsencrypt-prod') || - ((object.metadata.labels['firemud.dev/role'] in ['gateway-internal-ws', 'tcp-proxy-bridge'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && + ((object.metadata.labels['firemud.dev/role'] in ['gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && 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' && @@ -251,8 +251,10 @@ spec: (object.metadata.name == 'dev-telnet-tls' && object.metadata.labels['firemud.dev/role'] == 'telnet') || (object.metadata.name == 'dev-gateway-internal-ws' && object.metadata.labels['firemud.dev/role'] == 'gateway-internal-ws') || (object.metadata.name == 'dev-tcp-proxy-bridge' && object.metadata.labels['firemud.dev/role'] == 'tcp-proxy-bridge') || - (object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') && - object.metadata.name == 'dev-grpc-' + object.metadata.labels['firemud.dev/role'].substring(17)))) || + ((object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') && + object.metadata.name == 'dev-grpc-' + object.metadata.labels['firemud.dev/role'].substring(17)) || + (object.metadata.labels['firemud.dev/role'] == 'grpc-account-service' && object.metadata.name == 'dev-grpc-account-service') || + (object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service' && object.metadata.name == 'dev-grpc-game-session-service'))) || (request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$') && object.metadata.labels['firemud.dev/identity-name'] == request.namespace.substring(0, request.namespace.size() - 9) && ((object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-tls' && @@ -263,8 +265,10 @@ spec: object.metadata.labels['firemud.dev/role'] == 'gateway-internal-ws') || (object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-tcp-proxy-bridge' && object.metadata.labels['firemud.dev/role'] == 'tcp-proxy-bridge') || - (object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') && - object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-' + object.metadata.labels['firemud.dev/role'].substring(17)))))) + ((object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') && + object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-' + object.metadata.labels['firemud.dev/role'].substring(17)) || + (object.metadata.labels['firemud.dev/role'] == 'grpc-account-service' && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-account-service') || + (object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service' && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-game-session-service')))))) message: managed identity and runtime TLS Secrets are writable only by the controller or cert-manager for its owned identity Secret reason: Forbidden - expression: >- @@ -315,12 +319,12 @@ spec: (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$'))) || ((request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && ((request.operation == 'DELETE' && - 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))$') && + 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.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-')) || (request.operation != 'DELETE' && - 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))$') && + 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.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-')))) @@ -337,7 +341,7 @@ spec: request.operation == 'DELETE' && (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && (request.name == 'firemud-grpc-tls' || - (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))$') && + (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.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-')))) || @@ -345,7 +349,7 @@ spec: request.subResource == '' && (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && ((request.operation == 'DELETE' && - (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)))$') && + (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.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-'))) || @@ -353,8 +357,8 @@ spec: has(object.metadata.labels) && object.metadata.labels['firemud.dev/managed-by'] == 'hosted-identity-controller' && object.metadata.labels['firemud.dev/identity-name'] == ((request.namespace == 'dev-identity') ? 'dev-demo' : request.namespace.substring(0, request.namespace.size() - 9)) && - (object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && - 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))$') && + (object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && + 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.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-') && @@ -368,7 +372,7 @@ spec: object.spec.dnsNames == [((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.preview.firedevops.net'] && (!has(object.spec.uris) || object.spec.uris.size() == 0) && object.spec.issuerRef.name == 'letsencrypt-prod') || - (object.metadata.labels['firemud.dev/role'] in ['gateway-internal-ws', 'tcp-proxy-bridge'] && + (object.metadata.labels['firemud.dev/role'] in ['gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service'] && object.spec.issuerRef.name == 'firemud-ca-issuer')) && object.spec.issuerRef.kind == 'ClusterIssuer' && object.spec.issuerRef.group == 'cert-manager.io' && @@ -393,15 +397,25 @@ spec: ((!has(object.spec.dnsNames) || object.spec.dnsNames.size() == 0) && object.spec.uris == ['spiffe://firemud/ns/' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '/sa/tcp-proxy-service'] && object.spec.usages == ['digital signature', 'key encipherment', 'client auth'])) || - (!object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') || + ((!object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') && object.metadata.labels['firemud.dev/role'] != 'grpc-account-service') || (object.spec.secretName == object.metadata.name && object.spec.dnsNames == [object.metadata.labels['firemud.dev/role'].substring(17), object.metadata.labels['firemud.dev/role'].substring(17) + '.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)), object.metadata.labels['firemud.dev/role'].substring(17) + '.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc', object.metadata.labels['firemud.dev/role'].substring(17) + '.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc.cluster.local'] && object.spec.uris == ['spiffe://firemud/ns/' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '/sa/' + object.metadata.labels['firemud.dev/role'].substring(17)] && + object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth'])) && + (object.metadata.labels['firemud.dev/role'] != 'grpc-account-service' || + (object.spec.secretName == object.metadata.name && + object.spec.dnsNames == ['account-service', 'account-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)), 'account-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc', 'account-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc.cluster.local'] && + object.spec.uris == ['spiffe://firemud/ns/' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '/sa/account-service'] && + object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth'])) && + (object.metadata.labels['firemud.dev/role'] != 'grpc-game-session-service' || + (object.spec.secretName == object.metadata.name && + object.spec.dnsNames == ['game-session-service', 'game-session-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)), 'game-session-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc', 'game-session-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc.cluster.local'] && + object.spec.uris == ['spiffe://firemud/ns/' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '/sa/game-session-service'] && object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth']))) || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.subResource == 'status' && request.operation == 'UPDATE' && - 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))$') && + 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.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-') && @@ -510,7 +524,7 @@ spec: object.rules.exists(r, r.apiGroups == ['cert-manager.io'] && r.resources == ['certificates'] && - r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service')] && + r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service')] && r.verbs == ['get', 'update', 'patch', 'delete']) && object.rules.exists(r, r.apiGroups == ['cert-manager.io'] && @@ -520,12 +534,12 @@ spec: object.rules.exists(r, r.apiGroups == [''] && r.resources == ['secrets'] && - r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge-previous'), 'firemud-grpc-tls-previous', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service-previous')] && + r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge-previous'), 'firemud-grpc-tls-previous', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service-previous')] && r.verbs == ['get']) && object.rules.exists(r, r.apiGroups == [''] && r.resources == ['secrets'] && - r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge-previous'), 'firemud-grpc-tls-previous', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service-previous')] && + r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge-previous'), 'firemud-grpc-tls-previous', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service-previous')] && r.verbs == ['update', 'patch', 'delete']) && object.rules.exists(r, r.apiGroups == [''] && @@ -538,7 +552,7 @@ spec: object.rules.exists(r, r.apiGroups == [''] && r.resources == ['secrets'] && - r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', 'firemud-grpc-game-design-service', 'firemud-grpc-world-management-service', 'firemud-grpc-entity-management-service', 'firemud-grpc-game-logic-service', 'firemud-grpc-automation-scripting-service'] && + r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', 'firemud-grpc-game-design-service', 'firemud-grpc-world-management-service', 'firemud-grpc-entity-management-service', 'firemud-grpc-game-logic-service', 'firemud-grpc-automation-scripting-service', 'firemud-grpc-account-service', 'firemud-grpc-game-session-service'] && r.verbs == ['get', 'update', 'patch', 'delete']) && object.rules.exists(r, r.apiGroups == [''] && diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java index a8f242b2eb..f2bb0be542 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java @@ -63,6 +63,10 @@ public final class HostedIdentityContract { public static final String TCP_PROXY_BRIDGE_ROLE = "tcp-proxy-bridge"; public static final String GRPC_ROLE = "grpc"; public static final String GRPC_PUBLICATION_ROLE_PREFIX = "grpc-publication-"; + public static final String GRPC_ACCOUNT_WORKLOAD = "account-service"; + public static final String GRPC_ACCOUNT_ROLE = "grpc-account-service"; + public static final String GRPC_GAME_SESSION_WORKLOAD = "game-session-service"; + public static final String GRPC_GAME_SESSION_ROLE = "grpc-game-session-service"; public static final List GRPC_PUBLICATION_WORKLOADS = List.of( "game-design-service", @@ -97,6 +101,12 @@ public static String grpcPublicationRole(String workload) { return GRPC_PUBLICATION_ROLE_PREFIX + workload; } + public static boolean isGrpcWorkloadIdentityRole(String role) { + return GRPC_ACCOUNT_ROLE.equals(role) + || GRPC_GAME_SESSION_ROLE.equals(role) + || isGrpcPublicationRole(role); + } + public static boolean isGrpcPublicationRole(String role) { return role != null && GRPC_PUBLICATION_WORKLOADS.stream() diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java index 65601f3d39..9e8d053d29 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java @@ -189,11 +189,52 @@ private RoleMaterial grpcPublication( EnvironmentIdentityPlan plan, String workload, MaterializationBatch batch) { - String role = HostedIdentityContract.grpcPublicationRole(workload); + return grpcWorkloadIdentity( + client, + plan, + HostedIdentityContract.grpcPublicationRole(workload), + workload, + plan.grpcPublicationCertificateName(workload), + plan.grpcPublicationSourceSecretName(workload), + batch); + } + + private RoleMaterial grpcAccount( + KubernetesClient client, EnvironmentIdentityPlan plan, MaterializationBatch batch) { + return grpcWorkloadIdentity( + client, + plan, + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD, + plan.grpcAccountCertificateName(), + plan.grpcAccountSourceSecretName(), + batch); + } + + private RoleMaterial grpcGameSession( + KubernetesClient client, EnvironmentIdentityPlan plan, MaterializationBatch batch) { + return grpcWorkloadIdentity( + client, + plan, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD, + plan.grpcGameSessionCertificateName(), + plan.grpcGameSessionSourceSecretName(), + batch); + } + + private RoleMaterial grpcWorkloadIdentity( + KubernetesClient client, + EnvironmentIdentityPlan plan, + String role, + String workload, + String certificateName, + String sourceSecretName, + MaterializationBatch batch) { RoleExpectation expectation = new RoleExpectation( - plan.grpcPublicationDnsNames(workload), - List.of(plan.grpcPublicationUriSan(workload)), + plan.grpcWorkloadIdentityDnsNames(workload), + List.of(plan.grpcWorkloadIdentityUriSan(workload)), true, true, "kubernetes.io/tls", @@ -202,8 +243,14 @@ private RoleMaterial grpcPublication( client, plan, role, - certificateFactory.grpcPublication(plan, workload, properties.getGrpcRenewBefore()), - plan.grpcPublicationSourceSecretName(workload), + certificateFactory.grpcWorkloadIdentity( + plan, + role, + workload, + certificateName, + sourceSecretName, + properties.getGrpcRenewBefore()), + sourceSecretName, expectation, batch); } @@ -337,6 +384,12 @@ private RotationSnapshot rotationSnapshot(KubernetesClient client, EnvironmentId String role = HostedIdentityContract.grpcPublicationRole(workload); observations.put(role, rotationObservation(client, plan, role)); } + observations.put( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + rotationObservation(client, plan, HostedIdentityContract.GRPC_ACCOUNT_ROLE)); + observations.put( + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + rotationObservation(client, plan, HostedIdentityContract.GRPC_GAME_SESSION_ROLE)); String selectedRole = selectSerializedRole( observations.values().stream().map(RotationObservation::state).toList()); @@ -523,7 +576,7 @@ private SecretMaterialValidator.MaterialSummary validateAcceptedMaterial( HostedIdentityContract.GATEWAY_INTERNAL_WS_ROLE.equals(role) || HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE.equals(role) || HostedIdentityContract.GRPC_ROLE.equals(role) - || HostedIdentityContract.isGrpcPublicationRole(role); + || HostedIdentityContract.isGrpcWorkloadIdentityRole(role); Secret validationSecret = accepted; String expectedType = current.expectedType(); String expectedTrustAnchor = current.trustAnchor(); @@ -610,8 +663,8 @@ private static String certificateName(EnvironmentIdentityPlan plan, String role) plan.gatewayInternalWsCertificateName(); case HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE -> plan.tcpProxyBridgeCertificateName(); default -> { - if (HostedIdentityContract.isGrpcPublicationRole(role)) { - yield plan.grpcPublicationCertificateNames().get(role); + if (HostedIdentityContract.isGrpcWorkloadIdentityRole(role)) { + yield plan.grpcWorkloadIdentityCertificateNames().get(role); } throw new IllegalArgumentException("unsupported cert-manager identity role: " + role); } @@ -619,8 +672,8 @@ private static String certificateName(EnvironmentIdentityPlan plan, String role) } private static String sourceSecretName(EnvironmentIdentityPlan plan, String role) { - if (HostedIdentityContract.isGrpcPublicationRole(role)) { - return plan.grpcPublicationSourceSecretNames().get(role); + if (HostedIdentityContract.isGrpcWorkloadIdentityRole(role)) { + return plan.grpcWorkloadIdentitySourceSecretNames().get(role); } return plan.secretName(role); } @@ -633,7 +686,7 @@ private static String issuerName(EnvironmentIdentityPlan plan, String role) { HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE -> plan.grpcIssuer(); default -> { - if (HostedIdentityContract.isGrpcPublicationRole(role)) { + if (HostedIdentityContract.isGrpcWorkloadIdentityRole(role)) { yield plan.grpcIssuer(); } throw new IllegalArgumentException("unsupported cert-manager identity role: " + role); @@ -1125,6 +1178,14 @@ public RoleMaterial grpcPublication(String workload) { return CertificateMaterialService.this.grpcPublication(client, plan, workload, this); } + public RoleMaterial grpcAccount() { + return CertificateMaterialService.this.grpcAccount(client, plan, this); + } + + public RoleMaterial grpcGameSession() { + return CertificateMaterialService.this.grpcGameSession(client, plan, this); + } + private List certificateRequests() { if (certificateRequests == null) { certificateRequests = diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java index 54763c059d..928ea36bcd 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java @@ -79,14 +79,53 @@ public GenericKubernetesResource tcpProxyBridge( /** Builds one retained client/server identity for a protected publication workload. */ public GenericKubernetesResource grpcPublication( EnvironmentIdentityPlan plan, String workload, Duration renewBefore) { - return certificate( + return grpcWorkloadIdentity( plan, HostedIdentityContract.grpcPublicationRole(workload), + workload, plan.grpcPublicationCertificateName(workload), plan.grpcPublicationSourceSecretName(workload), + renewBefore); + } + + /** Builds the retained Account workload identity used by protected audit ingress. */ + public GenericKubernetesResource grpcAccount(EnvironmentIdentityPlan plan, Duration renewBefore) { + return grpcWorkloadIdentity( + plan, + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD, + plan.grpcAccountCertificateName(), + plan.grpcAccountSourceSecretName(), + renewBefore); + } + + /** Builds the retained Game Session workload identity used for Account JOIN calls. */ + public GenericKubernetesResource grpcGameSession( + EnvironmentIdentityPlan plan, Duration renewBefore) { + return grpcWorkloadIdentity( + plan, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD, + plan.grpcGameSessionCertificateName(), + plan.grpcGameSessionSourceSecretName(), + renewBefore); + } + + GenericKubernetesResource grpcWorkloadIdentity( + EnvironmentIdentityPlan plan, + String role, + String workload, + String certificateName, + String secretName, + Duration renewBefore) { + return certificate( + plan, + role, + certificateName, + secretName, plan.grpcIssuer(), - plan.grpcPublicationDnsNames(workload), - List.of(plan.grpcPublicationUriSan(workload)), + plan.grpcWorkloadIdentityDnsNames(workload), + List.of(plan.grpcWorkloadIdentityUriSan(workload)), List.of("digital signature", "key encipherment", "server auth", "client auth"), HostedIdentityProperties.INTERNAL_CERTIFICATE_DURATION, renewBefore); diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutService.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutService.java index fdcd0468eb..9b2262d0a9 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutService.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutService.java @@ -44,7 +44,7 @@ public RolloutResult sync( String telnetRevision, String gatewayInternalWsRevision, String grpcRevision, - Map grpcPublicationRevisions, + Map grpcWorkloadIdentityRevisions, Runnable runtimeProfileFence) { if (runtimeProfileFence == null) { throw new IllegalArgumentException("runtime profile guard is required"); @@ -58,8 +58,8 @@ public RolloutResult sync( if (grpcRevision == null) { throw new IllegalArgumentException("gRPC revision is required"); } - if (grpcPublicationRevisions == null) { - throw new IllegalArgumentException("gRPC publication revisions are required"); + if (grpcWorkloadIdentityRevisions == null) { + throw new IllegalArgumentException("gRPC workload identity revisions are required"); } Map> revisionsByDeployment = new LinkedHashMap<>(); revisionsByDeployment @@ -77,10 +77,10 @@ public RolloutResult sync( .computeIfAbsent(consumer, ignored -> new LinkedHashMap<>()) .put(HostedIdentityContract.GRPC_REVISION_ANNOTATION, grpcRevision); } - if (!grpcPublicationRevisions.isEmpty()) { + if (!grpcWorkloadIdentityRevisions.isEmpty()) { for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { String role = HostedIdentityContract.grpcPublicationRole(workload); - String revision = grpcPublicationRevisions.get(role); + String revision = grpcWorkloadIdentityRevisions.get(role); if (revision == null) { throw new IllegalArgumentException("gRPC publication revision is required: " + workload); } @@ -88,6 +88,25 @@ public RolloutResult sync( .computeIfAbsent(workload, ignored -> new LinkedHashMap<>()) .put(HostedIdentityContract.GRPC_REVISION_ANNOTATION, revision); } + String accountRevision = + grpcWorkloadIdentityRevisions.get(HostedIdentityContract.GRPC_ACCOUNT_ROLE); + if (accountRevision == null) { + throw new IllegalArgumentException("Account gRPC workload identity revision is required"); + } + revisionsByDeployment + .computeIfAbsent( + HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD, ignored -> new LinkedHashMap<>()) + .put(HostedIdentityContract.GRPC_REVISION_ANNOTATION, accountRevision); + String gameSessionRevision = + grpcWorkloadIdentityRevisions.get(HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + if (gameSessionRevision == null) { + throw new IllegalArgumentException( + "Game Session gRPC workload identity revision is required"); + } + revisionsByDeployment + .computeIfAbsent( + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD, ignored -> new LinkedHashMap<>()) + .put(HostedIdentityContract.GRPC_REVISION_ANNOTATION, gameSessionRevision); } Map readinessByDeployment = new LinkedHashMap<>(); for (Map.Entry> entry : revisionsByDeployment.entrySet()) { @@ -102,7 +121,7 @@ public RolloutResult sync( } boolean telnetReady = readinessByDeployment.getOrDefault(TCP_PROXY_DEPLOYMENT, false); var grpcConsumers = plan.grpcConsumers().stream(); - if (!grpcPublicationRevisions.isEmpty()) { + if (!grpcWorkloadIdentityRevisions.isEmpty()) { grpcConsumers = java.util.stream.Stream.concat( grpcConsumers, HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream()); diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java index 638b3605f7..dd2db8daae 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java @@ -178,6 +178,10 @@ static List identitySecretNames(EnvironmentIdentityPlan plan) { names.add(plan.grpcPublicationSourceSecretName(workload)); names.add(plan.grpcPublicationSourceSecretName(workload) + "-previous"); } + names.add(plan.grpcAccountSourceSecretName()); + names.add(plan.grpcAccountSourceSecretName() + "-previous"); + names.add(plan.grpcGameSessionSourceSecretName()); + names.add(plan.grpcGameSessionSourceSecretName() + "-previous"); return List.copyOf(names); } @@ -216,6 +220,8 @@ static Role runtimeRole(EnvironmentIdentityPlan plan) { static List requiredDeploymentNames(EnvironmentIdentityPlan plan) { LinkedHashSet names = new LinkedHashSet<>(plan.grpcConsumers()); names.addAll(HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS); + names.add(HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD); + names.add(HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); names.addAll(DeploymentRolloutService.BRIDGE_DEPLOYMENTS); return List.copyOf(names); } @@ -232,6 +238,8 @@ static List requiredCertificateNames(EnvironmentIdentityPlan plan) { HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream() .map(plan::grpcPublicationCertificateName) .toList()); + names.add(plan.grpcAccountCertificateName()); + names.add(plan.grpcGameSessionCertificateName()); return List.copyOf(names); } @@ -248,6 +256,8 @@ static List runtimeSecretNames(EnvironmentIdentityPlan plan) { HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream() .map(plan::grpcPublicationSecretName) .toList()); + names.add(plan.grpcAccountSecretName()); + names.add(plan.grpcGameSessionSecretName()); return List.copyOf(names); } diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java index 8b4cdff374..13c6b9089a 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java @@ -27,14 +27,14 @@ public record EnvironmentIdentityPlan( String grpcIssuer, String caSecretName, List grpcConsumers, - Map grpcPublicationCertificateNames, - Map grpcPublicationSecretNames, - Map grpcPublicationSourceSecretNames) { + Map grpcWorkloadIdentityCertificateNames, + Map grpcWorkloadIdentitySecretNames, + Map grpcWorkloadIdentitySourceSecretNames) { public EnvironmentIdentityPlan { grpcConsumers = List.copyOf(grpcConsumers); - grpcPublicationCertificateNames = Map.copyOf(grpcPublicationCertificateNames); - grpcPublicationSecretNames = Map.copyOf(grpcPublicationSecretNames); - grpcPublicationSourceSecretNames = Map.copyOf(grpcPublicationSourceSecretNames); + grpcWorkloadIdentityCertificateNames = Map.copyOf(grpcWorkloadIdentityCertificateNames); + grpcWorkloadIdentitySecretNames = Map.copyOf(grpcWorkloadIdentitySecretNames); + grpcWorkloadIdentitySourceSecretNames = Map.copyOf(grpcWorkloadIdentitySourceSecretNames); } public String secretName(String role) { @@ -45,8 +45,8 @@ public String secretName(String role) { case HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE -> tcpProxyBridgeSecretName; case HostedIdentityContract.GRPC_ROLE -> grpcSecretName; default -> { - if (HostedIdentityContract.isGrpcPublicationRole(role)) { - String secretName = grpcPublicationSecretNames.get(role); + if (HostedIdentityContract.isGrpcWorkloadIdentityRole(role)) { + String secretName = grpcWorkloadIdentitySecretNames.get(role); if (secretName != null) { yield secretName; } @@ -57,24 +57,57 @@ public String secretName(String role) { } public String grpcPublicationCertificateName(String workload) { - return grpcPublicationCertificateNames.get( + return grpcWorkloadIdentityCertificateNames.get( HostedIdentityContract.grpcPublicationRole(workload)); } public String grpcPublicationSecretName(String workload) { - return grpcPublicationSecretNames.get(HostedIdentityContract.grpcPublicationRole(workload)); + return grpcWorkloadIdentitySecretNames.get( + HostedIdentityContract.grpcPublicationRole(workload)); } public String grpcPublicationSourceSecretName(String workload) { - return grpcPublicationSourceSecretNames.get( + return grpcWorkloadIdentitySourceSecretNames.get( HostedIdentityContract.grpcPublicationRole(workload)); } + public String grpcAccountCertificateName() { + return grpcWorkloadIdentityCertificateNames.get(HostedIdentityContract.GRPC_ACCOUNT_ROLE); + } + + public String grpcAccountSecretName() { + return grpcWorkloadIdentitySecretNames.get(HostedIdentityContract.GRPC_ACCOUNT_ROLE); + } + + public String grpcAccountSourceSecretName() { + return grpcWorkloadIdentitySourceSecretNames.get(HostedIdentityContract.GRPC_ACCOUNT_ROLE); + } + + public String grpcGameSessionCertificateName() { + return grpcWorkloadIdentityCertificateNames.get(HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + } + + public String grpcGameSessionSecretName() { + return grpcWorkloadIdentitySecretNames.get(HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + } + + public String grpcGameSessionSourceSecretName() { + return grpcWorkloadIdentitySourceSecretNames.get(HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + } + public String grpcPublicationUriSan(String workload) { - return "spiffe://firemud/ns/" + runtimeNamespace + "/sa/" + workload; + return grpcWorkloadIdentityUriSan(workload); } public List grpcPublicationDnsNames(String workload) { + return grpcWorkloadIdentityDnsNames(workload); + } + + public String grpcWorkloadIdentityUriSan(String workload) { + return "spiffe://firemud/ns/" + runtimeNamespace + "/sa/" + workload; + } + + public List grpcWorkloadIdentityDnsNames(String workload) { return List.of( workload, workload + "." + runtimeNamespace, @@ -106,8 +139,8 @@ public EnvironmentIdentityPlan withGrpcConsumers(List consumers) { grpcIssuer, caSecretName, consumers, - grpcPublicationCertificateNames, - grpcPublicationSecretNames, - grpcPublicationSourceSecretNames); + grpcWorkloadIdentityCertificateNames, + grpcWorkloadIdentitySecretNames, + grpcWorkloadIdentitySourceSecretNames); } } diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java index 217748fa76..c7183a82b1 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java @@ -165,6 +165,12 @@ public UpdateControl reconcile( materialRequests.add( new RoleMaterialRequest(role, () -> materialization.grpcPublication(workload))); } + materialRequests.add( + new RoleMaterialRequest( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, materialization::grpcAccount)); + materialRequests.add( + new RoleMaterialRequest( + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, materialization::grpcGameSession)); List rolePipeline = new ArrayList<>(); for (RoleMaterialRequest request : materialRequests) { CertificateMaterialService.RoleMaterial material = request.material().get(); @@ -225,11 +231,17 @@ public UpdateControl reconcile( beforeRollout.profile(), roleMaterials); } - Map publicationRevisions = new LinkedHashMap<>(); + Map workloadIdentityRevisions = new LinkedHashMap<>(); for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { String role = HostedIdentityContract.grpcPublicationRole(workload); - publicationRevisions.put(role, projections.get(role).revision()); + workloadIdentityRevisions.put(role, projections.get(role).revision()); } + workloadIdentityRevisions.put( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + projections.get(HostedIdentityContract.GRPC_ACCOUNT_ROLE).revision()); + workloadIdentityRevisions.put( + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + projections.get(HostedIdentityContract.GRPC_GAME_SESSION_ROLE).revision()); DeploymentRolloutService.RolloutResult rollout = deploymentRolloutService.sync( client, @@ -237,7 +249,7 @@ public UpdateControl reconcile( projections.get(HostedIdentityContract.TELNET_ROLE).revision(), projections.get(HostedIdentityContract.GATEWAY_INTERNAL_WS_ROLE).revision(), projections.get(HostedIdentityContract.GRPC_ROLE).revision(), - publicationRevisions, + workloadIdentityRevisions, () -> assertRuntimeProfileCurrent(plan, runtimeProfile, "rollout mutation")); ServedEnvironmentProbe.ProbeResult probes; if (rollout.ready()) { @@ -487,13 +499,15 @@ private static RoleMaterials of(CertificateMaterialService.RoleMaterial... mater HostedIdentityContract.TELNET_ROLE, HostedIdentityContract.GATEWAY_INTERNAL_WS_ROLE, HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE, - HostedIdentityContract.GRPC_ROLE -> { + HostedIdentityContract.GRPC_ROLE, + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE -> { if (materialsByRole.putIfAbsent(role, material) != null) { throw new IllegalArgumentException("duplicate identity material role: " + role); } } default -> { - if (HostedIdentityContract.isGrpcPublicationRole(role)) { + if (HostedIdentityContract.isGrpcWorkloadIdentityRole(role)) { if (materialsByRole.putIfAbsent(role, material) != null) { throw new IllegalArgumentException("duplicate identity material role: " + role); } @@ -517,14 +531,21 @@ private CertificateMaterialService.RoleMaterial material(String role) { return materialsByRole.get(role); } - private boolean publicationEvidenceComplete() { + private boolean workloadIdentityEvidenceComplete() { return HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream() - .map(HostedIdentityContract::grpcPublicationRole) - .allMatch( - role -> { - CertificateMaterialService.RoleMaterial material = materialsByRole.get(role); - return material != null && material.ready(); - }); + .map(HostedIdentityContract::grpcPublicationRole) + .allMatch( + role -> { + CertificateMaterialService.RoleMaterial material = materialsByRole.get(role); + return material != null && material.ready(); + }) + && roleReady(HostedIdentityContract.GRPC_ACCOUNT_ROLE) + && roleReady(HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + } + + private boolean roleReady(String role) { + CertificateMaterialService.RoleMaterial material = materialsByRole.get(role); + return material != null && material.ready(); } } @@ -882,17 +903,21 @@ private boolean deleteOwnedMaterial(EnvironmentIdentityPlan plan) { plan.gatewayInternalWsSecretName() + "-previous", plan.tcpProxyBridgeSecretName() + "-previous", plan.grpcSecretName() + "-previous"); - List publicationSecretNames = - HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream() - .flatMap( - workload -> - java.util.stream.Stream.of( - plan.grpcPublicationSourceSecretName(workload), - plan.grpcPublicationSourceSecretName(workload) + "-previous")) - .toList(); + List workloadSecretNames = + new ArrayList<>( + HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream() + .flatMap( + workload -> + java.util.stream.Stream.of( + plan.grpcPublicationSourceSecretName(workload), + plan.grpcPublicationSourceSecretName(workload) + "-previous")) + .toList()); + workloadSecretNames.add(plan.grpcAccountSourceSecretName()); + workloadSecretNames.add(plan.grpcAccountSourceSecretName() + "-previous"); + workloadSecretNames.add(plan.grpcGameSessionSourceSecretName()); + workloadSecretNames.add(plan.grpcGameSessionSourceSecretName() + "-previous"); secretNames = - java.util.stream.Stream.concat(secretNames.stream(), publicationSecretNames.stream()) - .toList(); + java.util.stream.Stream.concat(secretNames.stream(), workloadSecretNames.stream()).toList(); List ownedSecretNames = new ArrayList<>(); for (String name : secretNames) { Secret secret = client.secrets().inNamespace(plan.identityNamespace()).withName(name).get(); @@ -910,11 +935,15 @@ private boolean deleteOwnedMaterial(EnvironmentIdentityPlan plan) { plan.telnetCertificateName(), plan.gatewayInternalWsCertificateName(), plan.tcpProxyBridgeCertificateName()); + List workloadCertificateNames = + new ArrayList<>( + HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream() + .map(plan::grpcPublicationCertificateName) + .toList()); + workloadCertificateNames.add(plan.grpcAccountCertificateName()); + workloadCertificateNames.add(plan.grpcGameSessionCertificateName()); certificateNames = - java.util.stream.Stream.concat( - certificateNames.stream(), - HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream() - .map(plan::grpcPublicationCertificateName)) + java.util.stream.Stream.concat(certificateNames.stream(), workloadCertificateNames.stream()) .toList(); List ownedCertificateNames = new ArrayList<>(); for (String name : certificateNames) { @@ -1056,11 +1085,12 @@ private UpdateControl status( boolean ready, RuntimeProfileService.RuntimeProfile profile, RoleMaterials materials) { - if (ready && !materials.publicationEvidenceComplete()) { + if (ready && !materials.workloadIdentityEvidenceComplete()) { ready = false; phase = HostedEnvironmentIdentityStatus.Phase.Verifying; - reason = "PublicationIdentityEvidenceIncomplete"; - message = "all five protected publication identity proofs are required for readiness"; + reason = "WorkloadIdentityEvidenceIncomplete"; + message = + "the five protected publication, exact Account, and Game Session workload identity proofs are required for readiness"; } resource.setStatus( statusService.status( @@ -1109,7 +1139,7 @@ private static HostedEnvironmentIdentityStatus.RoleStatus roleStatus( private static HostedEnvironmentIdentityStatus.RoleStatus previousRole( HostedEnvironmentIdentity resource, String role) { - if (HostedIdentityContract.isGrpcPublicationRole(role)) { + if (HostedIdentityContract.isGrpcWorkloadIdentityRole(role)) { return null; } if (resource.getStatus() == null) return null; diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlanner.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlanner.java index c026a27fe8..d8b62306d7 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlanner.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlanner.java @@ -66,6 +66,24 @@ public EnvironmentIdentityPlan plan(String name) { publicationSourceSecrets.put(role, sourceName); publicationSecrets.put(role, "firemud-grpc-" + workload); } + publicationCertificates.put( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + materialPrefix + "-grpc-" + HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD); + publicationSourceSecrets.put( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + materialPrefix + "-grpc-" + HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD); + publicationSecrets.put( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + "firemud-grpc-" + HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD); + publicationCertificates.put( + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + materialPrefix + "-grpc-" + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); + publicationSourceSecrets.put( + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + materialPrefix + "-grpc-" + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); + publicationSecrets.put( + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + "firemud-grpc-" + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); return new EnvironmentIdentityPlan( name, properties.getControlNamespace(), diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java index 739ea5508e..08c09621ac 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java @@ -445,7 +445,9 @@ void materializationBatchReusesOneRotationSelectionSnapshot() { plan.grpcPublicationSecretName("world-management-service"), plan.grpcPublicationSecretName("entity-management-service"), plan.grpcPublicationSecretName("game-logic-service"), - plan.grpcPublicationSecretName("automation-scripting-service")), + plan.grpcPublicationSecretName("automation-scripting-service"), + plan.grpcAccountSecretName(), + plan.grpcGameSessionSecretName()), java.util.Set.copyOf(read.getAllValues())); clearInvocations(runtimeSecrets); @@ -1709,6 +1711,45 @@ void grpcUsesTheAcceptedProjectionWithoutRereadingTheDeferredSource() { when(secretClient.identitySecrets().withName(sourceName)).thenReturn(sourceResource); when(sourceResource.get()).thenReturn(certManagerSource(plan, role, sourceName, data)); } + String accountRole = HostedIdentityContract.GRPC_ACCOUNT_ROLE; + String accountName = plan.grpcAccountSecretName(); + String accountSourceName = plan.grpcAccountSourceSecretName(); + String accountRevision = SecretProjectionService.revisionForRole(accountRole, data); + Resource accountProjectionResource = mock(Resource.class); + when(secretClient.runtimeSecrets().withName(accountName)).thenReturn(accountProjectionResource); + when(accountProjectionResource.get()) + .thenReturn( + ownedSecret( + plan, + accountRole, + accountName, + data, + acceptedAnnotations(accountRevision, "1".repeat(64)))); + Resource accountSourceResource = mock(Resource.class); + when(secretClient.identitySecrets().withName(accountSourceName)) + .thenReturn(accountSourceResource); + when(accountSourceResource.get()) + .thenReturn(certManagerSource(plan, accountRole, accountSourceName, data)); + String gameSessionRole = HostedIdentityContract.GRPC_GAME_SESSION_ROLE; + String gameSessionName = plan.grpcGameSessionSecretName(); + String gameSessionSourceName = plan.grpcGameSessionSourceSecretName(); + String gameSessionRevision = SecretProjectionService.revisionForRole(gameSessionRole, data); + Resource gameSessionProjectionResource = mock(Resource.class); + when(secretClient.runtimeSecrets().withName(gameSessionName)) + .thenReturn(gameSessionProjectionResource); + when(gameSessionProjectionResource.get()) + .thenReturn( + ownedSecret( + plan, + gameSessionRole, + gameSessionName, + data, + acceptedAnnotations(gameSessionRevision, "1".repeat(64)))); + Resource gameSessionSourceResource = mock(Resource.class); + when(secretClient.identitySecrets().withName(gameSessionSourceName)) + .thenReturn(gameSessionSourceResource); + when(gameSessionSourceResource.get()) + .thenReturn(certManagerSource(plan, gameSessionRole, gameSessionSourceName, data)); Secret ownedGrpc = ownedSecret(plan, HostedIdentityContract.GRPC_ROLE, plan.grpcSecretName(), data, Map.of()); Resource grpcSourceResource = mock(Resource.class); diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java index 9598adf44a..9a89e06d9f 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java @@ -131,6 +131,60 @@ void publicationCertificateUsesStableSourceNameAndBidirectionalWorkloadIdentity( certificateSpec, plan, HostedIdentityContract.grpcPublicationRole("game-design-service")); } + @Test + void accountCertificateUsesExactStableWorkloadIdentity() { + var properties = propertiesWithRenewBefore(); + var plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); + var certificate = + new CertificateResourceFactory().grpcAccount(plan, properties.getGrpcRenewBefore()); + var certificateSpec = spec(certificate); + + assertEquals("pr-42-grpc-account-service", certificate.getMetadata().getName()); + assertEquals("pr-42-grpc-account-service", certificateSpec.get("secretName")); + assertEquals("firemud-ca-issuer", issuerName(certificateSpec)); + assertEquals( + java.util.List.of("spiffe://firemud/ns/pr-42/sa/account-service"), + certificateSpec.get("uris")); + assertEquals( + java.util.List.of( + "account-service", + "account-service.pr-42", + "account-service.pr-42.svc", + "account-service.pr-42.svc.cluster.local"), + certificateSpec.get("dnsNames")); + assertEquals( + java.util.List.of("digital signature", "key encipherment", "server auth", "client auth"), + certificateSpec.get("usages")); + assertSecretTemplate(certificateSpec, plan, HostedIdentityContract.GRPC_ACCOUNT_ROLE); + } + + @Test + void gameSessionCertificateUsesExactStableWorkloadIdentity() { + var properties = propertiesWithRenewBefore(); + var plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); + var certificate = + new CertificateResourceFactory().grpcGameSession(plan, properties.getGrpcRenewBefore()); + var certificateSpec = spec(certificate); + + assertEquals("pr-42-grpc-game-session-service", certificate.getMetadata().getName()); + assertEquals("pr-42-grpc-game-session-service", certificateSpec.get("secretName")); + assertEquals("firemud-ca-issuer", issuerName(certificateSpec)); + assertEquals( + java.util.List.of("spiffe://firemud/ns/pr-42/sa/game-session-service"), + certificateSpec.get("uris")); + assertEquals( + java.util.List.of( + "game-session-service", + "game-session-service.pr-42", + "game-session-service.pr-42.svc", + "game-session-service.pr-42.svc.cluster.local"), + certificateSpec.get("dnsNames")); + assertEquals( + java.util.List.of("digital signature", "key encipherment", "server auth", "client auth"), + certificateSpec.get("usages")); + assertSecretTemplate(certificateSpec, plan, HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + } + @Test void certificateFactoryPublicSurfaceContainsOnlyMaterialFactories() { var declaredMethods = @@ -142,10 +196,16 @@ void certificateFactoryPublicSurfaceContainsOnlyMaterialFactories() { .filter(method -> java.lang.reflect.Modifier.isPublic(method.getModifiers())) .toList(); - assertEquals(5, publicMethods.size()); + assertEquals(7, publicMethods.size()); assertEquals( java.util.Set.of( - "ingress", "telnet", "gatewayInternalWs", "tcpProxyBridge", "grpcPublication"), + "ingress", + "telnet", + "gatewayInternalWs", + "tcpProxyBridge", + "grpcPublication", + "grpcAccount", + "grpcGameSession"), publicMethods.stream() .map(java.lang.reflect.Method::getName) .collect(java.util.stream.Collectors.toUnmodifiableSet())); diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java index 7858d73dc4..75f149d0bd 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java @@ -56,13 +56,14 @@ void mixedRevisionEditPreservesCurrentRoleAndUpdatesOnlyStaleRole() { } @Test - void publicationRevisionRollsEachProtectedDeploymentAndBlocksReadinessUntilAllReady() { + void workloadIdentityRevisionRollsAccountAndPublicationDeploymentsUntilAllReady() { EnvironmentIdentityPlan plan = planWithConsumers("account-service"); DeploymentClientGraph graph = deploymentClient( plan, "tcp-proxy-service", "account-service", + "game-session-service", "game-design-service", "world-management-service", "entity-management-service", @@ -78,8 +79,17 @@ void publicationRevisionRollsEachProtectedDeploymentAndBlocksReadinessUntilAllRe .thenReturn( readyDeployment( "account-service", - Map.of(HostedIdentityContract.GRPC_REVISION_ANNOTATION, "grpc-current"), + Map.of(HostedIdentityContract.GRPC_REVISION_ANNOTATION, "account-old"), + 3L)); + when(graph.resources().get("game-session-service").get()) + .thenReturn( + readyDeployment( + "game-session-service", + Map.of(HostedIdentityContract.GRPC_REVISION_ANNOTATION, "game-session-current"), 3L)); + ReplaceDeletable lockedAccount = mock(ReplaceDeletable.class); + when(graph.resources().get("account-service").lockResourceVersion("rv-3")) + .thenReturn(lockedAccount); for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { String revision = "game-logic-service".equals(workload) ? "publication-old" : "publication-current"; @@ -92,11 +102,14 @@ void publicationRevisionRollsEachProtectedDeploymentAndBlocksReadinessUntilAllRe when(graph.resources().get("game-logic-service").lockResourceVersion("rv-3")) .thenReturn(lockedGameLogic); - Map publicationRevisions = new LinkedHashMap<>(); + Map workloadIdentityRevisions = new LinkedHashMap<>(); for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { - publicationRevisions.put( + workloadIdentityRevisions.put( HostedIdentityContract.grpcPublicationRole(workload), "publication-current"); } + workloadIdentityRevisions.put(HostedIdentityContract.GRPC_ACCOUNT_ROLE, "account-current"); + workloadIdentityRevisions.put( + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, "game-session-current"); DeploymentRolloutService.RolloutResult result = new DeploymentRolloutService() .sync( @@ -105,7 +118,7 @@ void publicationRevisionRollsEachProtectedDeploymentAndBlocksReadinessUntilAllRe "telnet-current", "gateway-current", "grpc-current", - publicationRevisions, + workloadIdentityRevisions, () -> {}); assertEquals(false, result.ready()); @@ -122,6 +135,17 @@ void publicationRevisionRollsEachProtectedDeploymentAndBlocksReadinessUntilAllRe .getMetadata() .getAnnotations() .get(HostedIdentityContract.GRPC_REVISION_ANNOTATION)); + ArgumentCaptor accountReplacement = ArgumentCaptor.forClass(Deployment.class); + verify(lockedAccount).replace(accountReplacement.capture()); + assertEquals( + "account-current", + accountReplacement + .getValue() + .getSpec() + .getTemplate() + .getMetadata() + .getAnnotations() + .get(HostedIdentityContract.GRPC_REVISION_ANNOTATION)); } @Test diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java index ad84f7daa1..6366c0e698 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java @@ -233,7 +233,9 @@ void identityRoleNamesOnlyCoverCertManagerCertificates() { "pr-42-grpc-world-management-service", "pr-42-grpc-entity-management-service", "pr-42-grpc-game-logic-service", - "pr-42-grpc-automation-scripting-service"), + "pr-42-grpc-automation-scripting-service", + "pr-42-grpc-account-service", + "pr-42-grpc-game-session-service"), HostedIdentityScopeService.requiredCertificateNames(plan)); } @@ -249,6 +251,8 @@ void runtimeRoleCoversBothBridgeDeploymentsAndEveryGrpcConsumer() { "entity-management-service", "game-logic-service", "automation-scripting-service", + "account-service", + "game-session-service", "spring-cloud-gateway", "tcp-proxy-service"), HostedIdentityScopeService.requiredDeploymentNames(plan)); diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityTestFixtures.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityTestFixtures.java index a025e2e273..aa752e9f9a 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityTestFixtures.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityTestFixtures.java @@ -45,7 +45,7 @@ static Secret certManagerSource( HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE -> plan.grpcIssuer(); default -> { - if (HostedIdentityContract.isGrpcPublicationRole(role)) { + if (HostedIdentityContract.isGrpcWorkloadIdentityRole(role)) { yield plan.grpcIssuer(); } throw new IllegalArgumentException("unsupported cert-manager role: " + role); @@ -354,6 +354,34 @@ static StableBatchFixture stableBatchFixture() { .getAnnotations() .put(HostedIdentityContract.PROVENANCE_ANNOTATION, "cert-manager"); } + stubProjectionAndSource( + secretClient, + plan, + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + acceptedData, + acceptedData, + acceptedData); + secretClient + .runtimeSecrets() + .withName(secretName(plan, HostedIdentityContract.GRPC_ACCOUNT_ROLE)) + .get() + .getMetadata() + .getAnnotations() + .put(HostedIdentityContract.PROVENANCE_ANNOTATION, "cert-manager"); + stubProjectionAndSource( + secretClient, + plan, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + acceptedData, + acceptedData, + acceptedData); + secretClient + .runtimeSecrets() + .withName(secretName(plan, HostedIdentityContract.GRPC_GAME_SESSION_ROLE)) + .get() + .getMetadata() + .getAnnotations() + .put(HostedIdentityContract.PROVENANCE_ANNOTATION, "cert-manager"); SecretMaterialValidator validator = mock(SecretMaterialValidator.class); SecretMaterialValidator.MaterialSummary summary = new SecretMaterialValidator.MaterialSummary( @@ -464,6 +492,12 @@ static String secretName(EnvironmentIdentityPlan plan, String role) { case HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE -> plan.tcpProxyBridgeSecretName(); case HostedIdentityContract.GRPC_ROLE -> plan.grpcSecretName(); default -> { + if (HostedIdentityContract.GRPC_ACCOUNT_ROLE.equals(role)) { + yield plan.grpcAccountSecretName(); + } + if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { + yield plan.grpcGameSessionSecretName(); + } if (HostedIdentityContract.isGrpcPublicationRole(role)) { yield plan.grpcPublicationSecretName( role.substring(HostedIdentityContract.GRPC_PUBLICATION_ROLE_PREFIX.length())); @@ -474,6 +508,12 @@ static String secretName(EnvironmentIdentityPlan plan, String role) { } static String sourceSecretName(EnvironmentIdentityPlan plan, String role) { + if (HostedIdentityContract.GRPC_ACCOUNT_ROLE.equals(role)) { + return plan.grpcAccountSourceSecretName(); + } + if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { + return plan.grpcGameSessionSourceSecretName(); + } if (HostedIdentityContract.isGrpcPublicationRole(role)) { return plan.grpcPublicationSourceSecretName( role.substring(HostedIdentityContract.GRPC_PUBLICATION_ROLE_PREFIX.length())); diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java index 23d44318eb..67063f1a65 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java @@ -1344,6 +1344,12 @@ void caRotationValidatesOnlyTheSelectedNewSourceAndPinsOtherSharedRoles() { acceptedData, acceptedData); } + for (String role : + List.of( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE)) { + stubProjectionAndSource(secretClient, plan, role, acceptedData, acceptedData, acceptedData); + } stubCertificate( secretClient.client(), plan, @@ -1519,6 +1525,12 @@ private static DriftSelectionFixture driftSelectionFixture(boolean sourceAdvance acceptedData, acceptedData); } + for (String role : + List.of( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE)) { + stubProjectionAndSource(secretClient, plan, role, acceptedData, acceptedData, acceptedData); + } stubCertificate( secretClient.client(), plan, diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java index 62de51648e..adcdc4c6a1 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java @@ -172,7 +172,7 @@ void projectionAcceptanceStatusUsesTheFirstUnsyncedProjection() { } @Test - void protectedPublicationProjectionMustBeAcceptedBeforeReadiness() { + void accountAndPublicationProjectionsMustBeAcceptedBeforeReadiness() { List projections = new java.util.ArrayList<>( java.util.stream.Stream.concat( @@ -182,13 +182,17 @@ void protectedPublicationProjectionMustBeAcceptedBeforeReadiness() { SecretProjectionService.ProjectionResult.synced("gateway"), SecretProjectionService.ProjectionResult.synced("bridge"), SecretProjectionService.ProjectionResult.synced("grpc")), - HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream() - .map( - workload -> - "game-logic-service".equals(workload) - ? SecretProjectionService.ProjectionResult.awaiting( - "predecessor-not-accepted", workload) - : SecretProjectionService.ProjectionResult.synced(workload))) + java.util.stream.Stream.concat( + HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.stream() + .map( + workload -> + "game-logic-service".equals(workload) + ? SecretProjectionService.ProjectionResult.awaiting( + "predecessor-not-accepted", workload) + : SecretProjectionService.ProjectionResult.synced( + workload)), + java.util.stream.Stream.of( + SecretProjectionService.ProjectionResult.synced("account-service")))) .toList()); assertReadinessStatus( @@ -1731,6 +1735,10 @@ private DeploymentHeadGateFixture(RuntimeProfileService.RuntimeProfile runtimePr "4", SERIALIZED_DEFERRED_DRIFT)); when(batch.grpc(any())).thenReturn(material(plan, HostedIdentityContract.GRPC_ROLE, "5")); + when(batch.grpcAccount()) + .thenReturn(material(plan, HostedIdentityContract.GRPC_ACCOUNT_ROLE, "b")); + when(batch.grpcGameSession()) + .thenReturn(material(plan, HostedIdentityContract.GRPC_GAME_SESSION_ROLE, "c")); when(batch.grpcPublication(anyString())) .thenAnswer( invocation -> { diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java index 4393731dc0..5136dcc3db 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java @@ -48,6 +48,20 @@ void derivesPreviewTargetsFromOnlyTheClosedNameContract() { assertEquals( "spiffe://firemud/ns/pr-42/sa/game-design-service", plan.grpcPublicationUriSan("game-design-service")); + assertEquals("pr-42-grpc-account-service", plan.grpcAccountCertificateName()); + assertEquals("pr-42-grpc-account-service", plan.grpcAccountSourceSecretName()); + assertEquals("firemud-grpc-account-service", plan.grpcAccountSecretName()); + assertEquals( + plan.grpcAccountSecretName(), plan.secretName(HostedIdentityContract.GRPC_ACCOUNT_ROLE)); + assertEquals("pr-42-grpc-game-session-service", plan.grpcGameSessionCertificateName()); + assertEquals("pr-42-grpc-game-session-service", plan.grpcGameSessionSourceSecretName()); + assertEquals("firemud-grpc-game-session-service", plan.grpcGameSessionSecretName()); + assertEquals( + "spiffe://firemud/ns/pr-42/sa/game-session-service", + plan.grpcWorkloadIdentityUriSan(HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD)); + assertEquals( + plan.grpcGameSessionSecretName(), + plan.secretName(HostedIdentityContract.GRPC_GAME_SESSION_ROLE)); } @Test From 4d78fab93ae018a5ff813c59f26cb4b93073ee1d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 15:54:12 +1300 Subject: [PATCH 02/75] Retain workload identity high-water and preflight proof --- dev-tools/deploy/preflight.py | 215 ++++++++++-------- ...d-identity-controller-manifest-contract.sh | 6 +- dev-tools/tests/preflight-contract.sh | 206 +++++++++++++++-- k8s/base/grpc-bootstrap.example.yaml | 4 + k8s/hosted-identity-controller/README.md | 6 +- k8s/hosted-identity-controller/crd.yaml | 2 + .../HostedEnvironmentIdentityStatus.java | 18 ++ .../reconcile/HostedIdentityReconciler.java | 13 +- .../HostedIdentityReconcilerSafetyTest.java | 182 +++++++++++++++ 9 files changed, 539 insertions(+), 113 deletions(-) diff --git a/dev-tools/deploy/preflight.py b/dev-tools/deploy/preflight.py index e2168d3fd2..d114be2bf8 100644 --- a/dev-tools/deploy/preflight.py +++ b/dev-tools/deploy/preflight.py @@ -146,7 +146,15 @@ def _hosted_bridge_secret_ready_attempts_for_timeout(timeout_seconds: int) -> in "game-logic-service", "automation-scripting-service", ) -PUBLICATION_GRPC_LEAF_SECRET_KEYS = {"tls.crt", "tls.key", "ca.crt"} +ACCOUNT_GAME_SESSION_GRPC_WORKLOADS = ( + "account-service", + "game-session-service", +) +GRPC_WORKLOAD_SECRET_CONSUMERS = ( + *PUBLICATION_GRPC_WORKLOADS, + *ACCOUNT_GAME_SESSION_GRPC_WORKLOADS, +) +GRPC_WORKLOAD_LEAF_SECRET_KEYS = {"tls.crt", "tls.key", "ca.crt"} PUBLICATION_GRPC_TRUST_SECRET_NAME = "firemud-grpc-tls" PUBLICATION_GRPC_TRUST_SECRET_KEYS = {"ca.crt"} BASE_SECRET_COMPLIANCE_CLASSES = frozenset( @@ -938,13 +946,13 @@ def publication_workload_secret_requirements( expected: dict[str, Any], documents: list[dict[str, Any]], ) -> tuple[tuple[str, str, set[str]], ...]: - """Resolve each publication leaf Secret and its shared CA trust Secret.""" + """Resolve workload leaf Secrets and the shared publication CA trust Secret.""" expected_namespace = secret_binding_namespace( get(expected, "internalBindings.postgres.credentialsRef") ) if expected_namespace is None: raise ValueError( - "Cannot resolve publication workload Secret namespace from internalBindings.postgres.credentialsRef" + "Cannot resolve gRPC workload Secret namespace from internalBindings.postgres.credentialsRef" ) workload_mtls_ref = parse_binding_ref( get(expected, "internalBindings.certificates.workloadMtlsRef") @@ -963,7 +971,11 @@ def publication_workload_secret_requirements( workload_mtls_secret_name = workload_mtls_ref[2][0] requirements: list[tuple[str, str, set[str]]] = [] leaf_secret_names: list[str] = [] - for workload in PUBLICATION_GRPC_WORKLOADS: + for workload in GRPC_WORKLOAD_SECRET_CONSUMERS: + is_publication_workload = workload in PUBLICATION_GRPC_WORKLOADS + workload_label = ( + "publication workload" if is_publication_workload else "gRPC workload" + ) deployments = [ document for document in documents @@ -973,25 +985,25 @@ def publication_workload_secret_requirements( ] if len(deployments) != 1: raise ValueError( - f"Expected exactly one rendered Deployment for publication workload {workload}; found {len(deployments)}" + f"Expected exactly one rendered Deployment for {workload_label} {workload}; found {len(deployments)}" ) deployment = deployments[0] metadata = deployment["metadata"] workload_namespace = metadata.get("namespace", expected_namespace) if not isinstance(workload_namespace, str) or not workload_namespace.strip(): raise ValueError( - f"Rendered publication workload {workload} has an invalid namespace" + f"Rendered {workload_label} {workload} has an invalid namespace" ) if workload_namespace != expected_namespace: raise ValueError( - f"Rendered publication workload {workload} namespace {workload_namespace} " + f"Rendered {workload_label} {workload} namespace {workload_namespace} " f"does not match expected Secret namespace {expected_namespace}" ) pod_spec = get(deployment, "spec.template.spec") volumes = pod_spec.get("volumes") if isinstance(pod_spec, dict) else None if not isinstance(volumes, list): raise TypeError( - f"Rendered publication workload {workload} has no valid pod volumes list" + f"Rendered {workload_label} {workload} has no valid pod volumes list" ) grpc_volumes = [ volume @@ -1005,97 +1017,114 @@ def publication_workload_secret_requirements( ] if len(grpc_volumes) != 1: raise ValueError( - f"Expected exactly one grpc-tls volume for publication workload {workload}; found {len(grpc_volumes)}" + f"Expected exactly one grpc-tls volume for {workload_label} {workload}; found {len(grpc_volumes)}" ) - if len(trust_volumes) != 1: + if is_publication_workload and len(trust_volumes) != 1: raise ValueError( - f"Expected exactly one grpc-trust volume for publication workload {workload}; found {len(trust_volumes)}" + f"Expected exactly one grpc-trust volume for {workload_label} {workload}; found {len(trust_volumes)}" + ) + if not is_publication_workload and trust_volumes: + raise ValueError( + f"Rendered {workload_label} {workload} must mount its CA from the leaf Secret, not grpc-trust" ) grpc_volume = grpc_volumes[0] secret = grpc_volume.get("secret") secret_name = secret.get("secretName") if isinstance(secret, dict) else None expected_leaf_items = {("tls.crt", "tls.crt"), ("tls.key", "tls.key")} leaf_items = secret.get("items") if isinstance(secret, dict) else None + if is_publication_workload: + leaf_projection_is_valid = ( + isinstance(leaf_items, list) + and len(leaf_items) == len(expected_leaf_items) + and all( + isinstance(item, dict) + and set(item) == {"key", "path"} + and isinstance(item.get("key"), str) + and isinstance(item.get("path"), str) + for item in leaf_items + ) + and { + (item["key"], item["path"]) + for item in leaf_items + if isinstance(item, dict) + } + == expected_leaf_items + ) + else: + # The Account and Game Session Kustomize volumes intentionally project the + # complete cert-manager Secret, including ca.crt, into /tls. + leaf_projection_is_valid = isinstance(secret, dict) and "items" not in secret if ( not isinstance(secret, dict) or not isinstance(secret_name, str) or not secret_name.strip() or secret_name != secret_name.strip() - or not set(secret).issubset({"secretName", "defaultMode", "items"}) + or not set(secret).issubset( + {"secretName", "defaultMode", "items"} + if is_publication_workload + else {"secretName", "defaultMode"} + ) or set(grpc_volume) != {"name", "secret"} - or not isinstance(leaf_items, list) - or len(leaf_items) != len(expected_leaf_items) - or any( - not isinstance(item, dict) - or set(item) != {"key", "path"} - or not isinstance(item.get("key"), str) - or not isinstance(item.get("path"), str) - for item in leaf_items - ) - or { - (item["key"], item["path"]) - for item in leaf_items - if isinstance(item, dict) - } - != expected_leaf_items + or not leaf_projection_is_valid ): raise ValueError( - f"Rendered publication workload {workload} has a malformed grpc-tls Secret volume" + f"Rendered {workload_label} {workload} has a malformed grpc-tls Secret volume" ) if secret_name == workload_mtls_secret_name: raise ValueError( - f"Rendered publication workload {workload} grpc-tls Secret must be distinct from " + f"Rendered {workload_label} {workload} grpc-tls Secret must be distinct from " f"the workload mTLS Secret {workload_mtls_secret_name}" ) if secret_name == PUBLICATION_GRPC_TRUST_SECRET_NAME: raise ValueError( - f"Rendered publication workload {workload} grpc-tls Secret must not use the " + f"Rendered {workload_label} {workload} grpc-tls Secret must not use the " "shared trust Secret firemud-grpc-tls" ) expected_leaf_secret_name = f"firemud-grpc-{workload}" if secret_name != expected_leaf_secret_name: raise ValueError( - f"Rendered publication workload {workload} grpc-tls Secret must be " + f"Rendered {workload_label} {workload} grpc-tls Secret must be " f"{expected_leaf_secret_name}; found {secret_name}" ) - trust_volume = trust_volumes[0] - trust_secret = trust_volume.get("secret") - trust_secret_name = ( - trust_secret.get("secretName") if isinstance(trust_secret, dict) else None - ) - expected_trust_items = {("ca.crt", "ca.crt")} - trust_items = trust_secret.get("items") if isinstance(trust_secret, dict) else None - if ( - not isinstance(trust_secret, dict) - or trust_secret_name != PUBLICATION_GRPC_TRUST_SECRET_NAME - or not set(trust_secret).issubset({"secretName", "defaultMode", "items"}) - or set(trust_volume) != {"name", "secret"} - or not isinstance(trust_items, list) - or len(trust_items) != len(expected_trust_items) - or any( - not isinstance(item, dict) - or set(item) != {"key", "path"} - or not isinstance(item.get("key"), str) - or not isinstance(item.get("path"), str) - for item in trust_items - ) - or { - (item["key"], item["path"]) - for item in trust_items - if isinstance(item, dict) - } - != expected_trust_items - ): - raise ValueError( - f"Rendered publication workload {workload} requires the shared CA-only " - f"Secret {PUBLICATION_GRPC_TRUST_SECRET_NAME} in its grpc-trust volume" + if is_publication_workload: + trust_volume = trust_volumes[0] + trust_secret = trust_volume.get("secret") + trust_secret_name = ( + trust_secret.get("secretName") if isinstance(trust_secret, dict) else None ) + expected_trust_items = {("ca.crt", "ca.crt")} + trust_items = trust_secret.get("items") if isinstance(trust_secret, dict) else None + if ( + not isinstance(trust_secret, dict) + or trust_secret_name != PUBLICATION_GRPC_TRUST_SECRET_NAME + or not set(trust_secret).issubset({"secretName", "defaultMode", "items"}) + or set(trust_volume) != {"name", "secret"} + or not isinstance(trust_items, list) + or len(trust_items) != len(expected_trust_items) + or any( + not isinstance(item, dict) + or set(item) != {"key", "path"} + or not isinstance(item.get("key"), str) + or not isinstance(item.get("path"), str) + for item in trust_items + ) + or { + (item["key"], item["path"]) + for item in trust_items + if isinstance(item, dict) + } + != expected_trust_items + ): + raise ValueError( + f"Rendered {workload_label} {workload} requires the shared CA-only " + f"Secret {PUBLICATION_GRPC_TRUST_SECRET_NAME} in its grpc-trust volume" + ) containers = pod_spec.get("containers") if not isinstance(containers, list): raise TypeError( - f"Rendered publication workload {workload} has no valid pod containers list" + f"Rendered {workload_label} {workload} has no valid pod containers list" ) workload_containers = [ container @@ -1104,7 +1133,7 @@ def publication_workload_secret_requirements( ] if len(workload_containers) != 1: raise ValueError( - f"Expected exactly one owning container for publication workload {workload}; " + f"Expected exactly one owning container for {workload_label} {workload}; " f"found {len(workload_containers)}" ) container = workload_containers[0] @@ -1117,20 +1146,20 @@ def publication_workload_secret_requirements( ) if env_issues: raise ValueError( - f"Rendered publication workload {workload} has invalid gRPC TLS path environment: " + f"Rendered {workload_label} {workload} has invalid gRPC TLS path environment: " + "; ".join(env_issues) ) container_env = container.get("env", []) if not isinstance(container_env, list): raise TypeError( - f"Rendered publication workload {workload} has no valid container env list" + f"Rendered {workload_label} {workload} has no valid container env list" ) declared_grpc_path_names: list[str] = [] for entry in container_env: if not isinstance(entry, dict): raise TypeError( - f"Rendered publication workload {workload} has a malformed container env entry" + f"Rendered {workload_label} {workload} has a malformed container env entry" ) name = entry.get("name") if name not in GRPC_TLS_PATH_NAMES: @@ -1138,11 +1167,11 @@ def publication_workload_secret_requirements( declared_grpc_path_names.append(name) if not set(entry).issubset({"name", "value", "valueFrom"}): raise ValueError( - f"Rendered publication workload {workload} has a malformed {name} env entry" + f"Rendered {workload_label} {workload} has a malformed {name} env entry" ) if "value" in entry and "valueFrom" in entry: raise ValueError( - f"Rendered publication workload {workload} has an ambiguous {name} env entry" + f"Rendered {workload_label} {workload} has an ambiguous {name} env entry" ) if "valueFrom" in entry: value_from = entry.get("valueFrom") @@ -1152,17 +1181,19 @@ def publication_workload_secret_requirements( or not set(value_from).issubset({"configMapKeyRef", "secretKeyRef"}) ): raise ValueError( - f"Rendered publication workload {workload} has a malformed {name} env source" + f"Rendered {workload_label} {workload} has a malformed {name} env source" ) if len(declared_grpc_path_names) != len(set(declared_grpc_path_names)): raise ValueError( - f"Rendered publication workload {workload} has ambiguous gRPC TLS path env entries" + f"Rendered {workload_label} {workload} has ambiguous gRPC TLS path env entries" ) expected_grpc_paths = { "FIREMUD_GRPC_CERT_CHAIN_PATH": "/tls/tls.crt", "FIREMUD_GRPC_PRIVATE_KEY_PATH": "/tls/tls.key", - "FIREMUD_GRPC_CA_CERT_PATH": "/grpc-trust/ca.crt", + "FIREMUD_GRPC_CA_CERT_PATH": ( + "/grpc-trust/ca.crt" if is_publication_workload else "/tls/ca.crt" + ), } grpc_paths: dict[str, str] = {} for name in GRPC_TLS_PATH_NAMES: @@ -1175,44 +1206,45 @@ def publication_workload_secret_requirements( or path != expected_grpc_paths[name] ): raise ValueError( - f"Rendered publication workload {workload} must configure {name} as {expected_grpc_paths[name]}" + f"Rendered {workload_label} {workload} must configure {name} as {expected_grpc_paths[name]}" ) grpc_paths[name] = path volume_mounts = container.get("volumeMounts") if not isinstance(volume_mounts, list): raise TypeError( - f"Rendered publication workload {workload} has no valid container volumeMounts list" + f"Rendered {workload_label} {workload} has no valid container volumeMounts list" ) for mount in volume_mounts: if not isinstance(mount, dict): raise TypeError( - f"Rendered publication workload {workload} has a malformed container volume mount" + f"Rendered {workload_label} {workload} has a malformed container volume mount" ) if not isinstance(mount.get("name"), str) or not mount["name"].strip(): raise ValueError( - f"Rendered publication workload {workload} has a volume mount with an invalid name" + f"Rendered {workload_label} {workload} has a volume mount with an invalid name" ) mount_path = mount.get("mountPath") if not isinstance(mount_path, str) or not mount_path.startswith("/"): raise ValueError( - f"Rendered publication workload {workload} has a volume mount with a non-absolute mountPath" + f"Rendered {workload_label} {workload} has a volume mount with a non-absolute mountPath" ) if "readOnly" in mount and not isinstance(mount["readOnly"], bool): raise ValueError( - f"Rendered publication workload {workload} has a malformed volume mount readOnly value" + f"Rendered {workload_label} {workload} has a malformed volume mount readOnly value" ) expected_mounts = { "grpc-tls": "/tls", - "grpc-trust": "/grpc-trust", } + if is_publication_workload: + expected_mounts["grpc-trust"] = "/grpc-trust" validated_mounts: dict[str, dict[str, Any]] = {} for volume_name, mount_path in expected_mounts.items(): mounts = [mount for mount in volume_mounts if mount.get("name") == volume_name] if len(mounts) != 1: raise ValueError( - f"Expected exactly one {volume_name} mount for publication workload {workload}; found {len(mounts)}" + f"Expected exactly one {volume_name} mount for {workload_label} {workload}; found {len(mounts)}" ) mount = mounts[0] if ( @@ -1222,10 +1254,11 @@ def publication_workload_secret_requirements( or "subPathExpr" in mount ): raise ValueError( - f"Rendered publication workload {workload} requires a read-only {volume_name} mount at {mount_path} without subPath" + f"Rendered {workload_label} {workload} requires a read-only {volume_name} mount at {mount_path} without subPath" ) validated_mounts[volume_name] = mount + ca_trust_mount = "/grpc-trust" if is_publication_workload else "/tls" if any( not path_is_under_mount(path, "/tls") for path in ( @@ -1233,10 +1266,10 @@ def publication_workload_secret_requirements( grpc_paths["FIREMUD_GRPC_PRIVATE_KEY_PATH"], ) ) or not path_is_under_mount( - grpc_paths["FIREMUD_GRPC_CA_CERT_PATH"], "/grpc-trust" + grpc_paths["FIREMUD_GRPC_CA_CERT_PATH"], ca_trust_mount ): raise ValueError( - f"Rendered publication workload {workload} gRPC TLS paths do not match the split leaf/trust mounts" + f"Rendered {workload_label} {workload} gRPC TLS paths do not match its leaf/trust mount layout" ) for mount in volume_mounts: @@ -1248,16 +1281,16 @@ def publication_workload_secret_requirements( continue if any(path_is_under_mount(path, mount_path) for path in grpc_paths.values()): raise ValueError( - f"Rendered publication workload {workload} has another volume mount covering a gRPC TLS path" + f"Rendered {workload_label} {workload} has another volume mount covering a gRPC TLS path" ) requirements.append( - (secret_name, workload_namespace, set(PUBLICATION_GRPC_LEAF_SECRET_KEYS)) + (secret_name, workload_namespace, set(GRPC_WORKLOAD_LEAF_SECRET_KEYS)) ) leaf_secret_names.append(secret_name) if len(set(leaf_secret_names)) != len(leaf_secret_names): raise ValueError( - "Rendered publication workloads must mount five distinct grpc-tls Secrets" + "Rendered gRPC workload consumers must mount seven distinct grpc-tls Secrets" ) requirements.append( ( @@ -1275,7 +1308,7 @@ def publication_workload_secret_issues( *, lookup_cluster_secrets: bool = True, ) -> list[str]: - """Validate publication Secret bindings and, optionally, their live data keys.""" + """Validate workload Secret bindings and, optionally, their live data keys.""" try: requirements = publication_workload_secret_requirements(expected, documents) except (TypeError, ValueError) as exc: @@ -7552,7 +7585,7 @@ def main() -> int: "PREFLIGHT-SECRETS-001", True, "fail", - "Publication workload render: " + "; ".join(publication_secret_issues), + "gRPC workload render: " + "; ".join(publication_secret_issues), ) or has_required_failure secret_check_failed = True if not secret_check_failed: @@ -7561,7 +7594,7 @@ def main() -> int: "PREFLIGHT-SECRETS-001", True, "pass", - "Rendered player-facing and publication workloads reference required Secret bindings", + "Rendered player-facing and gRPC workload consumers reference required Secret bindings", ) or has_required_failure else: for secret_name, secret_namespace, binding_path in expected_player_secret_bindings( @@ -7603,7 +7636,7 @@ def main() -> int: "PREFLIGHT-SECRETS-001", True, "fail", - "Publication workload certificate: " + "; ".join(publication_secret_issues), + "gRPC workload certificate: " + "; ".join(publication_secret_issues), ) or has_required_failure ) @@ -7615,7 +7648,7 @@ def main() -> int: "PREFLIGHT-SECRETS-001", True, "pass", - "Required player-facing and publication workload Secrets and keys exist in the target cluster", + "Required player-facing and gRPC workload Secrets and keys exist in the target cluster", ) or has_required_failure ) diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index 354fe41ba4..10808574c3 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -377,7 +377,7 @@ require_literal "$CRD" "self.desiredState == oldSelf.desiredState || (oldSelf.de forbid_literal "$CRD" "self.metadata.namespace == 'firemud-system'" forbid_literal "$CRD" "x-kubernetes-preserve-unknown-fields" require_literal "$CRD" "self.metadata.name.matches('^(dev-demo|pr-[1-9][0-9]{0,50})$')" -for field in observedGeneration phase conditions profile runtimeNamespaceUid requestedHeadSha deployedHeadSha ingress telnet gatewayInternalWs tcpProxyBridge grpc grpcPublication; do +for field in observedGeneration phase conditions profile runtimeNamespaceUid requestedHeadSha deployedHeadSha ingress telnet gatewayInternalWs tcpProxyBridge grpc grpcAccountService grpcGameSessionService grpcPublication; do require_literal "$CRD" "$field" done require_literal "$APPLICATION_CONFIG" "dev-demo-requested-head-annotation: firemud.dev/requested-dev-demo-head-sha" @@ -396,7 +396,7 @@ import yaml source = Path(os.environ["CRD"]).read_text(encoding="utf-8") assert source.count("&consumer_status_schema") == 1 -assert source.count("*consumer_status_schema") == 5 +assert source.count("*consumer_status_schema") == 7 crd = yaml.safe_load(source) schema = crd["spec"]["versions"][0]["schema"]["openAPIV3Schema"] assert crd["spec"].get("preserveUnknownFields", False) is False @@ -458,6 +458,8 @@ consumer_schemas = [ for name in ("ingress", "telnet", "gatewayInternalWs", "tcpProxyBridge", "grpc") ] assert all(value == consumer_schemas[0] for value in consumer_schemas[1:]) +assert consumer_properties["grpcAccountService"] == consumer_schemas[0] +assert consumer_properties["grpcGameSessionService"] == consumer_schemas[0] publication_roles = consumer_properties["grpcPublication"] assert publication_roles["type"] == "object" assert publication_roles["maxProperties"] == 5 diff --git a/dev-tools/tests/preflight-contract.sh b/dev-tools/tests/preflight-contract.sh index 78b89fdc75..f94f57f62a 100644 --- a/dev-tools/tests/preflight-contract.sh +++ b/dev-tools/tests/preflight-contract.sh @@ -996,12 +996,22 @@ spec: containers: - name: account-service image: ghcr.io/benhook1013/account-service:latest + env: + - 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: /tls/ca.crt envFrom: - secretRef: name: postgres-credentials - configMapRef: name: firemud-config volumeMounts: + - name: grpc-tls + mountPath: /tls + readOnly: true - name: jwt-signing-keys mountPath: /var/run/secrets/firemud/jwt readOnly: true @@ -1009,6 +1019,9 @@ spec: mountPath: /var/run/secrets/firemud/jwks readOnly: true volumes: + - name: grpc-tls + secret: + secretName: firemud-grpc-account-service - name: jwt-signing-keys secret: secretName: jwt-signing-keys @@ -1018,6 +1031,32 @@ spec: --- apiVersion: apps/v1 kind: Deployment +metadata: + name: game-session-service +spec: + template: + spec: + containers: + - name: game-session-service + image: ghcr.io/benhook1013/game-session-service:latest + env: + - 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: /tls/ca.crt + volumeMounts: + - name: grpc-tls + mountPath: /tls + readOnly: true + volumes: + - name: grpc-tls + secret: + secretName: firemud-grpc-game-session-service +--- +apiVersion: apps/v1 +kind: Deployment metadata: name: game-design-service spec: @@ -9894,28 +9933,83 @@ publication_documents = [ } for workload in module.PUBLICATION_GRPC_WORKLOADS ] +for workload in module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS: + publication_documents.append( + { + "kind": "Deployment", + "metadata": {"name": workload, "namespace": "firemud"}, + "spec": { + "template": { + "spec": { + "volumes": [ + { + "name": "grpc-tls", + "secret": { + "secretName": f"firemud-grpc-{workload}", + }, + }, + ], + "containers": [ + { + "name": workload, + "env": [ + { + "name": path_name, + "value": path, + } + for path_name, path in zip( + module.GRPC_TLS_PATH_NAMES, + ( + "/tls/tls.crt", + "/tls/tls.key", + "/tls/ca.crt", + ), + ) + ], + "volumeMounts": [ + { + "name": "grpc-tls", + "mountPath": "/tls", + "readOnly": True, + }, + ], + } + ], + } + } + }, + } + ) +if module.PUBLICATION_GRPC_WORKLOADS != ( + "game-design-service", + "world-management-service", + "entity-management-service", + "game-logic-service", + "automation-scripting-service", +): + raise SystemExit("Account and Game Session changed the five publication-only workload set") publication_requirements = module.publication_workload_secret_requirements( publication_expected, publication_documents ) -expected_publication_names = { +expected_workload_secret_names = { f"firemud-grpc-{workload}" - for workload in module.PUBLICATION_GRPC_WORKLOADS + for workload in module.GRPC_WORKLOAD_SECRET_CONSUMERS } if {name for name, _, _ in publication_requirements} != ( - expected_publication_names | {module.PUBLICATION_GRPC_TRUST_SECRET_NAME} + expected_workload_secret_names | {module.PUBLICATION_GRPC_TRUST_SECRET_NAME} ): raise SystemExit( - "publication Secret requirements do not follow the five leaf bindings and shared trust binding" + "workload Secret requirements do not follow the seven leaf bindings and shared trust binding" ) publication_keys = {name: keys for name, _, keys in publication_requirements} if any(namespace != "firemud" for _, namespace, _ in publication_requirements): - raise SystemExit("publication Secret requirements did not use the expected-binding namespace") + raise SystemExit("workload Secret requirements did not use the expected-binding namespace") if any( - publication_keys[name] != {"tls.crt", "tls.key", "ca.crt"} - for name in expected_publication_names + publication_keys[name] != module.GRPC_WORKLOAD_LEAF_SECRET_KEYS + for name in expected_workload_secret_names ) or publication_keys[module.PUBLICATION_GRPC_TRUST_SECRET_NAME] != {"ca.crt"}: raise SystemExit( - "source publication Secret requirements omitted certificate-manager CA material" + "source workload Secret requirements omitted certificate-manager CA material" ) def publication_static_issues(documents): @@ -9938,6 +10032,34 @@ def expect_publication_static_failure(description, documents, expected_fragment= ) +for workload in module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS: + workload_index = len(module.PUBLICATION_GRPC_WORKLOADS) + ( + module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS.index(workload) + ) + wrong_leaf_documents = copy.deepcopy(publication_documents) + wrong_leaf_documents[workload_index]["spec"]["template"]["spec"]["volumes"][0][ + "secret" + ]["secretName"] = "wrong-workload-leaf" + expect_publication_static_failure( + f"a wrong {workload} leaf Secret reference", + wrong_leaf_documents, + f"grpc-tls Secret must be firemud-grpc-{workload}", + ) + + missing_ca_projection_documents = copy.deepcopy(publication_documents) + missing_ca_projection_documents[workload_index]["spec"]["template"]["spec"][ + "volumes" + ][0]["secret"]["items"] = [ + {"key": "tls.crt", "path": "tls.crt"}, + {"key": "tls.key", "path": "tls.key"}, + ] + expect_publication_static_failure( + f"a {workload} leaf volume that omits ca.crt", + missing_ca_projection_documents, + "malformed grpc-tls Secret volume", + ) + + swapped_leaf_documents = copy.deepcopy(publication_documents) first_leaf = swapped_leaf_documents[0]["spec"]["template"]["spec"]["volumes"][0][ "secret" @@ -10174,8 +10296,8 @@ default_mode_publication_documents[0]["spec"]["template"]["spec"]["volumes"][0][ default_mode_requirements = module.publication_workload_secret_requirements( publication_expected, default_mode_publication_documents ) -if len(default_mode_requirements) != len(module.PUBLICATION_GRPC_WORKLOADS) + 1: - raise SystemExit("publication grpc-tls Secret defaultMode was not accepted") +if len(default_mode_requirements) != len(module.GRPC_WORKLOAD_SECRET_CONSUMERS) + 1: + raise SystemExit("workload grpc-tls Secret defaultMode was not accepted") for forbidden_secret_key in ("optional", "unexpected"): forbidden_secret_documents = copy.deepcopy(publication_documents) @@ -10308,7 +10430,7 @@ if not any( publication_expected, missing_workload_documents ) ): - raise SystemExit("missing publication workload did not fail closed") + raise SystemExit("missing gRPC workload did not fail closed") ambiguous_workload_documents = publication_documents + [ copy.deepcopy(publication_documents[0]) @@ -10379,7 +10501,7 @@ if not any( publication_expected, namespace_mismatch_documents ) ): - raise SystemExit("publication workload namespace mismatch did not fail closed") + raise SystemExit("gRPC workload namespace mismatch did not fail closed") publication_success_fixture = { name: keys for name, _, keys in publication_requirements @@ -10402,13 +10524,13 @@ with patch.object( if module.publication_workload_secret_issues( publication_expected, publication_documents ): - raise SystemExit("complete publication Secret fixture failed preflight") + raise SystemExit("complete seven-workload Secret fixture failed preflight") if {name for name, _, _ in queried_publication_secrets} != ( - expected_publication_names | {module.PUBLICATION_GRPC_TRUST_SECRET_NAME} + expected_workload_secret_names | {module.PUBLICATION_GRPC_TRUST_SECRET_NAME} ): - raise SystemExit("preflight did not query precisely the mounted publication Secrets") + raise SystemExit("preflight did not query precisely the mounted workload Secrets") if any(namespace != "firemud" for _, namespace, _ in queried_publication_secrets): - raise SystemExit("preflight queried a publication Secret in the wrong namespace") + raise SystemExit("preflight queried a workload Secret in the wrong namespace") missing_publication_name = publication_requirements[0][0] with patch.object( @@ -10462,6 +10584,58 @@ if len(missing_ca_issues) != 1 or "missing keys: ca.crt" not in missing_ca_issue f"publication Secret missing ca.crt did not fail closed: {missing_ca_issues}" ) +for workload in module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS: + target_secret_name = f"firemud-grpc-{workload}" + with patch.object( + module, + "secret_keys_lookup_failure", + side_effect=lambda name, namespace, required, target=target_secret_name: ( + ( + f"Missing required Secret in cluster: {namespace}/{name}", + True, + False, + ) + if name == target + else (None, False, False) + ), + ): + missing_role_secret_issues = module.publication_workload_secret_issues( + publication_expected, publication_documents + ) + if ( + len(missing_role_secret_issues) != 1 + or target_secret_name not in missing_role_secret_issues[0] + or "Missing required Secret" not in missing_role_secret_issues[0] + ): + raise SystemExit( + f"missing {workload} leaf Secret did not fail closed: {missing_role_secret_issues}" + ) + + with patch.object( + module, + "secret_keys_lookup_failure", + side_effect=lambda name, namespace, required, target=target_secret_name: ( + ( + f"Required Secret {namespace}/{name} is missing keys: ca.crt", + True, + False, + ) + if name == target + else (None, False, False) + ), + ): + incomplete_role_secret_issues = module.publication_workload_secret_issues( + publication_expected, publication_documents + ) + if ( + len(incomplete_role_secret_issues) != 1 + or target_secret_name not in incomplete_role_secret_issues[0] + or "missing keys: ca.crt" not in incomplete_role_secret_issues[0] + ): + raise SystemExit( + f"incomplete {workload} leaf Secret did not fail closed: {incomplete_role_secret_issues}" + ) + namespace = "pr-42" release = "pr-42" node_port = 32007 diff --git a/k8s/base/grpc-bootstrap.example.yaml b/k8s/base/grpc-bootstrap.example.yaml index 00a9aaa6ae..aa278c1e72 100644 --- a/k8s/base/grpc-bootstrap.example.yaml +++ b/k8s/base/grpc-bootstrap.example.yaml @@ -1,3 +1,7 @@ +# This example only provisions the shared transport/trust Secret. Account Service, Game Session, +# and the five publication workloads also require their separate cert-manager-issued leaf Secrets: +# firemud-grpc-account-service, firemud-grpc-game-session-service, and one firemud-grpc- +# Secret for each publication workload. The shared Secret alone is not sufficient to start them. apiVersion: cert-manager.io/v1 kind: Certificate metadata: diff --git a/k8s/hosted-identity-controller/README.md b/k8s/hosted-identity-controller/README.md index a494f3da15..940cc233ef 100644 --- a/k8s/hosted-identity-controller/README.md +++ b/k8s/hosted-identity-controller/README.md @@ -18,9 +18,9 @@ There is no user-supplied hostname, Secret, Certificate, issuer, port, key, roll The trusted preview workflow derives an explicit mode from the validated runtime artifact: a `ClusterIP` `tcp-proxy-service` selects `private`, and a `NodePort` selects `public`. The runtime Namespace must carry the matching `firemud.dev/preview-exposure-mode` label; an absent, unknown, or changed mode is invalid. The controller never infers private mode from a failed public probe. -In `private` mode, the runtime TCP Proxy Service remains `ClusterIP`, has no NodePort, and has no canonical Telnet-port annotation. `telnetPort=0` is an internal profile sentinel only. After all five labeled, key-complete projections and the required Gateway/TCP Proxy rollouts converge, `Ready=True` requires served HTTPS, the private Gateway-to-TCP Proxy mutual-TLS bridge, and gRPC probes. The private proof therefore proves the internal bridge without claiming a public TCP endpoint, Telnet smoke, or gameplay acceptance. +In `private` mode, the runtime TCP Proxy Service remains `ClusterIP`, has no NodePort, and has no canonical Telnet-port annotation. `telnetPort=0` is an internal profile sentinel only. After all five labeled, key-complete shared-role projections and the required Gateway/TCP Proxy rollouts converge, `Ready=True` requires served HTTPS, the private Gateway-to-TCP Proxy mutual-TLS bridge, and gRPC probes. The private proof therefore proves the internal bridge without claiming a public TCP endpoint, Telnet smoke, or gameplay acceptance. -In `public` mode, the trusted allocator supplies the reserved NodePort and the runtime Namespace carries its Telnet-port annotation. `Ready=True` retains the public Telnet probe in addition to HTTPS, the Gateway-to-TCP Proxy bridge, gRPC, all five projections, and rollout convergence; the trusted workflow then requires the public `LOGIN -> PLAY -> LOOK` smoke. A public probe or smoke failure is terminal for public mode and cannot fall back to private mode. This bounded private mode does not replace the public two-path target in [ADR 0178](../../design/architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md). +In `public` mode, the trusted allocator supplies the reserved NodePort and the runtime Namespace carries its Telnet-port annotation. `Ready=True` retains the public Telnet probe in addition to HTTPS, the Gateway-to-TCP Proxy bridge, gRPC, all five shared-role projections, and rollout convergence; the trusted workflow then requires the public `LOGIN -> PLAY -> LOOK` smoke. A public probe or smoke failure is terminal for public mode and cannot fall back to private mode. This bounded private mode does not replace the public two-path target in [ADR 0178](../../design/architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md). ## Resource and status contract @@ -34,7 +34,7 @@ Controller-managed resources carry these stable labels: Existing runtime namespaces retain their workflow labels. PR namespaces must have `firemud.dev/preview=true` and a matching `firemud.dev/pr-number`; the demo namespace must have `firemud.dev/dev-demo=true` and `firemud.dev/environment-class=dev-demo-cluster`. -Status contains only non-secret evidence: `observedGeneration`, phase, conditions, a derived `profile` (including `runtimeNamespaceUid`, `requestedHeadSha`, `deployedHeadSha`, `exposureMode`, and `telnetPort`), and ingress, Telnet, Gateway-internal WebSocket, TCP Proxy bridge, and gRPC revision, source-generation, provenance, and state. `Ready` is true only when the current runtime Namespace UID and requested 40-character head SHA match the observed profile, the separately recorded post-Helm deployed head matches that request, every consumer has converged, and the mode-specific served probes pass. Public mode includes the served Telnet probe; private mode deliberately omits it and requires served HTTPS, the private bridge, and gRPC instead. A runtime UID, request, deployed-head, exposure-mode, or port change clears `Ready`; pre-Helm namespace preparation cannot claim deployment success. +Status contains only non-secret evidence: `observedGeneration`, phase, conditions, a derived `profile` (including `runtimeNamespaceUid`, `requestedHeadSha`, `deployedHeadSha`, `exposureMode`, and `telnetPort`), and role evidence for ingress, Telnet, Gateway-internal WebSocket, TCP Proxy bridge, and the shared gRPC transport bundle. The `grpcPublication` map remains exactly the five fixed publication roles; `grpcAccountService` and `grpcGameSessionService` separately retain each workload's `RoleStatus` high-water evidence. Readiness therefore covers seven gRPC workload identities: the five publication roles plus Account and Game Session. Each role status records only non-secret revision, source and source-object generations, SPKI fingerprint, provenance, and state. `Ready` is true only when the current runtime Namespace UID and requested 40-character head SHA match the observed profile, the separately recorded post-Helm deployed head matches that request, all seven gRPC workload identities and other consumers have converged, and the mode-specific served probes pass. Public mode includes the served Telnet probe; private mode deliberately omits it and requires served HTTPS, the private bridge, and gRPC instead. A runtime UID, request, deployed-head, exposure-mode, or port change clears `Ready`; pre-Helm namespace preparation cannot claim deployment success. The phases are `Pending`, `Provisioning`, `WaitingForCertificate`, `RuntimeAbsent`, `Syncing`, `Verifying`, `Ready`, `Degraded`, `Blocked`, `Retiring`, and `Retired`. diff --git a/k8s/hosted-identity-controller/crd.yaml b/k8s/hosted-identity-controller/crd.yaml index cabecb34d2..fbf0eef2a6 100644 --- a/k8s/hosted-identity-controller/crd.yaml +++ b/k8s/hosted-identity-controller/crd.yaml @@ -203,6 +203,8 @@ spec: gatewayInternalWs: *consumer_status_schema tcpProxyBridge: *consumer_status_schema grpc: *consumer_status_schema + grpcAccountService: *consumer_status_schema + grpcGameSessionService: *consumer_status_schema grpcPublication: type: object description: Per-publication workload certificate projection and rollout evidence only; this does not prove receiver-method authorization or authorize publication identity activation. diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/HostedEnvironmentIdentityStatus.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/HostedEnvironmentIdentityStatus.java index c87acdce4e..2ff7020ea8 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/HostedEnvironmentIdentityStatus.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/HostedEnvironmentIdentityStatus.java @@ -14,6 +14,8 @@ public class HostedEnvironmentIdentityStatus { private RoleStatus gatewayInternalWs; private RoleStatus tcpProxyBridge; private RoleStatus grpc; + private RoleStatus grpcAccountService; + private RoleStatus grpcGameSessionService; private Map grpcPublication; private RuntimeProfile profile; @@ -86,6 +88,22 @@ public void setGrpc(RoleStatus grpc) { this.grpc = copyRole(grpc); } + public RoleStatus getGrpcAccountService() { + return copyRole(grpcAccountService); + } + + public void setGrpcAccountService(RoleStatus grpcAccountService) { + this.grpcAccountService = copyRole(grpcAccountService); + } + + public RoleStatus getGrpcGameSessionService() { + return copyRole(grpcGameSessionService); + } + + public void setGrpcGameSessionService(RoleStatus grpcGameSessionService) { + this.grpcGameSessionService = copyRole(grpcGameSessionService); + } + public Map getGrpcPublication() { if (grpcPublication == null) { return null; diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java index 5b4e248e4d..30d61f3b40 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java @@ -1073,6 +1073,14 @@ private UpdateControl status( roleStatus( materials.material(HostedIdentityContract.GRPC_ROLE), previousRole(resource, HostedIdentityContract.GRPC_ROLE))); + updatedStatus.setGrpcAccountService( + roleStatus( + materials.material(HostedIdentityContract.GRPC_ACCOUNT_ROLE), + previousRole(resource, HostedIdentityContract.GRPC_ACCOUNT_ROLE))); + updatedStatus.setGrpcGameSessionService( + roleStatus( + materials.material(HostedIdentityContract.GRPC_GAME_SESSION_ROLE), + previousRole(resource, HostedIdentityContract.GRPC_GAME_SESSION_ROLE))); updatedStatus.setGrpcPublication(publicationRoleStatus(resource, materials)); resource.setStatus(updatedStatus); return UpdateControl.patchStatus(resource).rescheduleAfter(properties.getReconcileInterval()); @@ -1126,7 +1134,6 @@ static HostedEnvironmentIdentityStatus.RoleStatus previousRole( previousPublicationRoles(resource); return publicationRoles == null ? null : publicationRoles.get(role); } - if (HostedIdentityContract.isGrpcWorkloadIdentityRole(role)) return null; if (resource.getStatus() == null) return null; return switch (role) { case HostedIdentityContract.INGRESS_ROLE -> resource.getStatus().getIngress(); @@ -1135,6 +1142,10 @@ static HostedEnvironmentIdentityStatus.RoleStatus previousRole( resource.getStatus().getGatewayInternalWs(); case HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE -> resource.getStatus().getTcpProxyBridge(); case HostedIdentityContract.GRPC_ROLE -> resource.getStatus().getGrpc(); + case HostedIdentityContract.GRPC_ACCOUNT_ROLE -> + resource.getStatus().getGrpcAccountService(); + case HostedIdentityContract.GRPC_GAME_SESSION_ROLE -> + resource.getStatus().getGrpcGameSessionService(); default -> throw new IllegalArgumentException("unsupported identity role: " + role); }; } diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java index 84c4932fd4..a94795b73b 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java @@ -1559,6 +1559,125 @@ void grpcPublicationRollbackIsRejectedBeforeRecreatingMissingRuntimeProjection() verifyNoInteractions(fixture.projections); } + @Test + void grpcWorkloadIdentityRollbackIsRejectedAndHighWaterSurvivesRuntimeRecreation() { + record SourceProgressCase( + long sourceGeneration, long objectGeneration, String spki, String failure) {} + + List rollbackCases = + List.of( + new SourceProgressCase(3, 2, "c".repeat(64), "generation"), + new SourceProgressCase(4, 1, "c".repeat(64), "object-generation"), + new SourceProgressCase(4, 2, "c".repeat(64), "same-generation-substitution")); + for (String role : + List.of( + HostedIdentityContract.GRPC_ACCOUNT_ROLE, + HostedIdentityContract.GRPC_GAME_SESSION_ROLE)) { + for (SourceProgressCase rollbackCase : rollbackCases) { + DeploymentHeadGateFixture fixture = + new DeploymentHeadGateFixture( + new RuntimeProfileService.RuntimeProfile( + "recreated-runtime-uid", + "a".repeat(40), + "a".repeat(40), + HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, + 32016, + true)); + String previousCertificate = "previous-" + role; + String previousSpki = "b".repeat(64); + HostedEnvironmentIdentityStatus.RoleStatus highWater = + new HostedEnvironmentIdentityStatus.RoleStatus(); + highWater.setRevision( + SecretProjectionService.revisionForRole( + role, Map.of("tls.crt", encoded(previousCertificate)))); + highWater.setSourceGeneration(4L); + highWater.setSourceObjectGeneration(2L); + highWater.setSpkiSha256(previousSpki); + highWater.setProvenance("cert-manager"); + highWater.setState("source-ready"); + HostedEnvironmentIdentityStatus priorStatus = new HostedEnvironmentIdentityStatus(); + setGrpcWorkloadRoleStatus(priorStatus, role, highWater); + fixture.resource.setStatus(priorStatus); + + CertificateMaterialService.RoleMaterial olderSource = + roleMaterial( + role, + rollbackCase.sourceGeneration(), + rollbackCase.objectGeneration(), + rollbackCase.spki(), + "replacement-" + role + "-" + rollbackCase.failure()); + if (HostedIdentityContract.GRPC_ACCOUNT_ROLE.equals(role)) { + when(fixture.batch.grpcAccount()).thenReturn(olderSource); + } else { + when(fixture.batch.grpcGameSession()).thenReturn(olderSource); + } + + UpdateControl result = fixture.reconcile(); + + HostedEnvironmentIdentityStatus blocked = result.getResource().orElseThrow().getStatus(); + String expectedMessage = + switch (rollbackCase.failure()) { + case "generation" -> + "certificate source generation rolled back for role " + + role + + " (source generation 3 < prior generation 4)"; + case "object-generation" -> "certificate source object generation rolled back"; + case "same-generation-substitution" -> + "certificate source changed without generation advancement"; + default -> throw new AssertionError("unknown rollback case"); + }; + assertEquals(HostedEnvironmentIdentityStatus.Phase.Blocked, blocked.getPhase()); + assertEquals("ReconciliationBlocked", blocked.getConditions().get(0).getReason()); + assertEquals(expectedMessage, blocked.getConditions().get(0).getMessage()); + HostedEnvironmentIdentityStatus.RoleStatus retained = + grpcWorkloadRoleStatus(blocked, role); + assertNotNull(retained); + assertEquals(4L, retained.getSourceGeneration()); + assertEquals(2L, retained.getSourceObjectGeneration()); + assertEquals(highWater.getRevision(), retained.getRevision()); + assertEquals(previousSpki, retained.getSpkiSha256()); + verifyNoInteractions(fixture.projections); + } + } + } + + @Test + void grpcWorkloadIdentityStatusReadbackAllowsLegacyAbsence() { + HostedEnvironmentIdentity resource = resource(); + HostedEnvironmentIdentityStatus status = new HostedEnvironmentIdentityStatus(); + resource.setStatus(status); + assertNull( + HostedIdentityReconciler.previousRole(resource, HostedIdentityContract.GRPC_ACCOUNT_ROLE)); + assertNull( + HostedIdentityReconciler.previousRole( + resource, HostedIdentityContract.GRPC_GAME_SESSION_ROLE)); + + HostedEnvironmentIdentityStatus.RoleStatus account = + roleStatus("account-revision", 4L, 2L, "a".repeat(64)); + HostedEnvironmentIdentityStatus.RoleStatus gameSession = + roleStatus("game-session-revision", 5L, 3L, "b".repeat(64)); + status.setGrpcAccountService(account); + status.setGrpcGameSessionService(gameSession); + resource.setStatus(status); + + HostedEnvironmentIdentityStatus.RoleStatus accountReadback = + HostedIdentityReconciler.previousRole(resource, HostedIdentityContract.GRPC_ACCOUNT_ROLE); + HostedEnvironmentIdentityStatus.RoleStatus gameSessionReadback = + HostedIdentityReconciler.previousRole( + resource, HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + assertNotSame(account, accountReadback); + assertNotSame(gameSession, gameSessionReadback); + assertEquals(account.getRevision(), accountReadback.getRevision()); + assertEquals(account.getSourceGeneration(), accountReadback.getSourceGeneration()); + assertEquals(account.getSourceObjectGeneration(), accountReadback.getSourceObjectGeneration()); + assertEquals(account.getSpkiSha256(), accountReadback.getSpkiSha256()); + assertEquals(gameSession.getRevision(), gameSessionReadback.getRevision()); + assertEquals(gameSession.getSourceGeneration(), gameSessionReadback.getSourceGeneration()); + assertEquals( + gameSession.getSourceObjectGeneration(), gameSessionReadback.getSourceObjectGeneration()); + assertEquals(gameSession.getSpkiSha256(), gameSessionReadback.getSpkiSha256()); + } + @Test void grpcPublicationHistoryAllowsLegacyAbsenceAndRejectsMalformedPartialMap() { String role = HostedIdentityContract.grpcPublicationRole("game-design-service"); @@ -1731,6 +1850,8 @@ private static boolean crdSchemaAccepts(Map propertySchema, Object value) schemaMap(schemaMap(openApiSchema.get("properties")).get("status")).get("properties")); Map consumerSchema = schemaMap(statusProperties.get("ingress")); Map publicationSchema = schemaMap(statusProperties.get("grpcPublication")); + assertEquals(consumerSchema, statusProperties.get("grpcAccountService")); + assertEquals(consumerSchema, statusProperties.get("grpcGameSessionService")); assertEquals( consumerSchema, publicationSchema.get("additionalProperties"), @@ -2125,6 +2246,10 @@ void statusMaterialIsMappedByRoleRatherThanCallPosition() { assertEquals("3".repeat(64), status.getGatewayInternalWs().getSpkiSha256()); assertEquals("4".repeat(64), status.getTcpProxyBridge().getSpkiSha256()); assertEquals("5".repeat(64), status.getGrpc().getSpkiSha256()); + assertEquals("b".repeat(64), status.getGrpcAccountService().getSpkiSha256()); + assertEquals("c".repeat(64), status.getGrpcGameSessionService().getSpkiSha256()); + assertEquals(1L, status.getGrpcAccountService().getSourceGeneration()); + assertEquals(1L, status.getGrpcGameSessionService().getSourceGeneration()); ArgumentCaptor gatewayRevision = ArgumentCaptor.forClass(String.class); ArgumentCaptor> workloadIdentityRevisions = ArgumentCaptor.forClass(Map.class); @@ -2213,6 +2338,63 @@ private static CertificateMaterialService.RoleMaterial material( state); } + private static CertificateMaterialService.RoleMaterial roleMaterial( + String role, + long generation, + long objectGeneration, + String spki, + String certificate) { + return new CertificateMaterialService.RoleMaterial( + role, + new SecretBuilder() + .withType("kubernetes.io/tls") + .withData(Map.of("tls.crt", encoded(certificate))) + .build(), + new SecretMaterialValidator.MaterialSummary( + sha256(certificate), spki, Instant.EPOCH, Instant.MAX, "4".repeat(64)), + generation, + objectGeneration, + "cert-manager", + SOURCE_READY); + } + + private static HostedEnvironmentIdentityStatus.RoleStatus roleStatus( + String revision, long sourceGeneration, long sourceObjectGeneration, String spki) { + HostedEnvironmentIdentityStatus.RoleStatus status = + new HostedEnvironmentIdentityStatus.RoleStatus(); + status.setRevision(revision); + status.setSourceGeneration(sourceGeneration); + status.setSourceObjectGeneration(sourceObjectGeneration); + status.setSpkiSha256(spki); + status.setProvenance("cert-manager"); + status.setState("source-ready"); + return status; + } + + private static void setGrpcWorkloadRoleStatus( + HostedEnvironmentIdentityStatus status, + String role, + HostedEnvironmentIdentityStatus.RoleStatus roleStatus) { + if (HostedIdentityContract.GRPC_ACCOUNT_ROLE.equals(role)) { + status.setGrpcAccountService(roleStatus); + } else if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { + status.setGrpcGameSessionService(roleStatus); + } else { + throw new IllegalArgumentException("unsupported workload identity role: " + role); + } + } + + private static HostedEnvironmentIdentityStatus.RoleStatus grpcWorkloadRoleStatus( + HostedEnvironmentIdentityStatus status, String role) { + if (HostedIdentityContract.GRPC_ACCOUNT_ROLE.equals(role)) { + return status.getGrpcAccountService(); + } + if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { + return status.getGrpcGameSessionService(); + } + throw new IllegalArgumentException("unsupported workload identity role: " + role); + } + private static String sha256(String value) { try { return HexFormat.of() From 5a940f81742bdb5df484571c7edb1cd4b651bc5d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 28 Sep 2026 00:43:50 +1300 Subject: [PATCH 03/75] Format reconciled hosted identity controller sources --- .../hostedidentity/model/EnvironmentIdentityPlan.java | 6 +++--- .../reconcile/HostedIdentityReconciler.java | 3 +-- .../reconcile/HostedIdentityReconcilerSafetyTest.java | 9 ++------- 3 files changed, 6 insertions(+), 12 deletions(-) diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java index 90bbc90650..e59c2fbb77 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java @@ -47,10 +47,10 @@ public record EnvironmentIdentityPlan( HostedIdentityContract.GRPC_ACCOUNT_ROLE, HostedIdentityContract.GRPC_GAME_SESSION_ROLE)) .collect(Collectors.toUnmodifiableSet()); - if (!grpcWorkloadIdentityCertificateNames.keySet() - .equals(expectedGrpcWorkloadIdentityRoles) + if (!grpcWorkloadIdentityCertificateNames.keySet().equals(expectedGrpcWorkloadIdentityRoles) || !grpcWorkloadIdentitySecretNames.keySet().equals(expectedGrpcWorkloadIdentityRoles) - || !grpcWorkloadIdentitySourceSecretNames.keySet() + || !grpcWorkloadIdentitySourceSecretNames + .keySet() .equals(expectedGrpcWorkloadIdentityRoles)) { throw new IllegalArgumentException( "gRPC publication certificate, runtime Secret, and source Secret maps must contain exactly the supported roles"); diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java index 9c5672b4b2..e01c56c75b 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java @@ -1144,8 +1144,7 @@ static HostedEnvironmentIdentityStatus.RoleStatus previousRole( resource.getStatus().getGatewayInternalWs(); case HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE -> resource.getStatus().getTcpProxyBridge(); case HostedIdentityContract.GRPC_ROLE -> resource.getStatus().getGrpc(); - case HostedIdentityContract.GRPC_ACCOUNT_ROLE -> - resource.getStatus().getGrpcAccountService(); + case HostedIdentityContract.GRPC_ACCOUNT_ROLE -> resource.getStatus().getGrpcAccountService(); case HostedIdentityContract.GRPC_GAME_SESSION_ROLE -> resource.getStatus().getGrpcGameSessionService(); default -> throw new IllegalArgumentException("unsupported identity role: " + role); diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java index 19e4a2691b..b780258dc1 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java @@ -1629,8 +1629,7 @@ record SourceProgressCase( assertEquals(HostedEnvironmentIdentityStatus.Phase.Blocked, blocked.getPhase()); assertEquals("ReconciliationBlocked", blocked.getConditions().get(0).getReason()); assertEquals(expectedMessage, blocked.getConditions().get(0).getMessage()); - HostedEnvironmentIdentityStatus.RoleStatus retained = - grpcWorkloadRoleStatus(blocked, role); + HostedEnvironmentIdentityStatus.RoleStatus retained = grpcWorkloadRoleStatus(blocked, role); assertNotNull(retained); assertEquals(4L, retained.getSourceGeneration()); assertEquals(2L, retained.getSourceObjectGeneration()); @@ -2352,11 +2351,7 @@ private static CertificateMaterialService.RoleMaterial material( } private static CertificateMaterialService.RoleMaterial roleMaterial( - String role, - long generation, - long objectGeneration, - String spki, - String certificate) { + String role, long generation, long objectGeneration, String spki, String certificate) { return new CertificateMaterialService.RoleMaterial( role, new SecretBuilder() From 76599d3e5e83687b0a066b6ba3bd4b7890c52197 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:54:57 +1300 Subject: [PATCH 04/75] Align hosted workload identity inventory with seven leaves --- .../infrastructure/deployment-environments.md | 12 ++++++------ design/architecture/system-architecture-cicd.md | 2 +- .../platform-operations-and-delivery.md | 6 +++--- dev-tools/certs/README.md | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/design/architecture/infrastructure/deployment-environments.md b/design/architecture/infrastructure/deployment-environments.md index 8d127ce511..fc504f2c47 100644 --- a/design/architecture/infrastructure/deployment-environments.md +++ b/design/architecture/infrastructure/deployment-environments.md @@ -187,7 +187,7 @@ In production, FireMUD is deployed into Kubernetes (e.g., AWS EKS, Google GKE, o render matching checked-in baseline policies from the Helm chart using chart-specific selectors for the preview stack's labels. - Configuration and secrets are managed through ConfigMaps and Secrets. -- On the explicit `hosted-controller` target path for hosted preview/dev-demo, the in-cluster controller owns the `Certificate` resources for the public ingress, public Telnet, Gateway-internal WebSocket server, and TCP Proxy bridge client leaves, which **cert-manager** issues. The controller separately generates the shared gRPC mTLS bundle from the fixed `firemud-system/firemud-grpc-ca` Secret, then requests five per-workload gRPC publication leaves from `firemud-ca-issuer` and materializes and reconciles ten runtime Secret projections (the five shared-role projections plus five `firemud-grpc-` publication projections). In the default/current `standalone` path, Helm renders the chart-owned public `-telnet-tls` `Certificate` when Telnet TLS is enabled, plus chart-owned `Certificate` resources for the two internal bridge leaves. The trusted standalone Certificate writer also requests the five fixed per-workload gRPC leaves for preview and dev-demo; **cert-manager** renews them into the workload Secrets while the runtime workflow retains only the legacy shared bundle and public trust anchors. The hosted identity controller remains dormant. Controller non-secret Ready evidence does not replace served-certificate or player-facing preflight proof. This remains local/static target behavior until live controller activation and consumer-convergence proof exists. +- On the explicit `hosted-controller` target path for hosted preview/dev-demo, the in-cluster controller owns the `Certificate` resources for the public ingress, public Telnet, Gateway-internal WebSocket server, and TCP Proxy bridge client leaves, which **cert-manager** issues. The controller separately generates the shared gRPC mTLS bundle from the fixed `firemud-system/firemud-grpc-ca` Secret, then requests seven per-workload gRPC leaves from `firemud-ca-issuer` (five publication workloads, Account, and Game Session) and materializes and reconciles twelve runtime Secret projections (the five shared-role projections plus seven distinct `firemud-grpc-` projections). In the default/current `standalone` path, Helm renders the chart-owned public `-telnet-tls` `Certificate` when Telnet TLS is enabled, plus chart-owned `Certificate` resources for the two internal bridge leaves. The trusted standalone Certificate writer also requests the seven fixed per-workload gRPC leaves for preview and dev-demo; **cert-manager** renews them into the workload Secrets while the runtime workflow retains only the legacy shared bundle and public trust anchors. The hosted identity controller remains dormant. Controller non-secret Ready evidence does not replace served-certificate or player-facing preflight proof. This remains local/static target behavior until live controller activation and consumer-convergence proof exists. - The cluster uses **IPVS** (or a similar load-balancing mode) to route service traffic efficiently. - Redis is deployed as **two logical roles** in both Kubernetes and Docker Compose (see [Redis Architecture](../system-architecture-redis.md)): - A **Coordination Redis** deployment runs as a clustered StatefulSet with automatic failover in production and smaller clusters in non-production. It uses AOF, persistent volumes, and `noeviction` in player-facing environments to preserve volatile coordination state across normal rollouts and pod restarts within the documented tail-loss envelope; Redis is not the authoritative recovery or audit log. AOF, persistent volumes, and `noeviction` alone are insufficient for player-facing replay safety: the deployment must also satisfy the [ADR 0029 replay-readiness contract](../decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), including Redis 7.2+, ACL isolation, reserved capacity and an admission-readiness threshold, atomic marker consumption, configured `WAITAOF` local/replica acknowledgement thresholds, and a shared reset/uncertain-durability quarantine fence. A profile that cannot prove those controls is not eligible to admit new player handshakes. @@ -322,11 +322,11 @@ FireMUD's preview environment is a hosted single-node k3s cluster intended for r Hosted Helm values select certificate identity explicitly at `previewStack.certificateIdentity.mode`. A missing mode means `standalone`; the only accepted explicit values are `standalone` and `hosted-controller`. Malformed, duplicate, non-string, or unknown mode configuration is fatal, and selecting `hosted-controller` never falls back to workflow-created certificate identity. This keeps the controller and its authority dormant before activation while preserving existing standalone deployments. -For a standalone PR preview, the credential-free render artifact excludes PR-authored `Certificate` resources. After creating the exact runtime namespace, the trusted default-branch consumer creates fixed cert-manager `Certificate` resources for the public Telnet leaf (`pr-N-telnet-tls`, `letsencrypt-prod`), Gateway-internal WebSocket server (`pr-N-gateway-internal-ws`, `firemud-ca-issuer`), TCP Proxy bridge client (`pr-N-tcp-proxy-bridge`, `firemud-ca-issuer`), and five workload leaves (`pr-N-grpc-`, `firemud-ca-issuer`). It waits for issuance and key-complete Secrets before applying the sanitized runtime artifact. Names, issuers, DNS and URI identities are derived from the validated PR number and fixed trust contract, never from PR-controlled Certificate manifests. The dev-demo standalone writer uses the same fixed workload Certificate contract under namespace `dev`; hosted-controller mode uses only controller projections. +For a standalone PR preview, the credential-free render artifact excludes PR-authored `Certificate` resources. After creating the exact runtime namespace, the trusted default-branch consumer creates fixed cert-manager `Certificate` resources for the public Telnet leaf (`pr-N-telnet-tls`, `letsencrypt-prod`), Gateway-internal WebSocket server (`pr-N-gateway-internal-ws`, `firemud-ca-issuer`), TCP Proxy bridge client (`pr-N-tcp-proxy-bridge`, `firemud-ca-issuer`), and seven workload leaves (`pr-N-grpc-`, `firemud-ca-issuer`): the five publication workloads plus Account and Game Session. It waits for issuance and key-complete Secrets before applying the sanitized runtime artifact. Names, issuers, DNS and URI identities are derived from the validated PR number and fixed trust contract, never from PR-controlled Certificate manifests. The dev-demo standalone writer uses the same fixed workload Certificate contract under namespace `dev`; hosted-controller mode uses only controller projections. The internal preview CA is not installed while a legacy preview credential can read its private-key Secret or create signing requests or issuer aliases. Its only Kubernetes private-key copies are `firemud-system/firemud-grpc-ca` and `cert-manager/firemud-grpc-ca`; no runtime namespace receives a CA private key. Trusted namespace management, namespace-local runtime deployment, fixed standalone Certificate writing, hosted identity requesting, and recovery use distinct scoped credentials. The runtime and Certificate writers are bound only in the validated runtime namespace. Fail-closed admission binds the canonical internal issuer, its two protected CA Secret copies, exact standalone and retained Certificate shapes (including each gRPC workload SAN and Secret mapping), and cert-manager-generated CertificateRequests; cert-manager's built-in auto-approval is not itself an authorization boundary. Before any CA material is installed, operators prove live denial of direct and alias issuance paths and rotate the former `preview-deployer` credential. The CA recovery copy belongs to a separate `develop`-restricted recovery-only GitHub Environment and is restored only by its scoped trusted procedure. The same procedure can be instantiated with different credentials and trust material for a future production boundary, but this preview preparation does not establish production readiness. See the [preview trust bootstrap sequence](../../../k8s/trust-bootstrap/README.md). -The canonical hosted identity API is `platform.firemud.dev/v1alpha1` `HostedEnvironmentIdentity` in `firemud-system`, named `pr-` or `dev-demo`, with only `spec.desiredState: Active|Retired`. The in-cluster controller owns identity namespaces, derived hosts, certificate resources, Secret projections, and non-secret status. A trusted workflow first validates the PR-produced sanitized render artifact and waits for its exact base/head/merge-bound runtime images without holding the shared preview-allocation lifecycle lock. Under that non-cancelling lock it revalidates the target, allocates capacity and, only for `public` mode, the Telnet port, creates the disposable runtime namespace, and records the requested base SHA, head SHA, merge SHA, and image tag before requesting `Active`. It then waits for all ten labeled, key-complete Secret projections (`pr--tls`, `pr--telnet-tls`, `pr--gateway-internal-ws`, `pr--tcp-proxy-bridge`, and `firemud-grpc-tls`, plus the five `firemud-grpc-` publication Secrets), applies the validated runtime, and records the same tuple as deployed evidence. The controller validates and consumes the trusted lifecycle's public Telnet allocation, or the private profile's zero sentinel; it does not derive or overwrite either value. Post-apply identity, rollout, and mode-specific verification runs after the mutation lock is released, revalidating the exact PR source tuple around its waits so stale verification cannot publish success; only after those checks and the exact Namespace UID fence succeed does the workflow annotate the live namespace with the proof-complete tuple and UID. The fixed dev-demo path also requires all ten labeled, key-complete projections before Helm. Only a successful runtime apply may write the deployed tuple; controller transport readiness still requires the normalized requested and deployed head values to match, while the trusted preview lifecycle and reconciler require the complete namespace tuple, proof annotations, and current Namespace UID to match. Identity provisioning failure therefore blocks deployment without giving PR-controlled rendering any cluster, runtime, or identity credential, while a failed deployment cannot make the requested preview appear deployed. +The canonical hosted identity API is `platform.firemud.dev/v1alpha1` `HostedEnvironmentIdentity` in `firemud-system`, named `pr-` or `dev-demo`, with only `spec.desiredState: Active|Retired`. The in-cluster controller owns identity namespaces, derived hosts, certificate resources, Secret projections, and non-secret status. A trusted workflow first validates the PR-produced sanitized render artifact and waits for its exact base/head/merge-bound runtime images without holding the shared preview-allocation lifecycle lock. Under that non-cancelling lock it revalidates the target, allocates capacity and, only for `public` mode, the Telnet port, creates the disposable runtime namespace, and records the requested base SHA, head SHA, merge SHA, and image tag before requesting `Active`. It then waits for all twelve labeled, key-complete runtime Secret projections: five shared-role projections (`pr--tls`, `pr--telnet-tls`, `pr--gateway-internal-ws`, `pr--tcp-proxy-bridge`, and `firemud-grpc-tls`) and seven distinct workload projections (the five publication workloads plus `firemud-grpc-account-service` and `firemud-grpc-game-session-service`). It applies the validated runtime and records the same tuple as deployed evidence. The controller validates and consumes the trusted lifecycle's public Telnet allocation, or the private profile's zero sentinel; it does not derive or overwrite either value. Post-apply identity, rollout, and mode-specific verification runs after the mutation lock is released, revalidating the exact PR source tuple around its waits so stale verification cannot publish success; only after those checks and the exact Namespace UID fence succeed does the workflow annotate the live namespace with the proof-complete tuple and UID. The fixed dev-demo path also requires all twelve labeled, key-complete projections before Helm. Only a successful runtime apply may write the deployed tuple; controller transport readiness still requires the normalized requested and deployed head values to match, while the trusted preview lifecycle and reconciler require the complete namespace tuple, proof annotations, and current Namespace UID to match. Identity provisioning failure therefore blocks deployment without giving PR-controlled rendering any cluster, runtime, or identity credential, while a failed deployment cannot make the requested preview appear deployed. Post-apply identity, rollout, and mode-specific verification runs after `deploy-runtime` releases the `preview-allocation-lifecycle` lock and reacquires that lock for its final mutation/proof fence; another lifecycle job may run between deployment and verification. The reconciler suppresses duplicate repair dispatch while either the exact source `PR Preview Environment` run or its exact trusted `Trusted Hosted Identity Request` consumer is queued, running, or verifying. A Namespace-backed counter permits at most three proof-retry dispatches for one exact base/head/merge/image tuple and resets when that tuple changes; the counter and tuple are read and updated with the Namespace `resourceVersion`, and malformed evidence fails closed. These controls bound retry dispatches without claiming live proof. @@ -334,17 +334,17 @@ Post-apply identity, rollout, and mode-specific verification runs after `deploy- The trusted consumer derives one immutable exposure mode from the validated sanitized artifact before allocation or runtime mutation: `Service/tcp-proxy-service.spec.type: ClusterIP` selects `private`, and `NodePort` selects `public`; any other type, missing service, or later mode mismatch fails closed. The trusted workflow records that mode as the `firemud.dev/preview-exposure-mode` label on the runtime Namespace, not as an annotation; PR-controlled rendering cannot choose a different mode after validation. Requester credentials remain confined to the protected `trusted-hosted-cluster` workflow boundary and are used only for the canonical identity request, never exposed to the PR-controlled source or render jobs. -The bounded #2713 private proof is a parent bridge proof, not transport-complete preview acceptance. A `private` runtime must keep `tcp-proxy-service` as `ClusterIP`, have no public NodePort, and have no `firemud.dev/last-preview-telnet-port` annotation; the internal `telnetPort=0` value is a controller sentinel and is never written as a Service port. The current-head-bound controller may become `Ready` only after all ten labeled, key-complete projections and required Gateway/TCP Proxy rollouts converge, and after served HTTPS, the private Gateway-to-TCP Proxy mutual-TLS bridge, and gRPC probes succeed. Private success therefore does not claim a public Telnet endpoint or the public gameplay smoke. +The bounded #2713 private proof is a parent bridge proof, not transport-complete preview acceptance. A `private` runtime must keep `tcp-proxy-service` as `ClusterIP`, have no public NodePort, and have no `firemud.dev/last-preview-telnet-port` annotation; the internal `telnetPort=0` value is a controller sentinel and is never written as a Service port. The current-head-bound controller may become `Ready` only after all twelve labeled, key-complete projections and required Gateway/TCP Proxy rollouts converge, and after served HTTPS, the private Gateway-to-TCP Proxy mutual-TLS bridge, and gRPC probes succeed. Private success therefore does not claim a public Telnet endpoint or the public gameplay smoke. The `public` mode owned by #2795 retains the allocated preview NodePort and its Telnet-port annotation. It requires the same head-bound projections, rollout, HTTPS, bridge, and gRPC readiness plus the served public Telnet check and `LOGIN -> PLAY -> LOOK` smoke; a failed public check is a terminal failure for that mode. The workflow never converts a failed public deployment or smoke into `private`, and private success cannot satisfy the public mode's Telnet or ADR 0178 two-public-path obligations. The private exception is limited to this explicit parent bridge proof and does not amend the accepted public transport-complete target. -The fixed dev-demo lifecycle uses the same authority split only when `hosted-controller` is selected. It recreates and annotates the exact `dev` runtime with the requested head, image, and fixed NodePort `32016`, switches to requester credentials only for the fixed-shape `dev-demo` `Active` request, restores runtime credentials, and requires all ten labeled, key-complete runtime projections before Helm. A distinct deployed-head annotation is written only after Helm succeeds; controller readiness requires it to match the requested head, so a failed Helm attempt cannot make the runtime look deployed. Success is recorded only after runtime rollout, generation/head-bound controller `Ready`, operator preflight, and the public TCP smoke. Its non-cancelling reconciler lets any in-progress same-head deploy candidate converge, allows at most three completed non-success deploy attempts for that exact head, reports retry exhaustion as a terminal workflow error, and does not reset a runtime already aligned by a successful deploy candidate. It checks nonterminal runs independently before walking completed history only until the latest exact candidate and its bounded retry result are known, so an older-record re-run is not hidden by a newer completed attempt. A workflow-owned run name binds each run to its action and effective target head, keeping explicit destroy and other-target deploy runs outside that deploy retry budget even when a run ends before its jobs materialize or more than one API page behind newer history. A new `develop` head receives a fresh retry budget. Explicit dev-demo destroy observes the runtime namespace as `NotFound` before requesting `Retired`, waiting for terminal retirement, and deleting the request. This does not activate the separate PR-close mutation path. +The fixed dev-demo lifecycle uses the same authority split only when `hosted-controller` is selected. It recreates and annotates the exact `dev` runtime with the requested head, image, and fixed NodePort `32016`, switches to requester credentials only for the fixed-shape `dev-demo` `Active` request, restores runtime credentials, and requires all twelve labeled, key-complete runtime projections before Helm. A distinct deployed-head annotation is written only after Helm succeeds; controller readiness requires it to match the requested head, so a failed Helm attempt cannot make the runtime look deployed. Success is recorded only after runtime rollout, generation/head-bound controller `Ready`, operator preflight, and the public TCP smoke. Its non-cancelling reconciler lets any in-progress same-head deploy candidate converge, allows at most three completed non-success deploy attempts for that exact head, reports retry exhaustion as a terminal workflow error, and does not reset a runtime already aligned by a successful deploy candidate. It checks nonterminal runs independently before walking completed history only until the latest exact candidate and its bounded retry result are known, so an older-record re-run is not hidden by a newer completed attempt. A workflow-owned run name binds each run to its action and effective target head, keeping explicit destroy and other-target deploy runs outside that deploy retry budget even when a run ends before its jobs materialize or more than one API page behind newer history. A new `develop` head receives a fresh retry budget. Explicit dev-demo destroy observes the runtime namespace as `NotFound` before requesting `Retired`, waiting for terminal retirement, and deleting the request. This does not activate the separate PR-close mutation path. Privileged preview janitor, preview reconciler, dev-demo deploy/destroy, and dev-demo reconciler jobs accept scheduled or typed `repository_dispatch` requests rather than branch-selectable `workflow_dispatch` requests. A repository maintainer can trigger those trusted default-branch operations through `POST /repos///dispatches` with `event_type` set to `preview-janitor`, `preview-reconcile`, `dev-demo`, or `dev-demo-reconcile`; `dev-demo` accepts a validated `client_payload` with optional `action` (`deploy` or `destroy`), `head_sha`, `image_tag`, fixed `hostname`, and fixed `telnet_port`. The reconciler uses the same `dev-demo` event for exact-head retry. Manual per-PR deploy/release requests use the default-branch preview source workflow's typed `preview-deploy` or `preview-destroy` repository dispatch with a validated `client_payload` containing matching `action`, canonical `pr_number`, current `head_sha`, and fixed `preview_domain`; the source resolves the effective head-or-base image tag independently and produces only a sanitized render artifact or destroy intent for the trusted lifecycle. Priority labeling, capacity allocation, and cleanup remain trusted lifecycle decisions. Before a trusted operator activates the hosted identity controller, that operator must provision the fixed `firemud-system/firemud-grpc-ca` `Opaque` Secret with exactly `ca.crt` and `ca.key`. The configured trust-anchor value is the lowercase 64-hex SHA-256 fingerprint of the DER-encoded CA certificate. Bootstrap verifies the key shape and certificate fingerprint without printing either value; the controller independently verifies that the CA certificate and private key correspond before it issues any transport-only leaf. The controller only consumes this prerequisite and is not a CA provisioning authority. Standalone mode uses the same protected issuer for per-workload gRPC leaves: `firemud-grpc-ca` private-key copies stay in `firemud-system` and `cert-manager`, while cert-manager owns only leaf Secrets in `dev` and `pr-N` runtime namespaces. Leaf keys rotate with their Certificates; deleting a runtime namespace removes its leaf Certificates and projections without affecting the shared CA copies. -Runtime reclaim, redeploy, release, and lease expiry delete only the runtime namespace. Close/merge retirement is runtime-first: the trusted lifecycle deletes the exact runtime, requires a successful empty `--ignore-not-found` lookup proving Namespace `NotFound`, and only then requests `Retired`; lookup or deletion uncertainty retains identity and fails closed. Explicit identity removal of a live runtime is retirement-first: the trusted requester sets `Retired`, the controller scales Gateway and TCP Proxy to zero and waits for their observed shutdown, and the trusted runtime lifecycle then deletes the runtime and proves exact Namespace `NotFound`. In both paths, retained identity deletion remains blocked until the runtime is absent. Before deleting retained identity, the controller accounts for all ten runtime Secret projections: the five shared-role projections for (1) [public ingress TLS](../system-architecture-security.md#tls-termination-for-gateway), (2) [public Telnet TLS](../system-architecture-protocol-bridging.md#public-telnet-tls-modes), (3) the [Gateway internal WebSocket server](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), (4) the [TCP Proxy bridge client](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), and (5) the [shared gRPC transport bundle](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md#mtls-identity-and-certificate-lifecycle), plus five distinct per-workload gRPC publication projections (`firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`). Controller readiness binds the CR generation, live runtime namespace UID, exact requested and deployed head SHA pair, rollout and mode-specific served proof, and non-empty revisions for each of the five shared-role projections and each of the five publication projections; public mode additionally requires the served Telnet probe. Canonical 40-hex SHA values are normalized before equality comparison. This controller contract is local/static proof only until a live hosted rollout; it does not alter stage or production deployment paths. +Runtime reclaim, redeploy, release, and lease expiry delete only the runtime namespace. Close/merge retirement is runtime-first: the trusted lifecycle deletes the exact runtime, requires a successful empty `--ignore-not-found` lookup proving Namespace `NotFound`, and only then requests `Retired`; lookup or deletion uncertainty retains identity and fails closed. Explicit identity removal of a live runtime is retirement-first: the trusted requester sets `Retired`, the controller scales Gateway and TCP Proxy to zero and waits for their observed shutdown, and the trusted runtime lifecycle then deletes the runtime and proves exact Namespace `NotFound`. In both paths, retained identity deletion remains blocked until the runtime is absent. Before deleting retained identity, the controller accounts for all twelve runtime Secret projections: five shared-role projections for (1) [public ingress TLS](../system-architecture-security.md#tls-termination-for-gateway), (2) [public Telnet TLS](../system-architecture-protocol-bridging.md#public-telnet-tls-modes), (3) the [Gateway internal WebSocket server](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), (4) the [TCP Proxy bridge client](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), and (5) the [shared gRPC transport bundle](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md#mtls-identity-and-certificate-lifecycle), plus seven distinct per-workload gRPC projections: the five publication workloads (`firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`), Account (`firemud-grpc-account-service`), and Game Session (`firemud-grpc-game-session-service`). Controller readiness binds the CR generation, live runtime namespace UID, exact requested and deployed head SHA pair, rollout and mode-specific served proof, and non-empty revisions for each of the five shared-role projections and each of the seven workload projections; public mode additionally requires the served Telnet probe. Canonical 40-hex SHA values are normalized before equality comparison. This controller contract is local/static proof only until a live hosted rollout; it does not alter stage or production deployment paths. The hosted identity controller's egress boundary is exact-destination and operator-rendered. Its checked-in NetworkPolicy contains no `0.0.0.0/0` or `::/0`; trusted bootstrap substitutes validated `/32` IPv4 CIDRs for the observed `kubernetes.default` Service ClusterIP on TCP/443, the single API endpoint on TCP/6443, and the fixed public preview probe on TCP/443 plus NodePorts 32000-32016. Gateway access is separately limited to `spring-cloud-gateway` pods in the canonical preview and dev-demo namespaces on TCP/443 and TCP/8443. The observed k3s LoadBalancer path additionally requires the exact kube-system Traefik pod selector on TCP/8443 after public HTTPS DNAT, and the public TCP Proxy NodePort path requires the exact `tcp-proxy-service` selectors in those canonical namespaces on TCP/2323 after NodePort DNAT. DNS and Account TCP/6565 selectors remain explicit. `observe` and `active` bootstrap require all three addresses, require exactly one matching fixed public DNS A record, and verify the API Service and single-endpoint readback before any write; paused mode without addresses renders loopback-only deny markers. Standard NetworkPolicy may exempt traffic to the local node, and CNI post-DNAT behavior must be proven live for the public Traefik HTTPS and NodePort paths; the private proof separately needs live allow/deny evidence for its ClusterIP bridge path. This static boundary does not complete PO-3.2: live allow/deny and served Gateway↔TCP Proxy bridge proof remain required. diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 2785a2c61f..f432df99fa 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -187,7 +187,7 @@ For both `standalone` and explicit `hosted-controller` preview modes, the previe On the explicit `hosted-controller` target path, that lifecycle prepares the runtime namespace, capacity allocation, bounded allocated preview Telnet NodePort (or fixed dev-demo NodePort `32016`), and requested base/head/merge/image tuple annotations with the runtime credential before a requester-only credential applies `HostedEnvironmentIdentity` `Active`. The controller materializes the retained identity namespace and cert-manager Certificate resources; it does not create disposable runtime namespaces. Only successful runtime deployment writes the distinct deployed-head annotation consumed by controller readiness; the trusted workflow writes the separate proof-complete tuple and Namespace UID only after all verification checks and the exact Namespace UID fence succeed. Close/merge cleanup deletes runtime and waits for exact `NotFound` before requesting `Retired`. All uncertain lifecycle/API results fail closed and retain identity. -Hosted verification waits for the complete readiness tuple defined by the owning [deployment-environments contract](./infrastructure/deployment-environments.md) before running the existing gameplay smoke; this CI/CD overview does not duplicate that tuple. In `hosted-controller` mode, preparation creates the runtime Namespace, records its requested base/head/merge/image tuple and port annotations, submits the active identity request, and waits for all five raw controller-projected Secrets before Helm installs or upgrades the runtime workloads. A deployed tuple alone is not reconciled health: after the verification checks and exact Namespace UID fence, the workflow records proof annotations containing the exact base/head/merge/image tuple and live Namespace UID, and the reconciler requires those annotations to match before it treats the preview as aligned. This ordering rule does not relax the separate bootstrap prerequisite: the fixed `firemud-system/firemud-grpc-ca` Secret must already exist before controller activation so the gRPC projection can be issued. `standalone` remains the default/current certificate-identity path until live controller activation and consumer-convergence proof exists; the `hosted-controller` target does not change stage or production deployment. +Hosted verification waits for the complete readiness tuple defined by the owning [deployment-environments contract](./infrastructure/deployment-environments.md) before running the existing gameplay smoke; this CI/CD overview does not duplicate that tuple. In `hosted-controller` mode, preparation creates the runtime Namespace, records its requested base/head/merge/image tuple and port annotations, submits the active identity request, and waits for the complete labeled, key-complete controller-projected Secret set—including the distinct Account and Game Session workload leaves—before Helm installs or upgrades the runtime workloads. A deployed tuple alone is not reconciled health: after the verification checks and exact Namespace UID fence, the workflow records proof annotations containing the exact base/head/merge/image tuple and live Namespace UID, and the reconciler requires those annotations to match before it treats the preview as aligned. This ordering rule does not relax the separate bootstrap prerequisite: the fixed `firemud-system/firemud-grpc-ca` Secret must already exist before controller activation so the gRPC projection can be issued. `standalone` remains the default/current certificate-identity path until live controller activation and consumer-convergence proof exists; the `hosted-controller` target does not change stage or production deployment. Main CI remains responsible for stack startup, smoke, and cross-service verification. Preview deployment is intentionally a separate concern focused on reviewer-accessible environments. Capacity exhaustion or infrastructure failure reports preview proof as unavailable; it never records a pass, and any claimed hosted proof is bound to the current pull-request base/head/merge/image tuple. diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index 4245d17195..241d57dc6a 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -122,7 +122,7 @@ World Management runtime-target seeding is isolated behind `SmokeDemoRuntimeSeed ### Hosted Preview, Dev-Demo, and Deployment Delivery -Hosted preview deploys real Helm releases into a prod-like stack, exposes a deliberately small preview-only TCP port range alongside HTTPS when public mode is selected, and seeds the minimum state for `LOGIN -> PLAY -> LOOK`. The explicit private mode supplied by #2821 and consumed by #2713 is a bounded bridge proof: a validated ClusterIP runtime has no public NodePort or Telnet smoke requirement, and its controller readiness must prove current-head-bound HTTPS, the private Gateway↔TCP Proxy mTLS bridge, gRPC, all ten projections (five shared-role projections and five per-workload publication projections), and rollout convergence. Public preview acceptance remains the #2795 child path and requires its allocated NodePort, served public Telnet, and the accepted deployed first-party browser path; a public failure cannot fall back to private mode. Preview is not a separate gameplay architecture and should not put product-specific browser helpers into Gateway. The preview workflow and enabled service/Helm seeders establish the tenant/game/runtime records used by the smoke target, while preview-only TCP Proxy defaults apply routing metadata (`tenantId`, `gameInstanceId`, world/realm, and pointer) to the connection before forwarding the client’s `LOGIN`. This internal metadata and seed state are not a pre-existing player gameplay session and add no client bootstrap command; supported public smoke acceptance remains `LOGIN -> PLAY -> LOOK`. The arrangement is temporary operational glue, not the long-term TCP admission model. These boundaries are defined in [Deployment Environments](../../architecture/infrastructure/deployment-environments.md) and [ADR 0178](../../architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md); no live controller rollout or private bridge proof is claimed yet. +Hosted preview deploys real Helm releases into a prod-like stack, exposes a deliberately small preview-only TCP port range alongside HTTPS when public mode is selected, and seeds the minimum state for `LOGIN -> PLAY -> LOOK`. The explicit private mode supplied by #2821 and consumed by #2713 is a bounded bridge proof: a validated ClusterIP runtime has no public NodePort or Telnet smoke requirement, and its controller readiness must prove current-head-bound HTTPS, the private Gateway↔TCP Proxy mTLS bridge, gRPC, all twelve runtime Secret projections (five shared-role projections and seven workload-specific projections), and rollout convergence. Public preview acceptance remains the #2795 child path and requires its allocated NodePort, served public Telnet, and the accepted deployed first-party browser path; a public failure cannot fall back to private mode. Preview is not a separate gameplay architecture and should not put product-specific browser helpers into Gateway. The preview workflow and enabled service/Helm seeders establish the tenant/game/runtime records used by the smoke target, while preview-only TCP Proxy defaults apply routing metadata (`tenantId`, `gameInstanceId`, world/realm, and pointer) to the connection before forwarding the client’s `LOGIN`. This internal metadata and seed state are not a pre-existing player gameplay session and add no client bootstrap command; supported public smoke acceptance remains `LOGIN -> PLAY -> LOOK`. The arrangement is temporary operational glue, not the long-term TCP admission model. These boundaries are defined in [Deployment Environments](../../architecture/infrastructure/deployment-environments.md) and [ADR 0178](../../architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md); no live controller rollout or private bridge proof is claimed yet. Preview allocation and reconciliation status: automatic eligibility, bounded two-slot first-come allocation, the maintainer-controlled priority exception, lifecycle serialization, cleanup, and bounded proof-retry controls have focused local/static contract evidence. Live hosted allocation, Actions-run query behavior, Namespace lifecycle, and proof-dispatch behavior remain unverified; normative behavior and the remaining proof boundary are owned by [Deployment Environments](../../architecture/infrastructure/deployment-environments.md#pr-preview-environment). @@ -142,11 +142,11 @@ The hosted credential boundary is now explicit: every secret-consuming preview, The recovery path is separate from routine hosted delivery: `.github/workflows/preview-ca-recovery.yml` runs only from `develop` in the protected GitHub Environment `trusted-preview-ca-recovery`, using `TRUSTED_PREVIEW_CA_RECOVERY_KUBECONFIG` and the protected `FIREMUD_PREVIEW_CA_RECOVERY_BUNDLE` secret. Its fingerprint and context are non-secret Environment variables. This recovery-only workflow and credential bundle are distinct from the `trusted-hosted-cluster` deployment credentials and are not selected by PR-controlled or routine deployment jobs. -The standalone PR-preview consumer owns fixed Telnet and Gateway bridge Certificate requests because PR-authored Certificate resources are stripped from the render artifact. The scoped standalone Certificate writer now also owns five fixed gRPC workload Certificates in both preview and dev-demo; the runtime workflow validates their leaf Secrets, adds only the public CA projection to its shared trust bundle, then deletes any legacy runtime-local CA signing key and static leaf-source Secrets. Focused contract proof covers fixed specs, namespace/name/SAN/issuer admission, and key-complete Secret waits; live cert-manager issuance, CA-bootstrap denial proof, served-certificate identity, and the eventual player smoke remain unproved. Hosted-controller projections comprise those five workload leaves plus the five shared-role Secrets for ingress, Telnet, Gateway WebSocket, TCP Proxy bridge, and the shared gRPC bundle. +The standalone PR-preview consumer owns fixed Telnet and Gateway bridge Certificate requests because PR-authored Certificate resources are stripped from the render artifact. The scoped standalone Certificate writer owns seven fixed gRPC workload Certificates in both preview and dev-demo: the five publication workloads plus Account and Game Session. The runtime workflow validates their leaf Secrets, adds only the public CA projection to its shared trust bundle, then deletes any legacy runtime-local CA signing key and static leaf-source Secrets. Focused contract proof covers fixed specs, namespace/name/SAN/issuer admission, and key-complete Secret waits; live cert-manager issuance, CA-bootstrap denial proof, served-certificate identity, and the eventual player smoke remain unproved. Hosted-controller runtime projections comprise those seven workload leaves plus the five shared-role Secrets for ingress, Telnet, Gateway WebSocket, TCP Proxy bridge, and the shared gRPC bundle, for twelve total. Static/live boundary: `hosted-identity-controller-manifest-contract.sh`, `hosted-identity-controller-workflow-contract.sh`, `dev-demo-workflow-contract.sh`, and architecture-document checks are static or local prerequisite proof only. They do not establish a live controller deployment, exact NetworkPolicy allow/deny behavior, CNI post-DNAT behavior, issued certificate, runtime Namespace binding, Helm consumer activation, served-certificate probe, or consumer rollout. PO-3.2 remains incomplete until live allow/deny and served Gateway↔TCP Proxy bridge proof are available. -Exact remaining live-proof prerequisites for the #2713 private parent are: (1) populate and verify the protected `trusted-hosted-cluster` Environment with the distinct runtime, preview, GHCR, and requester credential bindings while keeping requester credentials inside the trusted workflow boundary; it currently has zero secrets; (2) prepare the live cluster, which currently has no hosted-identity controller CRD or Deployment, controller CA Secret, or requester credential, by provisioning the fixed CA and pull Secret, installing the attested digest-pinned controller and fail-closed policies, and proving the configured API/probe address readback; (3) publish the stable #2713 head and run the trusted workflow against a sanitized private artifact whose runtime Namespace has the exact mode label, ClusterIP Service, no NodePort, and no Telnet-port annotation; (4) observe all ten key-complete projections (five shared-role projections and five per-workload publication projections) and Gateway/TCP Proxy rollouts, current-head/Namespace-UID/generation-bound controller `Ready`, served HTTPS, the private mutual-TLS Gateway↔TCP Proxy bridge, gRPC, and the live controller NetworkPolicy allow/deny boundary; and (5) retain non-secret, head-bound evidence for each result. None of these live prerequisites is currently satisfied, so PO-3.2 and private hosted proof remain open. The public NodePort/Telnet smoke and later deployed-browser proof remain separate #2795 obligations. +Exact remaining live-proof prerequisites for the #2713 private parent are: (1) populate and verify the protected `trusted-hosted-cluster` Environment with the distinct runtime, preview, GHCR, and requester credential bindings while keeping requester credentials inside the trusted workflow boundary; it currently has zero secrets; (2) prepare the live cluster, which currently has no hosted-identity controller CRD or Deployment, controller CA Secret, or requester credential, by provisioning the fixed CA and pull Secret, installing the attested digest-pinned controller and fail-closed policies, and proving the configured API/probe address readback; (3) publish the stable #2713 head and run the trusted workflow against a sanitized private artifact whose runtime Namespace has the exact mode label, ClusterIP Service, no NodePort, and no Telnet-port annotation; (4) observe all twelve key-complete runtime projections (five shared-role projections and seven workload-specific projections, including Account and Game Session) and Gateway/TCP Proxy rollouts, current-head/Namespace-UID/generation-bound controller `Ready`, served HTTPS, the private mutual-TLS Gateway↔TCP Proxy bridge, gRPC, and the live controller NetworkPolicy allow/deny boundary; and (5) retain non-secret, head-bound evidence for each result. None of these live prerequisites is currently satisfied, so PO-3.2 and private hosted proof remain open. The public NodePort/Telnet smoke and later deployed-browser proof remain separate #2795 obligations. The fixed `develop` environment is a separate `dev-demo-cluster`, not a PR preview: namespace `dev`, release `dev`, hostname `dev.preview.firedevops.net`, and TCP port `32016`. Its workflow and scheduled reconciler deploy the current `develop` head, reset the namespace for reproducibility, and prove `LOGIN -> PLAY -> LOOK`; it is not a promotion source, rollback-evidence source, or DR-attestation source. PR janitor/capacity logic applies only to `pr-*` namespaces. Player-facing staging and production use the canonical Kustomize overlays, while hosted Helm retains preview/dev-demo ownership. diff --git a/dev-tools/certs/README.md b/dev-tools/certs/README.md index e91e114763..7552e3301d 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -8,6 +8,6 @@ Generated certificate outputs in this directory are ignored by Git and should no - `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target is provided. - `dev-tools/certs/generate-dev-certs.sh --workload` signs a local development or test-only publication leaf with the exact SPIFFE URI and service DNS SANs. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. -- Standalone hosted runs retain the legacy shared bundle for non-publication workloads and consume only cert-manager's five runtime-facing `firemud-grpc-` leaf Secrets. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. +- Standalone hosted runs retain the legacy shared bundle for other gRPC workloads and consume seven cert-manager-issued runtime-facing `firemud-grpc-` leaf Secrets: five publication workloads, Account, and Game Session. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. - `dev-tools/certs/ensure-dev-certs.sh` guarantees the canonical local smoke entrypoints have the required cert/key set in place before Compose boots. - `dev-tools/certs/clean-dev-certs.sh` removes generated certificate files from `dev-tools/certs/` unless a target directory or `CERT_DIR` override is provided. From c4a73b0a7caa988c5517143c5652dc46bad245af Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:15:21 +1300 Subject: [PATCH 05/75] docs: align seven workload certificate bootstrap guidance --- .../infrastructure/environment-and-secrets-overview.md | 4 ++-- design/architecture/system-architecture-deployment-runbook.md | 2 +- k8s/helm/README.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/design/architecture/infrastructure/environment-and-secrets-overview.md b/design/architecture/infrastructure/environment-and-secrets-overview.md index baa1a7def2..f35c83fa97 100644 --- a/design/architecture/infrastructure/environment-and-secrets-overview.md +++ b/design/architecture/infrastructure/environment-and-secrets-overview.md @@ -135,7 +135,7 @@ This section describes the Kubernetes-backed environments that use the canonical - Kubernetes `ConfigMap` objects store non‑secret configuration values like host names or feature flags. - Sensitive values (database passwords, TLS private keys, and interim JWT signing bundles) are delivered through Kubernetes `Secret` objects. The public `jwt-jwks` projection is delivered separately as read-only public material; hosted preview materializes it as a `ConfigMap`. -- TLS certificates are issued by **cert-manager** and rotated automatically; the canonical target gives each workload a distinct leaf certificate/private-key Secret. Current hosted manifests give five publication services distinct leaf Secrets and project only `ca.crt` from the shared `firemud-grpc-tls` trust bundle into those Pods. The other gRPC workloads still use the shared leaf identity, so hosted rendering remains incomplete evidence for the full target identity boundary and is not player-facing equivalence. Services reload updated certificates using `TlsCertificateWatcher` / `GrpcServerTlsReloader`. +- TLS certificates are issued by **cert-manager** and rotated automatically. The seven gRPC workload consumers (the five publication services plus Account and Game Session) use distinct leaf certificate/private-key Secrets; other gRPC workloads still use the shared leaf identity. Publication Pods use their own Secret for the leaf and key and project only `ca.crt` from the shared `firemud-grpc-tls` bundle for peer trust. The checked-in Kustomize Account and Game Session Pods use `/tls/ca.crt` from their respective leaf Secret for peer trust, while hosted Helm projects `ca.crt` from the shared bundle for these workloads too. Hosted rendering remains incomplete evidence for the full target identity boundary and is not player-facing equivalence. Services reload updated certificates using `TlsCertificateWatcher` / `GrpcServerTlsReloader`. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). - JWT authority and lifecycle are defined by [JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md). This overview records only the interim Account private-bundle mount, public JWKS mounts, and watcher delivery. - In player-facing environments (`hobby-self-hosted`, staging, production), the selected `INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK` mode allows only Account Service to consume JWT private signing material from a mounted file via `FIREMUD_AUTH_JWT_SECRET_PATH`, and only Account uses `JwtSecretWatcher` on that path; Account and every validator must consume the public JWKS projection. The selected `TARGET_NON_EXPORTABLE_SIGNER` mode has no private path or application private material and uses the same public-JWKS consumer boundary. The current `LEGACY_SECRET_DIAGNOSTIC` mode is shared-HMAC Secret/path wiring evidence only and is never player-facing authorization; inline-only or HMAC-only configuration and private-key mounts in validators are non-compliant for accepted modes. Current hosted preview is a separate HMAC/test wiring path and its hosted validation does not prove validator consumption. - Database credentials are stored in Secrets and rotated via explicit operational Jobs and runbooks (for example `db-credential-rotation` in `system-architecture-backup-recovery.md#post-restore-secret-hardening`); there is no fully automatic cadence today. @@ -446,7 +446,7 @@ The catalog document groups these variables by subsystem (PostgreSQL, Redis, TLS ## Certificate Management and Watchers -Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; see [Security Architecture](../system-architecture-security.md#cross-service-trust). Explicit local-development and throwaway-test profiles may use the documented plaintext internal transports and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. In hosted `pr-preview` and `dev-demo-cluster`, trusted certificate workflows request distinct cert-manager-issued leaves for the five publication services. The checked-in `k8s/base/` Pod manifests only bind and mount the corresponding `firemud-grpc-` Secrets; they do not issue those certificates. Live leaf issuance and consumer readiness must be proven before hosted identity activation. Staging and production operators must provision the five namespace-scoped publication Secrets and the shared `firemud-grpc-tls` trust bundle through the environment bootstrap process in the [deployment runbook](../system-architecture-deployment-runbook.md#environment-bootstrap). The remaining gRPC workloads continue to use the legacy shared leaf. Each publication Pod reads peer trust from only the public `ca.crt` key projected from `firemud-grpc-tls`; its private identity remains the service-specific `tls.crt` and `tls.key`. The shared CA bundle contains the legacy and current issuer trust anchors so these publication workloads can verify peers using either leaf generation. Hosted rendering remains non-player-facing/non-promotion evidence. The canonical target provisions distinct per-workload leaf certificate/private-key Secrets so each service has a concrete private identity. These certificates secure: +Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; see [Security Architecture](../system-architecture-security.md#cross-service-trust). Explicit local-development and throwaway-test profiles may use the documented plaintext internal transports and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. In hosted `pr-preview` and `dev-demo-cluster`, trusted certificate workflows provision distinct cert-manager-issued leaves for the five publication services, Account, and Game Session. The checked-in `k8s/base/` Pod manifests bind and mount each workload's corresponding `firemud-grpc-` Secret; they do not issue those certificates. Live leaf issuance and consumer readiness must be proven before hosted identity activation. Staging and production operators must provision all seven namespace-scoped workload Secrets and the shared `firemud-grpc-tls` trust bundle through the environment bootstrap process in the [deployment runbook](../system-architecture-deployment-runbook.md#environment-bootstrap). Other gRPC workloads continue to use the legacy shared leaf. Publication Pods read peer trust from only the public `ca.crt` key projected from `firemud-grpc-tls`, while their private identities remain in their service-specific Secrets. The checked-in Kustomize Account and Game Session Pods read peer trust from `/tls/ca.crt` in their respective leaf Secrets; hosted Helm instead uses the shared bundle's `ca.crt` projection for those workloads. The shared CA bundle must validate each of the seven distinct workload leaves as well as the shared leaf, so workloads using the shared trust projection can verify either leaf generation. Hosted rendering remains non-player-facing/non-promotion evidence. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). These certificates secure: - All mTLS-protected gRPC calls between services - Any internal WebSocket bridges that require mTLS (for example, the TCP Proxy Service connecting to Spring Cloud Gateway over `wss://`) diff --git a/design/architecture/system-architecture-deployment-runbook.md b/design/architecture/system-architecture-deployment-runbook.md index b3326d565a..0eb513c08d 100644 --- a/design/architecture/system-architecture-deployment-runbook.md +++ b/design/architecture/system-architecture-deployment-runbook.md @@ -38,7 +38,7 @@ Before the first player-facing deployment into `hobby-self-hosted`, `staging`, o 1. Provision the target namespace and registry pull credentials used by workloads. 2. Provision per-environment PostgreSQL credentials (`postgres-credentials`) and, when rotation Jobs are used, `postgres-admin-credentials`. 3. Select and record the custody state before applying workloads. The checked-in player-facing Kustomize mode is legacy Secret-backed signing plus public Secret JWKS wiring (`jwt-signing-keys` Secret and `jwt-jwks` Secret); it may appear in pre-apply diagnostics but is non-authorizing and is not an accepted player-facing custody state. Hosted preview Helm remains a separate diagnostic ConfigMap-backed path. For `INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK`, establish trusted pre-apply evidence for the pre-created interim `jwt-signing-keys` Secret, the separate interim Account-owned public `jwt-jwks` ConfigMap, and the materialization controller's name-scoped RBAC. Account has exclusive mounted/signing use of the private bundle; the materialization controller has only bounded, Account-authorized byte handling needed to materialize it and no competing signing authority. The [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md#signing-key-rotation-contract-normative) define custody and operation authority; this runbook requires every private-slot `generate`, `materialize`, `resourceVersion`-CAS, and `prune` action to use a persisted Account-authorized operation, with the controller executing only that operation and unable to choose slots or mutate desired key-ring state independently. For target non-exportable signer mode, establish trusted pre-apply evidence for the approved signer reference, target Account-owned public `jwt-jwks` ConfigMap, Account publication/CAS authority, and no private-material mount or distribution. In both accepted modes, `FIREMUD_AUTH_JWKS_PATH` is mandatory for Account and every validator; only the interim mode sets `FIREMUD_AUTH_JWT_SECRET_PATH`, while target non-exportable signer mode leaves it unset. These bootstrap records prove intended bindings and custody boundaries only; post-apply live signer, public-JWKS, and validator convergence is a separate owner-produced gate. -4. Provision cert-manager issuer bindings and certificate resources required for workload gRPC mTLS, Gateway internal mTLS WebSocket listener, TCP Proxy bridge mTLS client identity, and operator-only client identities where applicable. Also provision the five distinct publication-reader workload certificates as namespace-scoped Secrets named `firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`. Each publication Secret must contain non-empty `ca.crt`, `tls.crt`, and `tls.key` entries; its `ca.crt` must establish trust for that Secret's own leaf certificate. The `firemud-grpc-tls` shared bundle must contain the shared client leaf and a `ca.crt` trust bundle that validates both that shared leaf's issuer and the issuer of each of the five distinct publication leaves. Runtime publication-reader Pods mount their own publication Secret for the client leaf and key, and use only the shared `firemud-grpc-tls` CA bundle for trust. Each leaf must be non-CA and use exactly the `digital signature` and `key encipherment` key usages and exactly the `server auth` and `client auth` extended key usages. For each workload, set exactly the service URI SAN `spiffe://firemud/ns//sa/` and DNS SANs ``, `.`, `..svc`, and `..svc.cluster.local`; replace `` and `` with the target namespace and that Secret's service name. In this SPIFFE URI, `` names the service workload; it is not a value derived from the Pod's Kubernetes ServiceAccount name. Keep every workload leaf and private key distinct. Use the established issuance and trust process for the environment. `dev-tools/certs/generate-dev-certs.sh --workload` documents the canonical leaf profile, while `dev-tools/hosted/shared/ensure-grpc-tls-secret.sh` shows how hosted setup validates projected cert-manager leaf files and adds their issuer CA to the shared trust bundle. These development/hosted helpers are references for certificate contents and validation; they do not replace production CA custody, issuer authorization, or the environment's approved certificate-issuance procedure. +4. Provision cert-manager issuer bindings and certificate resources required for workload gRPC mTLS, Gateway internal mTLS WebSocket listener, TCP Proxy bridge mTLS client identity, and operator-only client identities where applicable. Also provision the five distinct publication-reader workload certificates as namespace-scoped Secrets named `firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`, plus the distinct Account and Game Session workload Secrets `firemud-grpc-account-service` and `firemud-grpc-game-session-service`. Each of these seven leaf Secrets must contain non-empty `ca.crt`, `tls.crt`, and `tls.key` entries; its `ca.crt` must establish trust for that Secret's own leaf certificate. The `firemud-grpc-tls` shared bundle must contain the shared client leaf and a `ca.crt` trust bundle that validates the shared leaf and all seven distinct workload leaves. Runtime publication-reader Pods mount their own publication Secret for the client leaf and key, and use only the shared `firemud-grpc-tls` CA bundle for trust. The checked-in Kustomize Account and Game Session Pods mount their respective full leaf Secret and use its `/tls/ca.crt` for peer trust; each of those Secrets' `ca.crt` must include the issuer trust needed for the gRPC peers those Pods call. Hosted Helm workloads use their own Secret for the leaf certificate and key and only the shared bundle's `ca.crt` for peer trust. This bootstrap requirement describes Secret contents and manifest bindings; it does not claim that issued Secrets, mounted certificates, or live workload readiness have been verified. Each workload leaf must be non-CA and use exactly the `digital signature` and `key encipherment` key usages and exactly the `server auth` and `client auth` extended key usages. For each workload, set exactly the service URI SAN `spiffe://firemud/ns//sa/` and DNS SANs ``, `.`, `..svc`, and `..svc.cluster.local`; replace `` and `` with the target namespace and that Secret's service name. In this SPIFFE URI, `` names the service workload; it is not a value derived from the Pod's Kubernetes ServiceAccount name. Keep every workload leaf and private key distinct. Use the established issuance and trust process for the environment. The [deployment-environment contract](./infrastructure/deployment-environments.md) and [ADR 0038](./decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md) own the canonical identity boundary. `dev-tools/certs/generate-dev-certs.sh --workload` documents the canonical leaf profile, while `dev-tools/hosted/shared/ensure-grpc-tls-secret.sh` shows how hosted setup validates projected cert-manager leaf files and adds their issuer CA to the shared trust bundle. These development/hosted helpers are references for certificate contents and validation; they do not replace production CA custody, issuer authorization, or the environment's approved certificate-issuance procedure. 5. Provision per-environment external integration credentials: backup/object-store, asset-store, outbound-communications, and operator-control-plane credentials as needed for that environment class. 6. Run `./dev-tools/deploy/preflight.py ` and require the common checks `PREFLIGHT-BOOTSTRAP-001`, `PREFLIGHT-SECRETS-001`, `PREFLIGHT-SECRETS-002`, `PREFLIGHT-BRIDGE-001`, `PREFLIGHT-REDIS-001`, `PREFLIGHT-EXTERNAL-001`, and `PREFLIGHT-SERVICES-001`, plus exactly one authenticated custody proof whose `proofId`, `custodyMode`, and `contractVersion` exactly match the selected mode: `PREFLIGHT-JWT-INTERIM-001` for `INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK` or `PREFLIGHT-JWT-002` for `TARGET_NON_EXPORTABLE_SIGNER`. Preserve that exact tuple in the deployment record for retry/replay. An unknown, unsupported, or not-yet-implemented state fails closed. `PREFLIGHT-JWT-001` and `PREFLIGHT-JWKS-001` may be emitted as legacy diagnostic wiring results, but they are never custody proof or player-facing readiness evidence and cannot substitute for the selected custody proof. 7. Record trusted pre-apply bootstrap secret-compliance evidence for each Tier A credential class. First deployment may use immutable initial-provisioning evidence (`lastProvisionedAt`) instead of rotation evidence, but the record must still satisfy the canonical secret-compliance schema before the environment is considered promotable or traffic-open. This evidence proves provisioning and binding only; it does not prove live signer or validator convergence. diff --git a/k8s/helm/README.md b/k8s/helm/README.md index 2225957dc9..cea4942839 100644 --- a/k8s/helm/README.md +++ b/k8s/helm/README.md @@ -48,7 +48,7 @@ helm upgrade --install pr-123 ./firemud \ --create-namespace ``` -Before applying the full-stack chart with publication workloads enabled, the trusted environment setup must provision these namespace-scoped leaf Secrets: `firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`. It must also provision the shared `firemud-grpc-tls` trust bundle. Standalone hosted setup uses the trusted [`ensure-standalone-grpc-certificates.sh`](../../dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh) Certificate writer for the five leaves; hosted-controller setup must wait for all five projections. Other environments must follow the approved issuance and bootstrap process in the [deployment runbook](../../design/architecture/system-architecture-deployment-runbook.md). Direct `helm template` only renders Secret references; it does not prove that the Secrets exist or are ready. Keep certificate material and secret credentials out of PR-controlled values and workflows. +Before applying the full-stack chart, trusted environment setup must provision these seven namespace-scoped workload leaf Secrets: `firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, `firemud-grpc-automation-scripting-service`, `firemud-grpc-account-service`, and `firemud-grpc-game-session-service`. It must also provision the shared `firemud-grpc-tls` trust bundle with issuer CA trust for all seven leaves. Standalone hosted setup uses the trusted [`ensure-standalone-grpc-certificates.sh`](../../dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh) Certificate writer for all seven leaves; hosted-controller setup must wait for all seven workload Secret projections before applying the chart. Hosted Helm workloads use their own Secret for the leaf certificate and key and the shared bundle's `ca.crt` projection for peer trust. Other environments must follow the approved issuance and bootstrap process in the [deployment runbook](../../design/architecture/system-architecture-deployment-runbook.md), under the canonical [deployment-environment contract](../../design/architecture/infrastructure/deployment-environments.md) and [ADR 0038](../../design/architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). Direct `helm template` only renders Secret references; it does not prove that the Secrets exist or are ready. Keep certificate material and secret credentials out of PR-controlled values and workflows. The hosted chart owns public `jwt-jwks` as a `ConfigMap`. Helm treats a same-name legacy Secret and the target ConfigMap as distinct resource identities, so the upgrade creates the ConfigMap and removes the obsolete Secret without a manual pre-delete. The `dev-tools/tests/helm-jwks-contract.sh` test proves the target rendered resource and workload wiring; it is not a live-cluster upgrade or downtime proof. From 6519ba3236984987f54a7e004acaa4c8a45185ae Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:51:45 +1300 Subject: [PATCH 06/75] fix: verify Game Session served workload identity before ready --- .../infrastructure/deployment-environments.md | 2 +- .../tests/hosted-gateway-bridge-contract.sh | 48 ++++++----- ...d-identity-controller-manifest-contract.sh | 32 ++++--- .../firemud/templates/network-policies.yaml | 8 +- k8s/hosted-identity-controller/README.md | 4 +- .../networkpolicy.yaml | 18 +++- .../probe/ServedEnvironmentProbe.java | 85 +++++++++++++++++-- .../reconcile/HostedIdentityReconciler.java | 5 +- .../probe/ServedEnvironmentProbeTest.java | 37 ++++++-- .../HostedIdentityReconcilerSafetyTest.java | 72 +++++++++++++++- 10 files changed, 247 insertions(+), 64 deletions(-) diff --git a/design/architecture/infrastructure/deployment-environments.md b/design/architecture/infrastructure/deployment-environments.md index fc504f2c47..8a7dd7352e 100644 --- a/design/architecture/infrastructure/deployment-environments.md +++ b/design/architecture/infrastructure/deployment-environments.md @@ -346,7 +346,7 @@ Before a trusted operator activates the hosted identity controller, that operato Runtime reclaim, redeploy, release, and lease expiry delete only the runtime namespace. Close/merge retirement is runtime-first: the trusted lifecycle deletes the exact runtime, requires a successful empty `--ignore-not-found` lookup proving Namespace `NotFound`, and only then requests `Retired`; lookup or deletion uncertainty retains identity and fails closed. Explicit identity removal of a live runtime is retirement-first: the trusted requester sets `Retired`, the controller scales Gateway and TCP Proxy to zero and waits for their observed shutdown, and the trusted runtime lifecycle then deletes the runtime and proves exact Namespace `NotFound`. In both paths, retained identity deletion remains blocked until the runtime is absent. Before deleting retained identity, the controller accounts for all twelve runtime Secret projections: five shared-role projections for (1) [public ingress TLS](../system-architecture-security.md#tls-termination-for-gateway), (2) [public Telnet TLS](../system-architecture-protocol-bridging.md#public-telnet-tls-modes), (3) the [Gateway internal WebSocket server](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), (4) the [TCP Proxy bridge client](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), and (5) the [shared gRPC transport bundle](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md#mtls-identity-and-certificate-lifecycle), plus seven distinct per-workload gRPC projections: the five publication workloads (`firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`), Account (`firemud-grpc-account-service`), and Game Session (`firemud-grpc-game-session-service`). Controller readiness binds the CR generation, live runtime namespace UID, exact requested and deployed head SHA pair, rollout and mode-specific served proof, and non-empty revisions for each of the five shared-role projections and each of the seven workload projections; public mode additionally requires the served Telnet probe. Canonical 40-hex SHA values are normalized before equality comparison. This controller contract is local/static proof only until a live hosted rollout; it does not alter stage or production deployment paths. -The hosted identity controller's egress boundary is exact-destination and operator-rendered. Its checked-in NetworkPolicy contains no `0.0.0.0/0` or `::/0`; trusted bootstrap substitutes validated `/32` IPv4 CIDRs for the observed `kubernetes.default` Service ClusterIP on TCP/443, the single API endpoint on TCP/6443, and the fixed public preview probe on TCP/443 plus NodePorts 32000-32016. Gateway access is separately limited to `spring-cloud-gateway` pods in the canonical preview and dev-demo namespaces on TCP/443 and TCP/8443. The observed k3s LoadBalancer path additionally requires the exact kube-system Traefik pod selector on TCP/8443 after public HTTPS DNAT, and the public TCP Proxy NodePort path requires the exact `tcp-proxy-service` selectors in those canonical namespaces on TCP/2323 after NodePort DNAT. DNS and Account TCP/6565 selectors remain explicit. `observe` and `active` bootstrap require all three addresses, require exactly one matching fixed public DNS A record, and verify the API Service and single-endpoint readback before any write; paused mode without addresses renders loopback-only deny markers. Standard NetworkPolicy may exempt traffic to the local node, and CNI post-DNAT behavior must be proven live for the public Traefik HTTPS and NodePort paths; the private proof separately needs live allow/deny evidence for its ClusterIP bridge path. This static boundary does not complete PO-3.2: live allow/deny and served Gateway↔TCP Proxy bridge proof remain required. +The hosted identity controller's egress boundary is exact-destination and operator-rendered. Its checked-in NetworkPolicy contains no `0.0.0.0/0` or `::/0`; trusted bootstrap substitutes validated `/32` IPv4 CIDRs for the observed `kubernetes.default` Service ClusterIP on TCP/443, the single API endpoint on TCP/6443, and the fixed public preview probe on TCP/443 plus NodePorts 32000-32016. Gateway access is separately limited to `spring-cloud-gateway` pods in the canonical preview and dev-demo namespaces on TCP/443 and TCP/8443. The observed k3s LoadBalancer path additionally requires the exact kube-system Traefik pod selector on TCP/8443 after public HTTPS DNAT, and the public TCP Proxy NodePort path requires the exact `tcp-proxy-service` selectors in those canonical namespaces on TCP/2323 after NodePort DNAT. DNS and the Account and Game Session TCP/6565 selectors remain explicit and label-scoped. `observe` and `active` bootstrap require all three addresses, require exactly one matching fixed public DNS A record, and verify the API Service and single-endpoint readback before any write; paused mode without addresses renders loopback-only deny markers. Standard NetworkPolicy may exempt traffic to the local node, and CNI post-DNAT behavior must be proven live for the public Traefik HTTPS and NodePort paths; the private proof separately needs live allow/deny evidence for its ClusterIP bridge path. This static boundary does not complete PO-3.2: live allow/deny and served Gateway↔TCP Proxy bridge proof remain required. - Same-repo pull requests may deploy one Helm release into namespace `pr-` with matching hostname `https://pr-.preview.`. - The preview deployment uses the full application stack, including the gateway, TCP proxy, backend microservices, and stateful supporting services required for normal gameplay flows. diff --git a/dev-tools/tests/hosted-gateway-bridge-contract.sh b/dev-tools/tests/hosted-gateway-bridge-contract.sh index d038d231e5..76f5216aca 100644 --- a/dev-tools/tests/hosted-gateway-bridge-contract.sh +++ b/dev-tools/tests/hosted-gateway-bridge-contract.sh @@ -348,28 +348,29 @@ if labelled_objects != {("Deployment", "tcp-proxy-service"), ("Service", "tcp-pr "certificate identity mode label rendered on an unexpected hosted object" ) -account_policy = named("NetworkPolicy", "account-service-controller-ingress")["spec"] -if account_policy != { - "podSelector": {"matchLabels": {"app": "account-service"}}, - "policyTypes": ["Ingress"], - "ingress": [{ - "from": [{ - "namespaceSelector": { - "matchLabels": {"kubernetes.io/metadata.name": "firemud-system"} - }, - "podSelector": { - "matchLabels": { - "app.kubernetes.io/name": "hosted-environment-identity-controller", - "app.kubernetes.io/component": "controller", - } - }, +for workload in ("account-service", "game-session-service"): + workload_policy = named("NetworkPolicy", f"{workload}-controller-ingress")["spec"] + if workload_policy != { + "podSelector": {"matchLabels": {"app": workload}}, + "policyTypes": ["Ingress"], + "ingress": [{ + "from": [{ + "namespaceSelector": { + "matchLabels": {"kubernetes.io/metadata.name": "firemud-system"} + }, + "podSelector": { + "matchLabels": { + "app.kubernetes.io/name": "hosted-environment-identity-controller", + "app.kubernetes.io/component": "controller", + } + }, + }], + "ports": [{"protocol": "TCP", "port": 6565}], }], - "ports": [{"protocol": "TCP", "port": 6565}], - }], -}: - raise SystemExit( - "Hosted Account ingress policy must allow only the identity controller to TCP 6565" - ) + }: + raise SystemExit( + f"Hosted {workload} ingress policy must allow only the identity controller to TCP 6565" + ) gateway_policy = named("NetworkPolicy", "spring-cloud-gateway-ingress")["spec"] if gateway_policy["podSelector"] != {"matchLabels": {"app": "spring-cloud-gateway"}}: @@ -498,11 +499,12 @@ documents = [ ] if any( document.get("kind") == "NetworkPolicy" - and document.get("metadata", {}).get("name") == "account-service-controller-ingress" + and document.get("metadata", {}).get("name") + in {"account-service-controller-ingress", "game-session-service-controller-ingress"} for document in documents ): raise SystemExit( - "standalone certificate identity mode unexpectedly rendered the hosted controller Account ingress policy" + "standalone certificate identity mode unexpectedly rendered a hosted controller gRPC ingress policy" ) for kind in ("Deployment", "Service"): matches = [ diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index 7fcb5bf5a9..be4d6e9e94 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -2066,22 +2066,28 @@ tcp_proxy_rules = [ ] assert len(tcp_proxy_rules) == 1 assert tcp_proxy_rules[0]["ports"] == [{"protocol": "TCP", "port": 2323}] -grpc_targets = [ - target +grpc_rules = [ + rule for rule in policy["spec"]["egress"] if any(port.get("port") == 6565 for port in rule.get("ports", [])) - for target in rule.get("to", []) ] -assert grpc_targets, "controller gRPC egress rule is missing" -for target in grpc_targets: - assert target.get("namespaceSelector", {}).get("matchLabels", {}).get( - "firemud.dev/preview" - ) == "true" or target.get("namespaceSelector", {}).get("matchLabels", {}).get( - "firemud.dev/dev-demo" - ) == "true", target - assert target.get("podSelector", {}).get("matchLabels") == { - "app": "account-service" - }, target +assert len(grpc_rules) == 1, grpc_rules +assert grpc_rules[0]["ports"] == [{"protocol": "TCP", "port": 6565}] +grpc_targets = grpc_rules[0]["to"] +assert { + ( + tuple(sorted(target["namespaceSelector"]["matchLabels"].items())), + tuple(sorted(target["podSelector"]["matchLabels"].items())), + ) + for target in grpc_targets +} == { + (namespace, (("app", workload),)) + for namespace in ( + (("firemud.dev/preview", "true"),), + (("firemud.dev/dev-demo", "true"),), + ) + for workload in ("account-service", "game-session-service") +}, grpc_targets PY for text_value in \ FIREMUD_HOSTED_IDENTITY_TRUSTED_OPERATOR \ diff --git a/k8s/helm/firemud/templates/network-policies.yaml b/k8s/helm/firemud/templates/network-policies.yaml index f40e18b14e..602ee69048 100644 --- a/k8s/helm/firemud/templates/network-policies.yaml +++ b/k8s/helm/firemud/templates/network-policies.yaml @@ -121,17 +121,18 @@ spec: - protocol: TCP port: 9000 {{- if eq $certificateIdentityMode "hosted-controller" }} +{{- range $workload := list "account-service" "game-session-service" }} --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: - name: account-service-controller-ingress + name: {{ $workload }}-controller-ingress labels: -{{ include "firemud.commonLabels" . | indent 4 }} +{{ include "firemud.commonLabels" $ | indent 4 }} spec: podSelector: matchLabels: - app: account-service + app: {{ $workload }} policyTypes: - Ingress ingress: @@ -147,6 +148,7 @@ spec: - protocol: TCP port: 6565 {{- end }} +{{- end }} --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy diff --git a/k8s/hosted-identity-controller/README.md b/k8s/hosted-identity-controller/README.md index 940cc233ef..5a9d597215 100644 --- a/k8s/hosted-identity-controller/README.md +++ b/k8s/hosted-identity-controller/README.md @@ -38,7 +38,7 @@ Status contains only non-secret evidence: `observedGeneration`, phase, condition The phases are `Pending`, `Provisioning`, `WaitingForCertificate`, `RuntimeAbsent`, `Syncing`, `Verifying`, `Ready`, `Degraded`, `Blocked`, `Retiring`, and `Retired`. -Normal Active reconciliation observes the derived profile, ensures independent cert-manager ingress and Telnet Certificates/Secrets, retains the shared `firemud-grpc-tls` transport bundle without claiming per-workload identity, and issues separate `-gateway-internal-ws` server and `-tcp-proxy-bridge` client identities from the same fixed internal trust anchor without sharing leaf keys. The Gateway identity has only `serverAuth` and the exact `spring-cloud-gateway-mtls..svc.cluster.local` DNS SAN; the TCP Proxy identity has only `clientAuth` and the exact `spiffe://firemud/ns//sa/tcp-proxy-service` URI SAN. Reconciliation syncs source material to runtime with resource-version compare-and-swap, and rolls all eleven gRPC consumers before fixed-SNI/SAN/issuer endpoint probes. The final acceptance gate also performs a mutual-TLS handshake to the fixed Account gRPC Service with the current projected client certificate, fixed CA, exact in-cluster SNI/hostname, and current leaf fingerprint; rollout counters alone cannot make the identity Ready. It separately uses the projected TCP Proxy bridge identity to verify the exact Gateway-internal TLS server identity. Existing runtime Secret material is copied to its fixed `*-previous` snapshot in the retained identity namespace before replacement. A clean destination may be created without a predecessor. +Normal Active reconciliation observes the derived profile, ensures independent cert-manager ingress and Telnet Certificates/Secrets, retains the shared `firemud-grpc-tls` transport bundle without claiming per-workload identity, and issues separate `-gateway-internal-ws` server and `-tcp-proxy-bridge` client identities from the same fixed internal trust anchor without sharing leaf keys. The Gateway identity has only `serverAuth` and the exact `spring-cloud-gateway-mtls..svc.cluster.local` DNS SAN; the TCP Proxy identity has only `clientAuth` and the exact `spiffe://firemud/ns//sa/tcp-proxy-service` URI SAN. Reconciliation syncs source material to runtime with resource-version compare-and-swap, and rolls all eleven gRPC consumers before fixed-SNI/SAN/issuer endpoint probes. The final acceptance gate performs mutual-TLS handshakes to both fixed Account and Game Session gRPC Services with the current projected client certificate, fixed CA, exact in-cluster SNI/hostname, and each service's current leaf fingerprint; rollout counters alone cannot make either identity Ready. It separately uses the projected TCP Proxy bridge identity to verify the exact Gateway-internal TLS server identity. Existing runtime Secret material is copied to its fixed `*-previous` snapshot in the retained identity namespace before replacement. A clean destination may be created without a predecessor. Renewal repeats the same generation-safe sequence. Ordinary internal WebSocket identity renewal updates retained and projected material in place; it does not terminate the bridge. A consumer that has not reloaded the new identity keeps the controller non-ready. Explicit `Retired` intent while a runtime still exists instead scales both `spring-cloud-gateway` and `tcp-proxy-service` to zero and waits for their observed replica counts to reach zero before any retained identity cleanup can proceed, preventing stale in-memory identity reuse when replacement material is unavailable. @@ -52,7 +52,7 @@ Kubernetes RBAC cannot constrain `create`, `escalate`, or `bind` with `resourceN The NetworkPolicy is fail-closed for controller egress. Its raw manifest contains required address markers, and the trusted bootstrap replaces them with validated `/32` IPv4 CIDRs in a private render. `--api-service-ipv4`, `--api-endpoint-ipv4`, and `--public-probe-ipv4` are required together for `observe` or `active` mode; a paused bootstrap without them substitutes `127.0.0.1/32` for all three destinations so the break-glass pause cannot reopen broad egress. The bootstrap reads back the `kubernetes.default` Service ClusterIP and the single observed API endpoint on TCP/6443 before any cluster write, and fails closed unless the fixed `dev.preview.firedevops.net` lookup returns exactly one matching IPv4 A record. -The hosted k3s cluster uses flannel VXLAN with kube-router policy enforcement: `kubernetes.default` is exposed on ClusterIP `:443`, DNATed to the hosted node API endpoint `:6443`, and kube-router evaluates the effective post-DNAT destination port. Separate exact rules therefore cover the API Service on TCP/443, the observed API endpoint on TCP/6443, and the fixed public probe address on TCP/443 plus NodePorts 32000-32016. In the observed LoadBalancer path, public HTTPS is DNATed to the kube-system Traefik pods on TCP/8443. Only public preview mode uses the TCP Proxy NodePort path, which is DNATed to selected `tcp-proxy-service` pods on TCP/2323; private mode uses the in-cluster ClusterIP bridge and never requires that NodePort. The policy grants only exact, label-scoped target ports. A separate selector rule reaches only `spring-cloud-gateway` pods in namespaces carrying the externally owned canonical preview or dev-demo label on TCP/443 and TCP/8443. DNS and the label-scoped Account TCP/6565 rule remain unchanged. Kubernetes NetworkPolicy cannot identify an API server or public hostname, so the controller must enforce the derived SNI/SAN/issuer allowlist itself. Standard NetworkPolicy implementations may exempt traffic to the local node, and the actual post-DNAT behavior and exact allow/deny boundary—including public NodePort target-port behavior—must be proven live; static rendering is not operational proof. PO-3.2 remains incomplete until the live allow/deny matrix and served Gateway↔TCP Proxy bridge proof succeed. +The hosted k3s cluster uses flannel VXLAN with kube-router policy enforcement: `kubernetes.default` is exposed on ClusterIP `:443`, DNATed to the hosted node API endpoint `:6443`, and kube-router evaluates the effective post-DNAT destination port. Separate exact rules therefore cover the API Service on TCP/443, the observed API endpoint on TCP/6443, and the fixed public probe address on TCP/443 plus NodePorts 32000-32016. In the observed LoadBalancer path, public HTTPS is DNATed to the kube-system Traefik pods on TCP/8443. Only public preview mode uses the TCP Proxy NodePort path, which is DNATed to selected `tcp-proxy-service` pods on TCP/2323; private mode uses the in-cluster ClusterIP bridge and never requires that NodePort. The policy grants only exact, label-scoped target ports. A separate selector rule reaches only `spring-cloud-gateway` pods in namespaces carrying the externally owned canonical preview or dev-demo label on TCP/443 and TCP/8443. DNS and the label-scoped Account and Game Session TCP/6565 selectors remain exact. Kubernetes NetworkPolicy cannot identify an API server or public hostname, so the controller must enforce the derived SNI/SAN/issuer allowlist itself. Standard NetworkPolicy implementations may exempt traffic to the local node, and the actual post-DNAT behavior and exact allow/deny boundary—including public NodePort target-port behavior—must be proven live; static rendering is not operational proof. PO-3.2 remains incomplete until the live allow/deny matrix and served Gateway↔TCP Proxy bridge proof succeed. The checked-in Deployment contains fail-closed image and activation markers. `bootstrap-hosted-identity-controller.sh` accepts only the approved image repository with a full SHA-256 digest and an explicit `paused`, `observe`, or `active` mode. Before invoking `kubectl`, it uses GitHub CLI attestation verification to require default SLSA provenance from this repository's `runtime-images.yml` workflow on exactly `develop` or `main` and rejects self-hosted-runner provenance. The trusted operator context therefore requires Python 3 with PyYAML, `gh` authenticated for GitHub API and private-repository attestation reads, read authentication for the private GHCR image, and network access to GitHub API, GHCR, and the Sigstore trust services used by GitHub attestations. After verification, bootstrap substitutes the image, gRPC trust-anchor fingerprint, and mode in a private render. For every mode, it validates the fixed `firemud-system/firemud-grpc-ca` certificate, key, and configured fingerprint before its first cluster write. It then applies and reads back the fail-closed namespace guard and its `Deny` binding before applying the namespace-lifecycle ClusterRoleBinding, followed by server-side apply without force-conflict takeover for the complete install. Its default is `paused`; Active bootstrap retains the later gate that verifies every required validating admission policy and binding before the controller is permitted to reconcile. diff --git a/k8s/hosted-identity-controller/networkpolicy.yaml b/k8s/hosted-identity-controller/networkpolicy.yaml index 1b2d40475a..10a828bde7 100644 --- a/k8s/hosted-identity-controller/networkpolicy.yaml +++ b/k8s/hosted-identity-controller/networkpolicy.yaml @@ -148,9 +148,9 @@ spec: ports: - protocol: TCP port: 2323 - # Ready additionally requires an mTLS handshake to the fixed Account gRPC - # Service using the current projected leaf. Runtime Namespace labels are - # externally owned and validated before the controller reaches this probe. + # Ready additionally requires mTLS handshakes to the fixed Account and + # Game Session gRPC Services using their current projected leaves. Runtime + # Namespace labels are externally owned and validated before this probe. - to: - namespaceSelector: matchLabels: @@ -164,6 +164,18 @@ spec: podSelector: matchLabels: app: account-service + - namespaceSelector: + matchLabels: + firemud.dev/preview: "true" + podSelector: + matchLabels: + app: game-session-service + - namespaceSelector: + matchLabels: + firemud.dev/dev-demo: "true" + podSelector: + matchLabels: + app: game-session-service ports: - protocol: TCP port: 6565 diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java index 9e36158c92..9405de9b1c 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java @@ -28,6 +28,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Set; import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; @@ -79,6 +80,7 @@ static final class HandshakePolicyRejectedException extends IllegalStateExceptio private static final String BRIDGE_PROBE_CLIENT_IP = "127.0.0.1"; private static final SecureRandom WEBSOCKET_NONCE_SOURCE = new SecureRandom(); private static final String GRPC_PROBE_SERVICE = "account-service"; + private static final String GRPC_GAME_SESSION_PROBE_SERVICE = "game-session-service"; private static final Logger LOGGER = LoggerFactory.getLogger(ServedEnvironmentProbe.class); private static final ThreadLocal CURRENT_ATTEMPT = new ThreadLocal<>(); private final HostedIdentityProperties properties; @@ -98,7 +100,8 @@ public ProbeResult probe( Secret tcpProxyBridgeMaterial, String expectedGatewayInternalWsLeafSha256, Secret grpcMaterial, - String expectedGrpcLeafSha256) { + String expectedGrpcLeafSha256, + String expectedGrpcGameSessionLeafSha256) { return probe( plan, HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, @@ -108,7 +111,8 @@ public ProbeResult probe( tcpProxyBridgeMaterial, expectedGatewayInternalWsLeafSha256, grpcMaterial, - expectedGrpcLeafSha256); + expectedGrpcLeafSha256, + expectedGrpcGameSessionLeafSha256); } public ProbeResult probe( @@ -120,7 +124,8 @@ public ProbeResult probe( Secret tcpProxyBridgeMaterial, String expectedGatewayInternalWsLeafSha256, Secret grpcMaterial, - String expectedGrpcLeafSha256) { + String expectedGrpcLeafSha256, + String expectedGrpcGameSessionLeafSha256) { return probe( plan, exposureMode, @@ -130,6 +135,7 @@ public ProbeResult probe( (hostname, port) -> bridge(hostname, port, tcpProxyBridgeMaterial, expectedGatewayInternalWsLeafSha256), (hostname, port) -> grpc(hostname, port, grpcMaterial, expectedGrpcLeafSha256), + (hostname, port) -> grpc(hostname, port, grpcMaterial, expectedGrpcGameSessionLeafSha256), TOTAL_PROBE_TIMEOUT); } @@ -148,6 +154,7 @@ ProbeResult probe( telnetProbe, bridgeProbe, grpcProbe, + grpcProbe, TOTAL_PROBE_TIMEOUT); } @@ -167,6 +174,7 @@ ProbeResult probe( telnetProbe, bridgeProbe, grpcProbe, + grpcProbe, timeout); } @@ -186,6 +194,49 @@ ProbeResult probe( telnetProbe, bridgeProbe, grpcProbe, + grpcProbe, + TOTAL_PROBE_TIMEOUT); + } + + ProbeResult probe( + EnvironmentIdentityPlan plan, + String exposureMode, + int telnetPort, + EndpointProbe httpsProbe, + EndpointProbe telnetProbe, + EndpointProbe bridgeProbe, + EndpointProbe grpcProbe, + Duration timeout) { + return probe( + plan, + exposureMode, + telnetPort, + httpsProbe, + telnetProbe, + bridgeProbe, + grpcProbe, + grpcProbe, + timeout); + } + + ProbeResult probe( + EnvironmentIdentityPlan plan, + String exposureMode, + int telnetPort, + EndpointProbe httpsProbe, + EndpointProbe telnetProbe, + EndpointProbe bridgeProbe, + EndpointProbe grpcProbe, + EndpointProbe grpcGameSessionProbe) { + return probe( + plan, + exposureMode, + telnetPort, + httpsProbe, + telnetProbe, + bridgeProbe, + grpcProbe, + grpcGameSessionProbe, TOTAL_PROBE_TIMEOUT); } @@ -197,6 +248,7 @@ ProbeResult probe( EndpointProbe telnetProbe, EndpointProbe bridgeProbe, EndpointProbe grpcProbe, + EndpointProbe grpcGameSessionProbe, Duration timeout) { if (!HostedIdentityContract.PRIVATE_PREVIEW_EXPOSURE_MODE.equals(exposureMode) && !HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE.equals(exposureMode)) { @@ -221,7 +273,7 @@ ProbeResult probe( ProbeName.GRPC, () -> { try { - return grpcProbe.check(grpcHostname(plan), GRPC_PORT); + return grpcProbe.check(grpcHostname(plan, GRPC_PROBE_SERVICE), GRPC_PORT); } catch (IllegalArgumentException exception) { LOGGER.debug( "gRPC probe rejected material or configuration for runtime Namespace {}", @@ -230,6 +282,21 @@ ProbeResult probe( return new ProbeResult(false, "grpc-material-or-configuration-invalid"); } })); + probes.add( + startProbe( + ProbeName.GRPC_GAME_SESSION, + () -> { + try { + return grpcGameSessionProbe.check( + grpcHostname(plan, GRPC_GAME_SESSION_PROBE_SERVICE), GRPC_PORT); + } catch (IllegalArgumentException exception) { + LOGGER.debug( + "Game Session gRPC probe rejected material or configuration for runtime Namespace {}", + plan.runtimeNamespace(), + exception); + return new ProbeResult(false, "grpc-material-or-configuration-invalid"); + } + })); long deadline = System.nanoTime() + timeout.toNanos(); try { List results = new ArrayList<>(probes.size()); @@ -400,11 +467,12 @@ interface InternalTlsSocketOpener { SSLSocket open() throws Exception; } - private static String grpcHostname(EnvironmentIdentityPlan plan) { - if (!plan.grpcConsumers().contains(GRPC_PROBE_SERVICE)) { + private static String grpcHostname(EnvironmentIdentityPlan plan, String service) { + if (!Set.of(GRPC_PROBE_SERVICE, GRPC_GAME_SESSION_PROBE_SERVICE).contains(service) + || !plan.grpcConsumers().contains(service)) { throw new IllegalArgumentException("fixed gRPC probe service is not a rollout consumer"); } - return GRPC_PROBE_SERVICE + "." + plan.runtimeNamespace() + ".svc.cluster.local"; + return service + "." + plan.runtimeNamespace() + ".svc.cluster.local"; } static SSLSocket openGrpcTlsSocket( @@ -890,7 +958,8 @@ enum ProbeName { HTTPS("https"), TELNET("telnet"), BRIDGE("bridge"), - GRPC("grpc"); + GRPC("grpc"), + GRPC_GAME_SESSION("grpc-game-session"); private final String label; diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java index e01c56c75b..80db24cee7 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java @@ -201,6 +201,8 @@ public UpdateControl reconcile( roleMaterials.material(HostedIdentityContract.GRPC_ROLE); CertificateMaterialService.RoleMaterial grpcAccount = roleMaterials.material(HostedIdentityContract.GRPC_ACCOUNT_ROLE); + CertificateMaterialService.RoleMaterial grpcGameSession = + roleMaterials.material(HostedIdentityContract.GRPC_GAME_SESSION_ROLE); validateDistinctIdentities( rolePipeline.stream() .map(RoleMaterialBinding::material) @@ -272,7 +274,8 @@ public UpdateControl reconcile( bridgeMaterial, gatewayInternalWs.summary().certificateFingerprint(), grpc.source(), - grpcAccount.summary().certificateFingerprint()); + grpcAccount.summary().certificateFingerprint(), + grpcGameSession.summary().certificateFingerprint()); } else { probes = new ServedEnvironmentProbe.ProbeResult(false, "rollout-pending"); } diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java index 0fb00a1d2a..f845f2917b 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java @@ -106,6 +106,23 @@ void readinessProbeRequiresBridgeAndInternalGrpcAcceptanceAfterPublicEndpoints() assertEquals( "bridge-rejected", probe.probe(plan, 32001, ready, ready, rejected, ready).reason()); assertEquals("grpc-rejected", probe.probe(plan, 32001, ready, ready, ready, rejected).reason()); + assertEquals( + "grpc-game-session-rejected", + probe + .probe( + plan, + HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, + 32001, + ready, + ready, + ready, + ready, + (hostname, port) -> { + assertEquals("game-session-service.pr-42.svc.cluster.local", hostname); + assertEquals(6565, port); + return new ServedEnvironmentProbe.ProbeResult(false, "rejected"); + }) + .reason()); assertEquals( "served-bridge-and-grpc-accepted", probe.probe(plan, 32001, ready, ready, ready, ready).reason()); @@ -140,9 +157,10 @@ void privateReadinessSkipsOnlyThePublicTelnetProbe() { Set.of( "pr-42.preview.firedevops.net:443", "spring-cloud-gateway-mtls.pr-42.svc.cluster.local:443", - "account-service.pr-42.svc.cluster.local:6565"), + "account-service.pr-42.svc.cluster.local:6565", + "game-session-service.pr-42.svc.cluster.local:6565"), Set.copyOf(endpoints)); - assertEquals(3, endpoints.size()); + assertEquals(4, endpoints.size()); } @Test @@ -211,9 +229,10 @@ void readinessProbeSuppliesEachDerivedEndpointToItsProbeSeam() { "pr-42.preview.firedevops.net:443", "pr-42.preview.firedevops.net:32001", "spring-cloud-gateway-mtls.pr-42.svc.cluster.local:443", - "account-service.pr-42.svc.cluster.local:6565"), + "account-service.pr-42.svc.cluster.local:6565", + "game-session-service.pr-42.svc.cluster.local:6565"), Set.copyOf(endpoints)); - assertEquals(4, endpoints.size()); + assertEquals(5, endpoints.size()); } @Test @@ -221,7 +240,7 @@ void readinessProbeRunsEveryEndpointConcurrentlyWithinOneDeadline() { HostedIdentityProperties properties = new HostedIdentityProperties(); EnvironmentIdentityPlan plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); ServedEnvironmentProbe probe = new ServedEnvironmentProbe(properties); - CountDownLatch started = new CountDownLatch(4); + CountDownLatch started = new CountDownLatch(5); EndpointProbeState state = new EndpointProbeState(started); ServedEnvironmentProbe.EndpointProbe endpoint = state::check; @@ -229,7 +248,7 @@ void readinessProbeRunsEveryEndpointConcurrentlyWithinOneDeadline() { probe.probe(plan, 32001, endpoint, endpoint, endpoint, endpoint, Duration.ofSeconds(10)); assertEquals("served-bridge-and-grpc-accepted", result.reason()); - assertEquals(4, state.calls.get()); + assertEquals(5, state.calls.get()); assertEquals(0, started.getCount()); } @@ -238,8 +257,8 @@ void readinessProbeCancelsAndClosesEveryOutstandingEndpointAttemptAtDeadline() t HostedIdentityProperties properties = new HostedIdentityProperties(); EnvironmentIdentityPlan plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); ServedEnvironmentProbe probe = new ServedEnvironmentProbe(properties); - CountDownLatch started = new CountDownLatch(4); - CountDownLatch interrupted = new CountDownLatch(4); + CountDownLatch started = new CountDownLatch(5); + CountDownLatch interrupted = new CountDownLatch(5); List openSockets = Collections.synchronizedList(new ArrayList<>()); ServedEnvironmentProbe.EndpointProbe endpoint = (hostname, port) -> { @@ -263,7 +282,7 @@ void readinessProbeCancelsAndClosesEveryOutstandingEndpointAttemptAtDeadline() t assertEquals("probe-deadline-exceeded", result.reason()); assertTrue(started.await(1, TimeUnit.SECONDS)); assertTrue(interrupted.await(1, TimeUnit.SECONDS)); - assertEquals(4, openSockets.size()); + assertEquals(5, openSockets.size()); for (SSLSocket openSocket : openSockets) { verify(openSocket).close(); } diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java index b780258dc1..d9e7c3e015 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java @@ -210,6 +210,7 @@ void workloadIdentityProjectionMustBeAcceptedBeforeReadiness() { any(Secret.class), anyString(), any(Secret.class), + anyString(), anyString())) .thenReturn(new ServedEnvironmentProbe.ProbeResult(true, "served")); Map acknowledgedProjections = @@ -276,7 +277,8 @@ void workloadIdentityProjectionMustBeAcceptedBeforeReadiness() { any(Secret.class), anyString(), any(Secret.class), - org.mockito.ArgumentMatchers.eq("b".repeat(64))); + org.mockito.ArgumentMatchers.eq("b".repeat(64)), + org.mockito.ArgumentMatchers.eq("c".repeat(64))); } @Test @@ -320,6 +322,70 @@ void probeStatusOwnsReasonAndMessageAfterEarlierGatesPass() { false); } + @Test + void staleGameSessionServedLeafBlocksControllerReadiness() { + var expected = + new RuntimeProfileService.RuntimeProfile( + "uid", + "a".repeat(40), + "a".repeat(40), + HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, + 32016, + true); + DeploymentHeadGateFixture fixture = new DeploymentHeadGateFixture(expected); + when(fixture.batch.tcpProxyBridge()) + .thenReturn( + DeploymentHeadGateFixture.material( + fixture.plan, HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE, "4")); + MixedOperation> secrets = mock(MixedOperation.class); + NonNamespaceOperation> runtimeSecrets = + mock(NonNamespaceOperation.class); + Resource absent = mock(Resource.class); + when(fixture.client.secrets()).thenReturn(secrets); + when(secrets.inNamespace(fixture.plan.runtimeNamespace())).thenReturn(runtimeSecrets); + when(runtimeSecrets.withName(fixture.plan.tcpProxyBridgeSecretName())).thenReturn(absent); + when(absent.get()).thenReturn(null); + when(fixture.rollout.sync(any(), any(), anyString(), anyString(), anyString(), anyMap(), any())) + .thenReturn(new DeploymentRolloutService.RolloutResult(true, true, true)); + when(fixture.probes.probe( + any(), + anyString(), + anyInt(), + anyString(), + anyString(), + org.mockito.ArgumentMatchers.isNull(), + anyString(), + any(Secret.class), + anyString(), + anyString())) + .thenReturn( + new ServedEnvironmentProbe.ProbeResult( + false, "grpc-game-session-leaf-fingerprint-mismatch")); + + UpdateControl result = fixture.reconcile(); + + HostedEnvironmentIdentityStatus status = result.getResource().orElseThrow().getStatus(); + assertEquals(HostedEnvironmentIdentityStatus.Phase.Verifying, status.getPhase()); + assertEquals("ServedProbePending", status.getConditions().get(0).getReason()); + assertEquals( + "grpc-game-session-leaf-fingerprint-mismatch", status.getConditions().get(0).getMessage()); + verify(fixture.probes) + .probe( + any(), + anyString(), + anyInt(), + anyString(), + anyString(), + org.mockito.ArgumentMatchers.isNull(), + anyString(), + any(Secret.class), + org.mockito.ArgumentMatchers.eq("b".repeat(64)), + org.mockito.ArgumentMatchers.eq("c".repeat(64))); + verify(fixture.projections, never()) + .acknowledge( + any(), any(), anyString(), anyString(), anyLong(), anyLong(), anyString(), any()); + } + @Test void readyStatusPreservesTheSuccessfulProbeMessage() { var status = @@ -523,6 +589,7 @@ void readinessBoundaryRejectsAChangedRuntimeTupleBeforeAcknowledgement() { any(Secret.class), anyString(), any(Secret.class), + anyString(), anyString())) .thenReturn(new ServedEnvironmentProbe.ProbeResult(true, "served")); @@ -580,6 +647,7 @@ void malformedRuntimeProfileAtReadinessBoundaryFailsClosedWithoutAcknowledgement any(Secret.class), anyString(), any(Secret.class), + anyString(), anyString())) .thenReturn(new ServedEnvironmentProbe.ProbeResult(true, "served")); @@ -800,6 +868,7 @@ void projectionAcknowledgementFenceNamesTheProtectedAction() { any(Secret.class), anyString(), any(Secret.class), + anyString(), anyString())) .thenReturn(new ServedEnvironmentProbe.ProbeResult(true, "served")); when(fixture.projections.acknowledge( @@ -2221,6 +2290,7 @@ void missingBridgeProjectionMapsReconciliationToVerifyingProbeStatus() { org.mockito.ArgumentMatchers.isNull(), anyString(), any(Secret.class), + anyString(), anyString())) .thenReturn( new ServedEnvironmentProbe.ProbeResult(false, "material-or-leaf-fingerprint-missing")); From 26efdeb5b7198c7f565d5f0e1840cb52493d807d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 02:13:56 +1300 Subject: [PATCH 07/75] docs: align hosted identity ADR with seven workload leaves --- ...ed-hosted-runtime-and-certificate-identity-lifecycles.md | 6 +++--- dev-tools/certs/README.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md b/design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md index 66ae28c763..18a597fc30 100644 --- a/design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md +++ b/design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md @@ -37,9 +37,9 @@ The controller establishes identity scope only through its one-time bootstrap/ad ### Runtime-first activation and explicit retirement -Runtime namespaces remain clean and disposable. A trusted lifecycle may reclaim, redeploy, release, or let a lease expire on the runtime namespace while retaining the active identity namespace. Runtime preparation creates or reuses the exact `pr-` or `dev` namespace, records the requested reviewed head and image, and allocates the bounded Telnet port. The trusted requester then applies `Active`, and the runtime lane waits for all five labeled, key-complete Secret projections defined by the [deployment-environment contract](../infrastructure/deployment-environments.md) before application preflight, server dry-run, and deploy. Only successful deployment may record the separate deployed-head evidence consumed by readiness. A failed or incomplete identity projection blocks runtime deployment, while a failed deployment cannot make the request appear deployed. +Runtime namespaces remain clean and disposable. A trusted lifecycle may reclaim, redeploy, release, or let a lease expire on the runtime namespace while retaining the active identity namespace. Runtime preparation creates or reuses the exact `pr-` or `dev` namespace, records the requested reviewed head and image, and allocates the bounded Telnet port. The trusted requester then applies `Active`, and the runtime lane waits for all twelve labeled, key-complete Secret projections defined by the [deployment-environment contract](../infrastructure/deployment-environments.md)—five shared-role projections and seven distinct gRPC workload projections—before application preflight, server dry-run, and deploy. Only successful deployment may record the separate deployed-head evidence consumed by readiness. A failed or incomplete identity projection blocks runtime deployment, while a failed deployment cannot make the request appear deployed. -A PR close or merge follows a runtime-first path: it requests `Retired` only after runtime cleanup has observed the exact runtime Namespace `NotFound` result, so that path gives the controller no live runtime to shut down. A trusted explicit identity-removal request for a live runtime follows a retirement-first path: it may set `Retired` while the runtime still exists, after which the controller must terminate Gateway and TCP Proxy and observe both bridge workloads at zero before the trusted runtime lifecycle deletes the namespace and proves exact `NotFound`. Retained identity deletion remains blocked until that runtime absence proof. Before deleting retained material, the controller accounts for all five declared projection roles: (1) [public ingress TLS](../system-architecture-security.md#tls-termination-for-gateway), (2) [public Telnet TLS](../system-architecture-protocol-bridging.md#public-telnet-tls-modes), (3) the [Gateway internal WebSocket server](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), (4) the [TCP Proxy bridge client](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), and (5) the [shared gRPC transport bundle](./adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md#mtls-identity-and-certificate-lifecycle). Runtime cleanup and identity retirement remain separate operations. If the provider or lifecycle API cannot reliably establish the requested lifecycle state, the safe result is to retain identity, report the lifecycle as incomplete or uncertain, and fail closed; an uncertain response never triggers broader deletion. +A PR close or merge follows a runtime-first path: it requests `Retired` only after runtime cleanup has observed the exact runtime Namespace `NotFound` result, so that path gives the controller no live runtime to shut down. A trusted explicit identity-removal request for a live runtime follows a retirement-first path: it may set `Retired` while the runtime still exists, after which the controller must terminate Gateway and TCP Proxy and observe both bridge workloads at zero before the trusted runtime lifecycle deletes the namespace and proves exact `NotFound`. Retained identity deletion remains blocked until that runtime absence proof. Before deleting retained material, the controller accounts for all twelve declared projections: the five shared-role projections for (1) [public ingress TLS](../system-architecture-security.md#tls-termination-for-gateway), (2) [public Telnet TLS](../system-architecture-protocol-bridging.md#public-telnet-tls-modes), (3) the [Gateway internal WebSocket server](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), (4) the [TCP Proxy bridge client](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), and (5) the [shared gRPC transport bundle](./adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md#mtls-identity-and-certificate-lifecycle), plus seven distinct gRPC workload projections for the five publication services, Account, and Game Session. Runtime cleanup and identity retirement remain separate operations. If the provider or lifecycle API cannot reliably establish the requested lifecycle state, the safe result is to retain identity, report the lifecycle as incomplete or uncertain, and fail closed; an uncertain response never triggers broader deletion. If retirement observes a live runtime profile that differs from the profile already recorded in controller status, it reports `RuntimeIdentityChanged`, preserves the previously observed profile, and never refreshes retirement authority from the mismatched live values. Recovery belongs to the trusted lifecycle: it removes the whole disposable runtime namespace and obtains the runtime-first exact `NotFound` proof. A later retirement reconcile can then continue deleting the retained identity through the normal ownership-checked path. This recovery does not permit manual deletion of retained identity material and does not weaken the live-runtime bridge-shutdown or runtime-absence gates. @@ -53,7 +53,7 @@ All controller-owned certificate leaves use RSA-2048 keys. The cert-manager reso ### Generation-bound readiness and certificate convergence -The controller publishes non-secret status only. A `Ready=True` result is valid only when `status.observedGeneration` equals `metadata.generation`, the live runtime namespace UID and requested head SHA match the status profile, a separately recorded post-deployment head equals that request after canonical 40-hex normalization, rollout and served proofs have converged, and non-empty ingress, Telnet, Gateway-internal WebSocket, TCP Proxy bridge, and gRPC revisions are present. PR preview and dev-demo preparation write only their distinct requested-head annotations; only a successful runtime deployment writes the corresponding deployed-head annotation. The workflow treats `Pending`, `Provisioning`, `WaitingForCertificate`, `RuntimeAbsent`, `Syncing`, `Verifying`, `Degraded`, `Blocked`, `Retiring`, and `Retired` as non-ready and uses the Ready condition's reason/message for failure detail. +The controller publishes non-secret status only. A `Ready=True` result is valid only when `status.observedGeneration` equals `metadata.generation`, the live runtime namespace UID and requested head SHA match the status profile, a separately recorded post-deployment head equals that request after canonical 40-hex normalization, rollout and served proofs have converged, and non-empty revisions are present for the five shared roles and seven distinct gRPC workload roles. Account and Game Session must additionally serve their current projected leaves at the fixed gRPC endpoints; rollout counters alone are insufficient. PR preview and dev-demo preparation write only their distinct requested-head annotations; only a successful runtime deployment writes the corresponding deployed-head annotation. The workflow treats `Pending`, `Provisioning`, `WaitingForCertificate`, `RuntimeAbsent`, `Syncing`, `Verifying`, `Degraded`, `Blocked`, `Retiring`, and `Retired` as non-ready and uses the Ready condition's reason/message for failure detail. Certificate issuance and replacement for one identity proceed through a serialized lifecycle. The controller and issuer path validate actual served certificates and keys, including validity, required SANs, key correspondence without exposing private material, expected issuer and trust chain, monotonic identity generation, and distinct SPKI for intentional replacement. After issuance, affected ingress, Telnet, and, where applicable, gRPC consumers must reload or restart and serve or accept the new identity. A consumer that has not converged leaves the lifecycle failed or pending and does not authorize removal of the prior usable identity solely because a new resource exists. diff --git a/dev-tools/certs/README.md b/dev-tools/certs/README.md index 7552e3301d..2b29745070 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -7,7 +7,7 @@ Generated certificate outputs in this directory are ignored by Git and should no ## Script Map - `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target is provided. -- `dev-tools/certs/generate-dev-certs.sh --workload` signs a local development or test-only publication leaf with the exact SPIFFE URI and service DNS SANs. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. +- `dev-tools/certs/generate-dev-certs.sh --workload` signs a local development or test-only gRPC workload leaf for the five publication services, Account, or Game Session with the exact SPIFFE URI and service DNS SANs. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. - Standalone hosted runs retain the legacy shared bundle for other gRPC workloads and consume seven cert-manager-issued runtime-facing `firemud-grpc-` leaf Secrets: five publication workloads, Account, and Game Session. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. - `dev-tools/certs/ensure-dev-certs.sh` guarantees the canonical local smoke entrypoints have the required cert/key set in place before Compose boots. - `dev-tools/certs/clean-dev-certs.sh` removes generated certificate files from `dev-tools/certs/` unless a target directory or `CERT_DIR` override is provided. From a9f94e7f27a77f63d78b1b721d4573e6c7891aea Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:54:07 +1300 Subject: [PATCH 08/75] Prepare Account join authority and audit receipt stage --- .../account-service/api-contracts.md | 21 +- .../account-service/operations.md | 2 +- .../account-service/runtime-and-data.md | 21 +- .../logging-admin-service/api-contracts.md | 2 +- .../system-architecture-authentication.md | 34 +- .../system-architecture-authz-route-matrix.md | 7 +- ...ystem-architecture-authz-route-matrix.yaml | 72 +- .../player-access-and-session.md | 14 +- ...d-identity-controller-manifest-contract.sh | 59 +- k8s/base/logging-admin-service.yaml | 4 + k8s/helm/firemud/templates/apps.yaml | 6 + protos/account/v1/account_service.proto | 48 +- .../v1/game_session_service.proto | 6 + .../v1/logging_admin_service.proto | 75 +- .../shared/v1/player_execution_context.proto | 20 + .../client/LoggingAdminClient.java | 95 +- .../controller/AuthController.java | 16 + .../accountservice/data/TestDataSeeder.java | 4 + .../dto/AccountAuditDigest.java | 23 + .../dto/AccountAuditEnvelope.java | 17 + .../accountservice/dto/AccountDto.java | 2 +- .../accountservice/dto/AccountJoinDigest.java | 107 ++ .../accountservice/dto/BootstrapRealmDto.java | 1 + .../dto/CreateAccountRequest.java | 2 - .../dto/DirectTextCallerContext.java | 14 + .../dto/DirectTextJoinScope.java | 6 + .../dto/DirectTextJoinTarget.java | 17 + .../dto/JoinPublicProductionRequest.java | 9 + .../dto/JoinPublicProductionResult.java | 12 + .../dto/RuntimeMembershipDto.java | 2 + .../accountservice/dto/VerifiedJoinScope.java | 20 + .../accountservice/entity/Account.java | 2 +- .../entity/AccountTenantMembership.java | 4 + .../accountservice/entity/Subscription.java | 1 + .../AccountAuditOutboxRepository.java | 105 ++ .../AccountConnectScopeRepository.java | 82 + .../AccountJoinOperationRepository.java | 257 +++ .../AccountTenantMembershipRepository.java | 21 + .../repository/SubscriptionRepository.java | 21 +- .../service/AccountAuditDeliveryJob.java | 43 + .../service/AccountService.java | 14 + .../service/impl/AccountGrpcService.java | 168 +- .../service/impl/AccountServiceImpl.java | 953 ++++++++++-- .../src/main/resources/application-prod.yml | 2 + .../src/main/resources/application.yml | 2 + ...V26__global_registration_join_evidence.sql | 270 ++++ .../src/main/resources/openapi.yaml | 74 +- .../AccountApplicationIntegrationTest.java | 48 + .../AccountRepositoryIntegrationTest.java | 412 +++++ .../controller/AccountControllerTest.java | 26 +- .../controller/AuthControllerTest.java | 2 + .../PublicBootstrapRoutesProdProfileTest.java | 2 +- .../dto/AccountJoinDigestTest.java | 118 ++ .../service/AccountAuditDeliveryJobTest.java | 87 ++ .../service/impl/AccountGrpcServiceTest.java | 308 +++- .../service/impl/AccountServiceImplTest.java | 1379 ++++++++++++++++- ...untRuntimeStubServerCompatibilityTest.java | 3 + .../test/AccountRuntimeStubServer.java | 125 +- .../AccountAuditGrpcAuthConfiguration.java | 37 + .../dto/AccountAuditReceiptDto.java | 13 + .../dto/AccountAuditReceiptOutcome.java | 8 + .../dto/AccountAuditReceiptStatus.java | 7 + .../loggingadmin/dto/AccountAuditScope.java | 16 + .../dto/CreateLogEventRequest.java | 24 +- .../entity/AccountAuditReceipt.java | 30 + .../AccountAuditReceiptInsertResult.java | 3 + .../AccountAuditReceiptRepository.java | 89 ++ .../AuditReceiptNotFoundException.java | 7 + .../AuditStorageUnavailableException.java | 7 + .../loggingadmin/service/LogEventService.java | 6 +- .../service/impl/LogEventServiceImpl.java | 213 ++- .../service/impl/LoggingAdminGrpcService.java | 296 +++- .../migration/V2__account_audit_receipts.sql | 47 + .../service/impl/LogEventServiceImplTest.java | 212 +++ .../impl/LoggingAdminGrpcServiceAuthTest.java | 392 ++++- 75 files changed, 6217 insertions(+), 457 deletions(-) create mode 100644 protos/shared/v1/player_execution_context.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionRequest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java create mode 100644 services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 5f2ab479ab..bc2d9f4394 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,7 +60,7 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. -The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` and `ExportAccount` implementation is Account/profile-local; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Explicit `JOIN` / `Join & Play` is not implemented. The current runtime membership response is the current four-field admission response, with `accountId` and `tenantId` context: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. It does not expose target-only `membershipLifecycleState` or `membershipAuthorityGeneration`; connect-token issuance and text `PLAY` proceed only when the first two admission fields are true, and an eligible public-production request with `membershipExists=false` may return `JOIN_REQUIRED`. An existing non-admitting response cannot be classified as `INACTIVE` because lifecycle state is target-only. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The sole target canonical operation is `JoinPublicProductionMembership`; the obsolete implicit membership-writer surface has been removed and is not a compatibility operation. Runtime convergence remains partial until explicit join is implemented with the target transaction, version, and durable audit/outbox evidence. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` and `ExportAccount` implementation is Account/profile-local; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Connect-token issuance and text `PLAY` do not enforce the emitted lifecycle state or generation; they proceed only when the two admission booleans are true, and an eligible public-production request with missing or non-admitting membership may return `JOIN_REQUIRED`. The consumer therefore does not distinguish `INACTIVE` from another existing non-admitting state even though Account emits the lifecycle field. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. ### Current vs Target Export Lifecycle @@ -75,9 +75,10 @@ For `security_locked` accounts, Account's successful recovery authorization issu `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. -- `CreateAccount` – registers a new user and returns its `accountId` so internal services can establish their own sessions using the authentication flows described below. +- `CreateAccount` – registers a global Account identity and returns its `accountId`; it does not select a tenant or create membership/profile state. Registration also appends a platform-scoped audit outbox record in the Account transaction. - `SendNotification` – deliver account notifications asynchronously. - `Authenticate` – verifies one account-selected ordinary credential mode, either `PASSWORD` or verified-email `EMAIL_OTP`, using a required, typed `CredentialSourceContext` and, only for the approved Game Session-to-Account control path, issues the receiver-specific private `game-session-account-delegation` JWT with exact audience `account-service`. Gameplay credential and email-code authentication are global Account-identity operations: their current wire requests reserve the former `tenant_id` fields, and Account neither selects nor requires membership before returning identity. The pre-v1 wire convergence also reserves the former `username` field number and places `email` on a new field number, so mixed old/new Account and Game Session versions fail closed instead of reinterpreting identifiers; the two services must be deployed as one compatibility cohort for uninterrupted gameplay login. The target registry-backed flow stores one `session:auth:token:` record; current gameplay issuance uses the legacy account-scoped session key and defers tenant membership/grant/entitlement to `JOIN`/`PLAY`. Generic `Service JWT` and `aud=internal` profiles are forbidden; workload-only authorization uses mTLS. The context contains a server-derived canonical client address and transport class; Account rejects absent or untrusted context in player-facing environments, and public callers cannot assert it. +- `JoinPublicProductionMembership` – implemented local internal Account RPC for explicit public-production membership creation/restoration. It accepts the Account-issued `connectScopeId`, operation `requestId`, and authenticated caller context; it revalidates the exact stored target and fresh `allowPublicJoin` entitlement evidence, binds a v1 digest to that caller/scope/policy snapshot, and commits membership/version, durable operation outcome, and tenant audit outbox evidence together. The digest's canonical grammar remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). A `PENDING` operation after an unknown database commit outcome still requires recovery/reconciliation implementation and exact-final-head PostgreSQL proof; no implicit membership writer or production end-to-end completion is claimed. - `ResolveEffectiveSecurityPolicy` – **Target-state internal Account contract.** Resolve the effective policy for the exact account, optional tenant-scoped action, and action class from the versioned platform baseline, deployment policy, and applicable tenant policy using the tightening precedence in ADR 0045. Return the contributing policy versions, resolved values, and opaque `effectivePolicyVersion`/digest from one Account-owned resolution. Callers must not merge inputs or use cached/default policy; missing, invalid, contradictory, stale, or unavailable resolution fails the sensitive action closed. No other service is a policy authority. - `ApplyAccountSafetyRestriction` / `GetAccountSafetyRestrictions` – target Account-owned owner-command and safe projection contracts for `account_security_lock` and `platform_access_ban`. The command carries one exact category, global account scope, source case/security-event identity, a distinct `ownerEnforcementRequestId`, owner-enforcement digest, and owner authorization evidence; `controlPlaneRequestId` remains correlation-only and never carries or aliases the owner identity. Account validates and atomically commits its monotonic revision, account authority-generation effects, and idempotent result. The current proto/transport mapping does not yet expose the distinct owner request field; that is implementation drift, not proof that the target command is implemented. These contracts do not create a moderation appeal case, and current proto/implementation/proof do not yet provide the complete lifecycle. - `RefreshGameplayServiceToken` – Account-local RPC for the token refresh/replacement operation defined in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). Account validates the declared receiver binding and current authority, while Game Session supplies the binding-refresh installation/reconciliation consequence; the current proto and implementation do not yet prove the target registry-backed operation. @@ -102,13 +103,13 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `IssuePlayerBootstrapToken` – authenticate a first-party player account and issue the short-lived `player-bootstrap` token profile used only for gameplay bootstrap. - `ListBootstrapWorlds` – list caller-visible worlds for first-party gameplay bootstrap. - `ListBootstrapRealms` – list caller-visible realms for a selected world during first-party gameplay bootstrap. -- `IssueDirectTextConnectScope` – target-only internal Account API called only by authenticated Game Session mTLS during authenticated `REALMS`. The request carries the authenticated caller context in a typed `PlayerExecutionContext` plus the exact server-resolved `{tenantId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion}` target, with exact `playtestLifecycleId` and positive `playtestStateGeneration` for every non-public target and both fields absent for a non-grant public-production target. Account validates that authenticated caller context separately from scope validation; the response returns an opaque short-lived `connectScopeId` and `connectScopeExpiresAt` bound to that complete evaluated target and exact `catalogRevision`/`pointerVersion` snapshot. It is distinct from `ListBootstrapRealms`, which is first-party discovery, and `JoinPublicProductionMembership`, which is the explicit membership mutation. An unavailable Account or routing authority fails closed as `AUTH_UNAVAILABLE`; reachable missing, malformed, ambiguous, stale, or otherwise contract-invalid catalog/pointer evidence is `ADMISSION_POINTER_UNAVAILABLE` before a valid scope comparison, while a valid scope whose exact `catalogRevision`/`pointerVersion` pair differs from the fresh authoritative snapshot returns `CONNECT_SCOPE_MISMATCH`. Fresh Account membership checks remain required separately at the applicable join, connect-token, and admission gates. Detailed scope semantics remain delegated to [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) and [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). +- `IssueDirectTextConnectScope` – implemented local internal Account API called by authenticated Game Session during authenticated `REALMS`. The request carries authenticated caller context in typed `PlayerExecutionContext` plus the server-resolved target; Account validates caller context separately from the short-lived scope and returns an opaque `connectScopeId` bound to the evaluated routing snapshot. It is distinct from `ListBootstrapRealms`, which is first-party discovery, and `JoinPublicProductionMembership`, which is the membership mutation. Reachable missing or invalid routing evidence fails as `ADMISSION_POINTER_UNAVAILABLE`; a changed exact routing pair fails as `CONNECT_SCOPE_MISMATCH`; unavailable authority fails as `AUTH_UNAVAILABLE`. Fresh Account membership checks remain required separately at applicable admission gates. The canonical scope and transport requirements remain owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); this local status does not claim direct text-client end-to-end proof. - `ListBootstrapCharacters` – list caller-visible characters for the selected opaque server-issued `connectScopeId` target during first-party gameplay bootstrap. The exact realm snapshot resolves and carries `playableStateScope` to the character-query boundary; neither clients nor Account derive a physical storage key, and the route world/realm must match the resolved scope. - Bootstrap discovery and join use the canonical realm catalog and admission-pointer contract in [Multi-Tenancy](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). The existing canonical resolver for the exact-snapshot `stateScope` to `playableStateScope` projection is owned there. REST bootstrap character discovery/creation and direct-text `CHARS`/creation are transport-local producers of that same server-derived projection; neither path accepts a caller-selected value, derives a storage key, or carries the projection through `JOIN` or connect-token issuance. Missing or mismatched proof that the REST and direct-text producers apply the same resolver is implementation drift, not a second resolver contract. Character-query input remains owned by the [Entity Management API contract](../entity-management-service/api-contracts.md#grpc). -- `JoinPublicProductionMembership` – target-only internal Account API for explicit open-enrollment `JOIN`; its canonical membership lifecycle and freshness contract are owned by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). The local route remains unimplemented, accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. +- `JoinPublicProductionMembership` – implemented local internal Account API for explicit public-production `JOIN`; the canonical membership lifecycle and freshness contract are owned by [Authentication](../../system-architecture-authentication.md) and its local persistence/transaction consequences by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). It accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. Durable recovery/reconciliation for an operation left `PENDING` after an unknown database commit outcome, exact-final-head PostgreSQL runtime proof, direct text-client end-to-end proof, and membership-generation snapshot proof remain open. - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). -- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the response is the four-field admission shape documented above and does not expose lifecycle state or `membershipAuthorityGeneration`. **Target-only:** the response adds `membershipLifecycleState` and opaque `membershipAuthorityGeneration`, with the independent `membershipVersion`, from one fresh atomic Account membership snapshot. +- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. - `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. @@ -161,7 +162,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `POST` | `/auth/request-email-verification` | Send an account-scoped verification email selected by normalized email with a neutral known/unknown response; the public route accepts no numeric account selector | | `POST` | `/auth/verify-email` | **Target public route; current bearer exception.** Verify an account-scoped email token. The current HTTP configurations allowlist only `GET /auth/verify-email` (which has no controller mapping), so the implemented `POST` route inherits bearer authentication until the public-route configuration is deliberately converged and proved. | | `POST` | `/auth/recover-username` | Send an account-scoped username reminder by normalized email with a neutral known/unknown response | -| `POST` | `/accounts` | Create a new user account | +| `POST` | `/accounts` | Create a global Account identity and platform-scoped audit outbox row; tenant membership and profile creation are separate operations. Legacy tenant input is not registration authority. | | `GET` | `/accounts/{accountId}/export` | **Current legacy route.** Returns an Account/profile-local export and does not satisfy ADR 0050. | | `POST` | `/accounts/{accountId}/exports` | **Target-state only.** Initiate or idempotently replay one asynchronous portable-data export within the defined global account scope using the caller's `requestId`; Account computes and persists the canonical, versioned `requestDigest` and `exportId`, returns the existing operation on a matching retry, and returns an idempotency conflict on a digest mismatch. Active accounts use the authenticated account subject; `security_locked` accounts use only the distinct Account-issued, expiring `security-lock-export` credential after Account-owned recovery authorization; `deactivated_pending_delete` accounts use only `pending-deletion-access`. No state accepts a tenant selector or a support-only bypass. | | `GET` | `/accounts/{accountId}/exports/{exportId}` | **Target-state only.** Read durable portable-data export status, owner contribution state, and the versioned manifest using the same bounded subject/credential branch that initiated the job. | @@ -177,7 +178,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `GET` | `/auth/bootstrap/worlds/{world}/realms` | List caller-visible realms for a selected world during first-party gameplay bootstrap | | `GET` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters?connectScopeId={scope}` | List caller-visible characters for the signed realm-discovery target during first-party gameplay bootstrap. The REST producer applies the canonical realm-snapshot mapping to `playableStateScope` before passing it to Entity Management; callers cannot select or provide it. | | `POST` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters` | **Target; not currently routable or implemented.** Account-owned player-bootstrap facade for scoped character creation; retains the target delegation contract to Entity Management `CreateCharacter` after signed-scope and membership/grant checks. The REST producer applies the same canonical mapping, and `playableStateScope` is server-derived rather than an accepted request field. | -| `POST` | `/internal/runtime/public-production-join` | Target Account-owned boundary for `JoinPublicProductionMembership`, used by explicit text-client `JOIN`; explicit JOIN behavior remains target-only and unimplemented, and no implicit membership-writer route is exposed | +| `POST` | `/internal/runtime/public-production-join` | **Target REST adapter; not currently routable.** Explicit text-client JOIN uses the implemented internal `JoinPublicProductionMembership` RPC; no implicit membership-writer route is exposed. | | `GET` | `/internal/runtime/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}/{accountId}` | Internal-only authoritative lookup for one non-public realm-access grant; the lifecycle ID is part of the exact target | | `GET` | `/internal/runtime/accounts/{accountId}/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}` | Internal-only authoritative lookup/list for the account's exact non-public world/realm/lifecycle target used by discovery/admission filtering | | `POST` | `/tenant-admin/tenants/{tenantId}/realm-access-grants/{worldSlug}/{realmSlug}/{playtestLifecycleId}` | **Target-state only; not currently routable.** Target duplicate-safe create-or-extend surface. The body carries the exact `accountId`, `operation`, requested `grantExpiresAt`, stable `requestId`, and conditional `expectedGrantRevision` (absent-grant precondition for `CREATE`, required current revision for `EXTEND`); exact `mutationDigest/v1` retries replay the stored outcome and changed intent or revision returns `IDEMPOTENCY_CONFLICT` or `GRANT_REVISION_CONFLICT` as defined above. | @@ -188,8 +189,8 @@ These RPCs and schemas are accepted target state but are not present in the curr | `PUT` | `/tenants/{tenantId}/profiles/{accountId}` | **Canonical target, `tenant_regular`.** Account live membership authority supplies current membership lifecycle, `membershipAuthorityGeneration`, and independent `membershipVersion`; caller subject and scoped role checks apply. The legacy `/profiles/{accountId}` route is implementation drift only and has no `platformAdmin` override. | | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | -| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** it checks tenant `gameplayAvailable`, the current four-field membership response, and public `allowPublicJoin`, but it does not yet enforce the complete private/playtest grant-and-entitlement target at connect-token issuance. **Current response drift:** the live `ConnectTokenResponse` body exposes the internal `jti`; the target response is metadata-only and must not expose `jti` or any raw token. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | -| `POST` | `/auth/bootstrap/join` | **Target-state only; not implemented at the current Account Service boundary.** Perform an explicit caller-bound `JoinPublicProductionMembership` / `Join & Play` operation for a discovery-selected public production realm using the exact `connectScopeId` and `requestId`. Account consumes the canonical JOIN digest contract defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative), verifies the scope's exact routing pair at membership commit, and retains only the local operation, membership, audit, and outbox consequences. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A stale pair or digest returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. | +| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** it checks tenant `gameplayAvailable`, the current partial membership response without enforcing its emitted lifecycle state or generation, and public `allowPublicJoin`, but it does not yet enforce the complete private/playtest grant-and-entitlement target at connect-token issuance. **Current response drift:** the live `ConnectTokenResponse` body exposes the internal `jti`; the target response is metadata-only and must not expose `jti` or any raw token. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | +| `POST` | `/auth/bootstrap/join` | **Local Account controller and operation; complete production proof incomplete.** The local `JoinPublicProductionMembership` operation implements explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then reads entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Exact-final-head PostgreSQL proof, recovery/reconciliation after an unknown commit outcome, direct text end-to-end proof, and membership-generation snapshot proof remain open. | | `DELETE` | `/tenants/{tenantId}/memberships/me` | Leave a joined game using caller-bound membership authority; removes future membership-based discovery/admission while retained character, purchase, audit, and legal data follow their owning policies | | `GET` | `/internal/runtime/tenants/{tenantId}/entitlements` | Internal runtime/admission entitlement snapshot for gameplay-affecting services | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | @@ -230,7 +231,7 @@ Every tenant-targeted request identifies its tenant in the route or request cont | --- | --- | --- | --- | | Public auth/bootstrap | `/auth/login`, `/auth/request-password-reset`, `/auth/complete-password-reset`, `/auth/request-email-verification`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. `POST /auth/verify-email` is target-public but is excluded from the current public allowlist and therefore requires a bearer under the current configuration; the allowlisted `GET` has no controller mapping. | | Player bootstrap issuance | `/auth/player-bootstrap` | First-party player account authentication bootstrap | **Target state:** issues the `player-bootstrap` token profile only after atomically creating its one active `session:auth:token:` registry record; registry failure fails issuance before exposure. It must not return a `control-ui` JWT or perform tenant-scoped admission checks. It may share Account's credential verification, abuse controls, and account-state checks with `/auth/login`, but the endpoint, audience, claims, lifetime, and allowed surfaces remain distinct. **Current implementation:** uses the legacy `session:auth:account::` Account session key rather than the ADR 0035 registry shape. | -| Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | The implemented bootstrap derives caller identity before tenant selection, then resolves tenant scope through realm discovery. World and realm discovery may show a public production target before membership exists; character discovery now requires the caller's current membership to exist and permit gameplay admission, while explicit `/auth/bootstrap/join` remains the unimplemented target-state first-party open-enrollment writer. Character discovery and connect-token issuance consume the opaque server-issued `connectScopeId`, verify the route matches it, and revalidate its tenant/runtime target against current admission state. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Account delivers the connect token only through the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. | +| Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | The implemented bootstrap derives caller identity before tenant selection, then resolves tenant scope through realm discovery. World and realm discovery may show a public production target before membership exists; character discovery now requires the caller's current membership to exist and permit gameplay admission, and `/auth/bootstrap/join` has a local Account controller/operation for the explicit first-party open-enrollment writer. Character discovery and connect-token issuance consume the opaque server-issued `connectScopeId`, verify the route matches it, and revalidate its tenant/runtime target against current admission state. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Account delivers the connect token only through the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | | Authenticated account control-plane APIs | Current legacy `/accounts/{accountId}/export`; target `/auth/logout`, `/auth/logout-all`, `/tenants/{tenantId}/profiles/{accountId}`, active-account `/accounts/{accountId}/exports/**`, `/accounts/{accountId}`, `/tenants/{tenantId}/memberships/me`, `/tenants/{tenantId}/memberships/{accountId}` | Exact ordinary account subject through the declared `control-ui` JWT route class | This is the target authentication class only while the account remains eligible for ordinary authority. The current singular legacy export is classified here as an ordinary authenticated account-subject route; the target export lifecycle uses the authenticated account subject while active. The REST inventory identifies which routes are currently implemented and which remain target-only. | | Tenant-admin billing-safe export | `/tenant-admin/tenants/{tenantId}/export` | Exact `control-ui` caller with live `tenantAdmin` membership bound to the `{tenantId}` route segment | `billing_safe_tenant` classification. The route has a tenant binding but no `accountId` subject selector, requires live membership and membership-generation evidence, and remains target-only/not currently routable. | diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index 943f66281f..585438a383 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -11,7 +11,7 @@ This document collects the Account Service operational behavior, readiness model ## Saga Participation -The Account audit handoff is a mandatory owner-local durable-outbox target, not a compensated Saga step. Global registration creates only global account/security state and emits a platform-scoped audit with no `tenantId` from that transaction; tenant-scoped profile and membership operations are separate and use the exact committed `tenantId`. Explicit `JoinPublicProductionMembership` emits its separate tenant-scoped audit from the membership transaction. Global `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity audits likewise use platform scope and omit `tenantId`. Producer consequences are defined in [Account Runtime and Data](./runtime-and-data.md#architecture-and-runtime-notes), while the normative ingress, envelope, receipt, readback, retention, and authorization contract is owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). **Current runtime:** Account persists the account, profile, and membership locally, then attempts the `CreateLogEvent` RPC post-commit on a best-effort basis. Logging failure is swallowed and does not roll back or compensate the committed creation. The owner-local outbox and corresponding proto/receiver implementation must be implemented and proved before mandatory audit delivery is claimed. No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker; existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). +The Account audit handoff is a mandatory owner-local durable-outbox target, not a compensated Saga step. Global registration creates only global account/security state and emits a platform-scoped audit with no `tenantId` from that transaction; tenant-scoped profile and membership operations are separate and use the exact committed `tenantId`. Explicit `JoinPublicProductionMembership` emits its separate tenant-scoped audit from the membership transaction. The target contract also requires global `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity audits to use platform scope and omit `tenantId`; those producers are not yet converged to the current outbox path. Producer consequences are defined in [Account Runtime and Data](./runtime-and-data.md#architecture-and-runtime-notes), while the normative ingress, envelope, receipt, readback, retention, and authorization contract is owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). **Current local implementation:** registration and successful explicit JOIN append immutable audit envelopes to Account's SQL outbox in the same local transaction as their owner-state writes. A delivery job sends the unchanged envelope to Logging & Admin and marks it complete only after matching receipt evidence; failed or ambiguous delivery leaves the event pending for retry with the same identity. Logging & Admin locally implements receipt persistence, deduplication, exact payload digest checking, and receipt readback. This status does not claim PostgreSQL runtime proof or direct text-client end-to-end proof. Durable recovery/reconciliation of a JOIN operation left `PENDING` after an unknown database commit outcome remains open under the Overseer decision and ADR 0025. These audit paths are not Account Saga steps. No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker; existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). The current `PurchaseWorkflowService` implementation for one-time payments and donations is non-exposed, unsupported provider-mutating drift, not a V1 product path or entitlement authority. It currently enters the shared runner to create a payment intent, record the transaction with the Logging & Admin Service, and refund through compensation if the log step fails. The target Account containment boundary requires every generic purchase or donation entry point to reject before entering that runner or making any Stripe call; no supported V1 flow may invoke it. Current V1 remains the hosting-billing boundary in [ADR 0143](../../decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md), while the future marketplace direction in [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md) remains deferred and must be implemented and proved separately. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index bdb465b82a..108d19b6e1 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -16,11 +16,11 @@ Account V25 enforces the live tenant-scoped profile identity `(tenantId, account Account implements bounded owner-local cleanup of expired password-reset, email-verification, and email-login-challenge SQL rows, with per-family deleted-row counts and oldest-expired-row lag metrics. The cleanup uses the same process-local wall-clock basis as current credential issuance and validation against timezone-less SQL timestamps; cross-node timezone normalization and existing-row migration are not established by this cleanup. Six focused unit cases in `ExpiredCredentialCleanupJobTest` executed locally; seven PostgreSQL integration cases in `CredentialCleanupRepositoryIntegrationTest` passed in hosted CI, while local execution compiles but skips them when Docker is unavailable. This cleanup does not claim atomic token consumption, session revocation, or completion of the full [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) retention contract; shared retention classes, dependency horizons, blockers, holds, and cross-service proof remain outstanding. -The live account-creation paths still require a caller-provided `tenantId` and create an admission-enabled `AccountTenantMembership` as part of account creation. Legacy Account migrations also default existing account/profile and billing rows to tenant `1` and backfill membership from that value. This conflicts with the canonical [global-registration and explicit `JoinPublicProductionMembership` flow](../../system-architecture-authentication.md#login-and-session-flow). This is a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. +The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback returns a stored terminal outcome when present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. Successful repeated JOINs replay the stored operation result; `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. -The live runtime membership response currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`, while the latter response cannot be classified as `INACTIVE` and explicit `JOIN` remains unavailable. They do not create or restore membership. The obsolete implicit membership-writer surface has been removed, and explicit `JOIN`/`Join & Play` remains target-only and unimplemented. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. The proto and Account producer emit lifecycle state and generation, but Game Session does not validate them; `authorityAvailability`, `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent, and one authoritative snapshot with fail-closed consumer proof is not established. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the two admission fields are true; an eligible public-production request with missing or non-admitting membership may return `JOIN_REQUIRED`, but the current consumer does not distinguish `INACTIVE` from another existing non-admitting lifecycle state. These paths do not create or restore membership. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. The durable recovery/reconciliation seam for an operation left `PENDING` after an unknown database commit outcome remains open; no Overseer decision is implied. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. The current `application.yml` and `application-prod.yml` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods. The shared interceptor therefore bypasses bearer validation, while the current handlers use request-body `accountId`/`tenantId` values without exact workload or typed caller-context checks. This contradicts the internal-only matrix contract and blocks readiness until the methods are removed from the public bypass list and missing-token, wrong-workload, tenant-binding, and cross-tenant negative proof is present. @@ -28,7 +28,7 @@ The target realm-grant mutation boundary remains the Account API's tenant-admin Recovery/verification foundations are live, but the current password-reset transaction reads a token, updates the account, and deletes the token as separate operations. Concurrent requests can therefore consume the same valid reset token more than once; atomic single-use consumption and concurrent-reuse proof remain required under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). -The direct-text `REALMS`-to-`JOIN` scope handoff is also target-only and unimplemented. Account-local remaining work is to validate the authenticated `PlayerExecutionContext` separately from the short-lived target-bound scope, issue that scope during authenticated realm resolution, and validate its exact routing snapshot at `JoinPublicProductionMembership`; Game Session transport retention and server-generated join-attempt identity are defined by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). +The local direct-text `REALMS`-to-`JOIN` path issues a short-lived Account-owned scope for an authenticated caller and validates the retained target snapshot and caller binding at `JoinPublicProductionMembership`; Game Session supplies a server-generated join-attempt identity. A committed policy-independent intent survives entitlement outages and can be resumed by an exact request retry; when the second transaction outcome is uncertain, Account reads back and returns a terminal result if committed, otherwise asks the caller to retry that request ID. No background recovery worker or direct text-client end-to-end proof is claimed. The canonical scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). @@ -41,8 +41,8 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi Raw Telnet and other non-WebSocket text streams never see or transmit these JWT profiles. First-party browser/mobile gameplay clients use only the bounded `player-bootstrap` profile for HTTPS bootstrap; the one-use WebSocket connect token is a separate edge credential. Generic `Service JWT` and `aud=internal` profiles are forbidden. Workload-only calls use mTLS and exact method allowlists without a bearer token. Gameplay protocol clients (Telnet and WebSocket) never see or transmit private delegation tokens. - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. -- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after exact receipt/readback or reconciliation; unavailable, timeout, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current runtime:** local writes commit first; Account then attempts `CreateLogEvent` post-commit on a best-effort basis, and logging failure is swallowed without compensating or rolling back creation. The current proto and receiver do not yet carry or enforce the target identity, envelope, digest, deduplication, readback, or Account workload authorization contract, so the durable outbox and mandatory receiver implementation remain open. -- **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current runtime:** Account attempts `CreateLogEvent` after its local commit on a best-effort basis and swallows logging failure; that attempt is not delivery proof. +- **Target state:** global Account registration creates only global account/security state and records a durable, owner-local audit outbox entry in that same local transaction. Tenant-scoped profile and membership operations are separate from registration; registration audit uses explicit **platform scope** and never fabricates a `tenantId`, creates membership, or restores membership. Tenant-scoped profile and successful `JoinPublicProductionMembership` events use explicit **tenant scope** with the exact committed `tenantId`; they never use platform scope. The sole membership writer remains explicit `JoinPublicProductionMembership`; a successful JOIN records its separate tenant-scoped audit/outbox consequence in the same membership transaction as described below. Each outbox record preserves one stable `auditEventId` and immutable event envelope/digest across retries, then delivers that unchanged record through the canonical Account audit-ingress, receipt, and readback contract owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Any upstream Account domain-event digest is payload evidence; Logging & Admin's receiver computes its separate `payloadDigest` over the exact payload bytes. Account treats delivery as complete only after an exact receiver receipt; unavailable, timeout, mismatched, or ambiguous responses remain retryable with the same identity and never mint a replacement event. A terminal `MINIMIZED/NON_REPLAYABLE` result after the receiver's safe watermark is recorded against that same outbox identity, ends producer retry/reconciliation, and does not create a replacement event. Account's outbox cleanup remains gated by the receiver/readback horizon and safe-watermark rules owned by Logging & Admin; Account does not invent a second retention policy. This does not make Logging & Admin a second authority for Account state. **Current local implementation:** global registration and successful explicit JOIN append immutable Account audit envelopes in their respective local transactions. Account's delivery job submits the unchanged envelope and marks it delivered only after Logging & Admin returns matching receipt evidence; failures leave it `PENDING` for retry. Logging & Admin locally implements durable receipt deduplication, exact payload-byte digest validation, receipt readback, and terminal minimized receipts. After an accepted terminal minimized receipt, Account atomically clears only its producer payload and retains compact event, digest, and receiver identity evidence; `COMMITTED` producer payloads still lack configured safe-watermark, hold, reference, and finite-retention cleanup proof. These are local implementation facts, not PostgreSQL runtime or direct text end-to-end proof. The JOIN intent is committed before entitlement work, while policy binding, membership, audit outbox, and terminal outcome share one second transaction. Request-driven retry resumes a pending intent; an absent terminal readback is reported as retryable unavailable, not as a membership result. No periodic pending-operation reconciler is claimed. +- **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN use the durable outbox/receipt path described above. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). - The core `account` record represents a global platform account identified by `accountId`. Tables that represent per-game state or billing attach to tenants via a `tenantId` column so the same platform account can join multiple games without data leakage. Every tenant-scoped query enforces this filter as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). - Provides a JWKS endpoint for other services to validate tokens. Account Service owns signing-key lifecycle authorization, token issuance/rotation, desired key-ring state, and JWKS publication. In target non-exportable-signer mode, Account delegates only explicitly authorized private-key operations to the approved signer boundary; signer custody does not transfer lifecycle or publication authority. In the interim Account-only mounted fallback, the materialization controller is the sole Kubernetes API reader, writer, and generator for the fixed `jwt-signing-keys` Secret and custodian of that interim private material, but it may act only on Account-authorized operations. Account consumes projected key files and has no signing-Secret API authority. Kubernetes Jobs or CronJobs only observe Account-owned rotation, convergence, and retained evidence; they do not request or own rotation, read or write private keys, or publish JWKS, as described in the [Security Architecture](../../system-architecture-security.md). @@ -50,7 +50,7 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi - Telnet and other non-WebSocket text transports authenticate through the credential-bearing `LOGIN` flow described in [Authentication & Authorization](../../system-architecture-authentication.md) and do not carry public JWTs or gameplay connect tokens. First-party browser/mobile/server clients use the short-lived `player-bootstrap` profile for HTTPS bootstrap and an HttpOnly-cookie connect token for the WebSocket handshake. Explicitly classified non-first-party/public generic WebSocket clients have no current supported connect-token carrier; the dedicated issuance route, secure-storage response, and `X-Firemud-Connect-Token` handshake header remain target-only until their authorization-matrix, replay, signed-context, response, and carrier proofs are complete. The Game Session Service calls the internal `Authenticate` gRPC method (mTLS-protected) to verify credential-bearing login and obtain `game-session-account-delegation` JWTs for Account, while `/auth/login` remains a browser/control-plane endpoint. - Admin and creator UI authentication is initiated via the `/auth/login` HTTP endpoint, which issues `control-ui` JWTs used only for the exact control-plane audience described in the authentication and frontend architecture designs. - Owns credential brute-force defense and login abuse handling for every password and verified-email-code path. It combines trusted canonical source context with normalized account-candidate and coarse pressure buckets, applies graduated temporary throttles, and emits stable retry outcomes. These buckets are policy signals, not durable authority; any Cache/Rate-Limit Redis use must preserve one-to-one opaque subject isolation or explicitly declare a coarse heuristic, bounded cardinality, eviction/reset behavior, and outage mode under [ADR 0087](../../decisions/adr-0087-isolated-subject-rate-limits-with-explicit-loss-semantics.md). Ordinary failed attempts never transition the account to `security_locked`; that durable state requires evidence supporting a verified or high-confidence compromise assessment, explicit security policy, or audited operator action. Account is also the sole canonical resolver and publisher of the effective versioned security policy; callers do not merge deployment or tenant overrides or fall back to cached/default values, and an unavailable or contradictory policy resolution fails sensitive actions closed. Suspicious activity triggers notification emails and audit events as described in [Security Architecture](../../system-architecture-security.md#brute-force-defense-and-abuse-handling) and [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md). -- No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker. The existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift and do not authorize future Saga use. Account creation's cross-service audit handoff is target-state owner-local outbox work, not a compensated Saga step; the current post-commit best-effort behavior and its failure semantics are described above. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). +- No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker. The existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift and do not authorize future Saga use. Account registration and explicit JOIN audit handoffs use the owner-local outbox and are not compensated Saga steps. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). - Leverages the [Shared Libraries](../../system-architecture-shared-libraries.md) for common DTOs, logging interceptors, and Micrometer metrics. ## Data Model @@ -139,7 +139,7 @@ The `player-bootstrap` token profile is distinct from both `control-ui` and priv - Audience is `player-bootstrap`. - It is issued only by `POST /auth/player-bootstrap` / `IssuePlayerBootstrapToken`. - `POST /auth/player-bootstrap` is the canonical first-party browser/mobile player-login endpoint. It authenticates player credentials directly under the same password, OTP, brute-force defense, and account-lock policy used for gameplay login rather than deriving bootstrap from a pre-existing admin/creator session. -- It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. The current runtime requires existing caller-bound membership for character discovery, connect-token issuance, and text `PLAY` and uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. For a publicly visible public-production target whose joining policy permits entry, `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating or restoring membership; the latter response is not lifecycle-aware and explicit `JOIN` remains unavailable. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. +- It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. The current runtime requires existing caller-bound membership for character discovery, connect-token issuance, and text `PLAY` and uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. For a publicly visible public-production target whose joining policy permits entry, `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return `JOIN_REQUIRED` without creating or restoring membership; the latter response is not lifecycle-aware while explicit `JOIN` is a separate local action. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. - It is stored in memory only by first-party gameplay UIs and is accepted only on gameplay-bootstrap surfaces such as bootstrap discovery and `POST /auth/connect-token`. - For first-party `/ws/game/**`, subsequent gameplay `LOGIN` must complete from the bootstrap/connect context already established for that socket; browser clients must not be required to replay account credentials after bootstrap. - If the token is lost because the page/app process is restarted, the client must restart bootstrap from `POST /auth/player-bootstrap`; the current architecture does not define a hidden silent-bootstrap refresh mechanism. @@ -176,7 +176,7 @@ Runtime caller contract: - Minimum request fields: `accountId`, `tenantId`, `requestId`. - Target minimum response fields: `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `authorityAvailability`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and the applicable `outboxCheckpoints[]` entry for the membership authority stream. - `membershipAuthorityGeneration` is an opaque Account-owned value. Runtime callers compare it only for exact freshness/equality and must not infer ordering or authority from its representation. It is the authoritative generation for connect-token issuance, gameplay-token refresh, gameplay binding and reconnect validation, and membership revocation. -- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. Current generated proto, Account implementation, and runtime callers do not yet expose and prove every target field, including `membershipLifecycleState`, `authorityAvailability`, and the opaque generation; that remains implementation drift. +- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The generated proto and Account producer emit `membershipLifecycleState` and the opaque generation, but current runtime callers do not enforce either field. `authorityAvailability`, roles, the complete tuple, and checkpoints remain absent; a fresh atomic target snapshot and fail-closed consumer proof remain implementation drift. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` is the authoritative internal entitlement surface for gameplay/runtime flows. Runtime callers may cache its positive result only under the strict-new-commitment and bounded-continuity rules in [ADR 0028](../../decisions/adr-0028-differentiated-entitlement-freshness.md); the cache never becomes a second writer. - Minimum request fields: `tenantId`, `requestId`. - For target player-admission calls only, the minimum request additionally carries `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. Game Session supplies these fields as trusted typed execution/request context; the private `game-session-account-delegation` JWT carries its declared Account authority but does not carry `verifiedConnectScopeId` or the complete runtime target bundle. Account requires `callerAccountId` to equal the authenticated delegation JWT's `accountId`/`sub` and the exact bound Game Session subject, then verifies the scope and target fields against the signed connect scope and current exact target before returning the already-declared caller/target-bound evidence. World Management's tenant/operation-bound lifecycle calls retain their separate operation context and do not fabricate player-binding fields. @@ -206,7 +206,7 @@ Runtime caller contract: - `requestId` is the idempotency key for connect-token issuance. Retrying the same `(accountId, connectScopeId, requestId)` replays the same deterministic application failure directly while its retained failure envelope is available. A stored success returns the same token payload only after current authority and all applicable admission, registry, and issuance postconditions revalidate; failed revalidation returns the applicable canonical denial without reminting or mutating the committed issuance result. If the compact receipt still exists after its encrypted response envelope has been removed at the declared response-recovery horizon, an exact digest match returns `RESPONSE_RECOVERY_EXPIRED`, never remints or reconstructs a JWT, and is terminal for that original issuance attempt; callers must start a fresh authorized request under a new `requestId`. A changed digest remains `IDEMPOTENCY_CONFLICT`. The exact membership freshness baseline used for issuance is bound to that `connectScopeId` and `requestId`; it is immutable comparison evidence, not a duplicate request field. If Gateway may already have consumed the token, the caller must rediscover and use a new `requestId` rather than replaying the prior issuance key. - Existing caller-bound membership is mandatory for every target. For a selected publicly visible public-production target whose joining policy permits entry, missing membership returns `JOIN_REQUIRED`, commits no membership row, successful gameplay-connect issuance record, token registry record, token, or cookie, and records the same deterministic failure under `(accountId, connectScopeId, requestId)`. An exact retry replays `JOIN_REQUIRED` even if membership is created later while its failure envelope remains retained; after response-envelope removal, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` rather than minting or changing the result. The caller must use a new request ID after the explicit join or recovery-expired terminal outcome. The target replay outcome is durable for the complete issuance-idempotency window. The current implementation provides only the bounded Session Service replay record, so durable database-backed failure replay remains an implementation gap. A private or playtest target additionally requires the current Account-owned realm-access grant; a grant never substitutes for membership or public onboarding. - - `JoinPublicProductionMembership` is the sole target canonical name for the authoritative explicit open-enrollment membership operation. Its target request preserves exactly `connectScopeId` and `requestId`; for direct text, Game Session supplies the retained scope and generates the high-entropy request ID server-side rather than accepting either value from the client. The internal boundary authenticates the exact Game Session mTLS workload and validates its typed caller-bound `PlayerExecutionContext`, including `accountId`, before using the scope. The scope binds the target and exact catalog/pointer pair, not the membership subject. Public player-bootstrap surfaces derive `accountId` from the authenticated caller and do not accept a caller-selected account ID. Account verifies the exact bound catalog/pointer pair at commit, separately from the fresh Account entitlement `allowPublicJoin` check. Connect-token issuance and public-production `PLAY` must require its result but never invoke it implicitly. Explicit `JOIN`/`Join & Play` remains target-only and unimplemented; no implicit membership writer is exposed by connect-token issuance or `PLAY`. + - The target membership-writer contract is `JoinPublicProductionMembership`; its canonical caller, scope, policy, and replay behavior is owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Connect-token issuance and public-production `PLAY` require existing membership and never invoke the writer implicitly. The local Account RPC, digest, transaction, and recovery status are recorded under [Implementation Status](#implementation-status). - It is valid only for the default public production realm and only when the caller satisfies the public-production admission policy. - `requestId` is the attempt idempotency key and `connectScopeId` remains a required request field. Account uses the canonical JOIN digest preimage, field order, and UTF-8 encoding defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). It persists the resulting digest with the verified caller/scope inputs and operation record. Retrying the same `{connectScopeId, requestId}` and digest returns the same membership result or deterministic application failure; a changed digest returns `IDEMPOTENCY_CONFLICT`, while a changed request ID is a distinct operation. - The resulting membership must be immediately visible to `GetTenantMembershipForRuntime`. @@ -268,8 +268,7 @@ Current `AccountRealmAccessGrant` persistence and internal grant reads are limit ### Runtime Implementation Status and Drift -- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks local membership existence/admission after fresh entitlement and target checks. Only an absent membership on an eligible public-production target may return `JOIN_REQUIRED`. A present non-admitting membership is denied without `JOIN_REQUIRED`; the current four-field response cannot classify it as `INACTIVE` because lifecycle state is target-only. Current text `PLAY` still may return non-actionable `JOIN_REQUIRED` for a missing or present non-admitting membership on an eligible public-production target, as tracked for Unit 1B. Explicit `JOIN` remains unavailable. The current non-public mappings differ by surface: Account connect-token issuance and character discovery return `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text `PLAY` maps either case to `WORLD_ACCESS_DENIED`. This split is current behavior, not the target canonical outcome; target private/playtest admission uses `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership and keeps grant denial separate. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. -- Explicit `JOIN`/`Join & Play` and the membership-authority-generation reread at connect-token issuance remain target follow-through. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. +- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks local membership existence/admission after fresh entitlement and target checks. Only an absent membership on an eligible public-production target may return `JOIN_REQUIRED`. A present non-admitting membership is denied without `JOIN_REQUIRED`; the current four-field response cannot classify it as `INACTIVE` because lifecycle state is target-only. Current text `PLAY` still may return `JOIN_REQUIRED` for a missing or present non-admitting membership on an eligible public-production target, as tracked for Unit 1B. The local explicit `JOIN`/`Join & Play` operation and controller exist. The current non-public mappings differ by surface: Account connect-token issuance and character discovery return `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text `PLAY` maps either case to `WORLD_ACCESS_DENIED`. This split is current behavior, not the target canonical outcome; target private/playtest admission uses `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership and keeps grant denial separate. PostgreSQL exact-final-head proof, recovery/reconciliation after unknown JOIN commit outcomes, direct text-to-Logging end-to-end proof, and the membership-authority-generation reread at connect-token issuance remain incomplete. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. ## Monetization and Notification Domain Notes diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 46c08e9f43..9860a6516d 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -8,7 +8,7 @@ The canonical Account-to-Logging & Admin audit ingress is the existing `logging_ Target `CreateLogEventRequest` carries `scope` (`platform` or `tenant`), `tenantId` only for `tenant` scope and never for `platform` scope, stable `auditEventId` generated and persisted by Account, `producerService`, `eventType`, producer `occurredAt`, positive `schemaVersion`, exact UTF-8 `payload`, `payloadDigestVersion` exactly `1` until a later canonical digest-version registry is accepted, and `payloadDigest`. Global registration, `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity events use `platform` scope with no `tenantId`; tenant profile and JOIN events use `tenant` scope with the exact committed `tenantId`. Unsupported digest versions fail before deduplication or persistence. `producerService` is derived from the authenticated Account workload identity and a mismatching request value is rejected. An upstream producer domain-event digest, when present inside `payload`, remains opaque payload evidence and is distinct from the receiver's `payloadDigest`. `payloadDigest` is `sha256:` followed by 64 lowercase hexadecimal characters over the exact UTF-8 payload bytes under `payloadDigestVersion=1`; no JSON reserialization or alternate canonicalization is permitted. Retry equivalence is the complete immutable `(scope, tenantId-if-tenant, auditEventId, producerService, eventType, occurredAt, schemaVersion, payloadDigestVersion, payloadDigest, exact payload bytes)` tuple: while exact payload bytes remain retained, an exact match returns the original receipt, while any changed field or payload bytes fails closed as `IDEMPOTENCY_CONFLICT`. After the safe watermark permits payload minimization, the retained identity and metadata may still detect a changed non-payload field, but the receiver must not claim exact payload equality or replay; a matching late request is a terminal non-replayable result. Timeout, transport failure, or an ambiguous response is not success; the producer retries or reconciles with the same identity and digest and never mints a replacement event. -`CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. The current proto and receiver instead expose only the legacy `CreateLogEvent` shape and `AdminRoleGuard`; this is explicitly current drift pending the target convergence. +`CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. **Current local implementation:** the Account audit request/response schema, Account workload check, exact payload digest validation, durable receipt insert/deduplication, bounded receipt readback, and accepted/duplicate/conflict/minimized outcomes are implemented locally. Account registration and JOIN now produce owner-local outbox entries; Account's delivery client checks returned receipt evidence before marking delivery complete. Focused local unit coverage exists, but PostgreSQL runtime proof and direct text-client-to-Logging end-to-end proof are not claimed. The target contract remains authoritative for full retention/readback horizons and any unresolved runtime edge cases. The receipt retention class and cleanup owner are defined in [Logging & Admin Runtime and Data](./runtime-and-data.md#audit-envelope-and-receipt-retention). diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index c956fb822e..2bd550bb6a 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -30,7 +30,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. - The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -- **Membership behavior (current versus target):** The explicit join action and the required `membershipAuthorityGeneration` reread at connect-token issuance remain unimplemented/proof gaps. On a cache miss, current connect-token issuance and text `PLAY` require a fresh current Account membership adapter response identified by `accountId` and `tenantId`, with these four admission-evidence fields: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; the first two must be true. A current `session:connect-token:*` replay hit can return a cached success before fresh entitlement, membership, and pointer rereads; the exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` separately reads the current realm grant for private/playtest targets. The adapter response has no `membershipLifecycleState` field: `membershipExists=false` represents missing membership, while `membershipExists=true` and `gameplayAdmissionAllowed=false` represents existing but non-admitting membership without distinguishing `INACTIVE` from any other existing non-admitting state. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`; the latter cannot be classified as `INACTIVE`, and explicit `JOIN` remains unavailable. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`. Current connect-token issuance retains its Account-owned rejection mapping and its private/playtest grant validation remains incomplete. Both paths return `AUTH_UNAVAILABLE` for unavailable or unsafe membership authority. This current `JOIN_REQUIRED` result is a fail-closed, non-actionable denial while explicit `JOIN`/`Join & Play` is unimplemented; it must not be presented as proof that the target repair flow is available. The obsolete writer seam has been removed, while the complete first-party browser/mobile sequence remains target-only and individual bootstrap/connect-token endpoints remain partial implementation surfaces. Returning members may proceed when current runtime membership and character checks pass, but current behavior does not prove the target exact generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh membership snapshot. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires the applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. +- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`; the required `membershipAuthorityGeneration` reread at connect-token issuance remains a proof gap. On a cache miss, current connect-token issuance and text `PLAY` require a fresh current Account membership adapter response identified by `accountId` and `tenantId`, with these four admission-evidence fields: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; the first two must be true. A current `session:connect-token:*` replay hit can return a cached success before fresh entitlement, membership, and pointer rereads; the exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` separately reads the current realm grant for private/playtest targets. The adapter response has no `membershipLifecycleState` field: `membershipExists=false` represents missing membership, while `membershipExists=true` and `gameplayAdmissionAllowed=false` represents existing but non-admitting membership without distinguishing `INACTIVE` from any other existing non-admitting state. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return `JOIN_REQUIRED`; the latter cannot be classified as `INACTIVE`. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`. Current connect-token issuance retains its Account-owned rejection mapping and its private/playtest grant validation remains incomplete. Both paths return `AUTH_UNAVAILABLE` for unavailable or unsafe membership authority. This current `JOIN_REQUIRED` result remains a fail-closed admission denial until the caller completes the local explicit join operation; it is not proof of the target lifecycle snapshot or final admission flow. The obsolete writer seam has been removed, while the complete first-party browser/mobile sequence remains partial and its PostgreSQL, recovery/reconciliation, direct text end-to-end, and downstream membership-generation proof remain open. Returning members may proceed when current runtime membership and character checks pass, but current behavior does not prove the target exact generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh membership snapshot. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires the applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. - **Target-only/currently unavailable public non-browser issuance:** Public non-browser connect-token issuance and `X-Firemud-Connect-Token` carriage are not current supported capabilities. They may be exposed only after a dedicated route is fully registered in the authorization matrix and its `gameplay-connect` issuance/replay record, `replayAdmissionFence`, quarantine/deny state, signed-context, response, and carrier proofs are complete. This path is exempt from the ordinary active issued-token registry, `tokenGeneration`, `issuanceFence`, and `session:auth:token:` record; its bounded selected-target `authorityTuple` and separate `membershipVersion` are immutable issuance evidence passed into the later exact-binding admission checks, not a registry lookup or standalone gameplay authority. Current clients must not be told that header support exists. - First-party browser and mobile-browser gameplay use the short-lived `player-bootstrap` JWT for HTTPS bootstrap calls and carry the resulting gameplay-connect token only in the `Firemud-Connect-Token` HttpOnly cookie. First-party native-mobile and other first-party non-browser clients using a cookie jar remain cookie-only. Telnet and other non-WebSocket text transports use credential-bearing `LOGIN` and do not carry public JWTs or connect tokens. - `/sessions/{sessionId}/refresh-roles` exists as an operational hook, but current role-refresh token regeneration and periodic active-session `game-session-account-delegation` rotation remain implementation gaps; the placeholder response is not proof of refresh. @@ -271,9 +271,31 @@ These modes are complementary: public browse remains available before authentica ``` The field names, `=`, line separators, and final newline are literal ASCII bytes. Values use the owning contract's canonical UTF-8 wire forms (including canonical decimal revisions and UTC RFC3339 timestamps), are not trimmed, case-folded, or Unicode-normalized, and may not contain `=` or a newline. `targetClass` is server-derived and not caller input. The bracket notation in the preimage illustration denotes conditional lines, not literal bytes: for `PUBLIC_PRODUCTION`, both lifecycle lines are omitted entirely, never encoded as empty, null, or sentinel values; for `NON_PUBLIC`, both are required, with a positive `playtestStateGeneration`. Account stores the digest with the scope record, including the immutable `evaluatedAt` value, and exact-compares it with the complete stored field set whenever the scope is consumed; a missing, extra, altered, or differently serialized field fails closed. This Account-owned scope-integrity evidence is distinct from the separately signed Gateway context and the JOIN idempotency digest. -- The canonical `JOIN` idempotency digest is `SHA-256` over the UTF-8 bytes of this exact newline-delimited preimage, including the final newline and preserving this field order: +- Before consulting entitlement authority, Account durably claims the stable `requestId` as `PENDING` with a policy-independent `joinIntentDigest/v1`. This immutable intent digest binds the request ID, authenticated account, verified caller binding, verified `connectScopeId` and scope snapshot digest, and the complete server-resolved target. It contains no entitlement availability, policy result, or entitlement version. The claim is committed before policy evaluation so an unavailable authority or an uncertain later transaction cannot erase evidence of the logical attempt. The intent digest is `SHA-256` over the UTF-8 bytes of the exact newline-delimited preimage below, including the final newline. Field names, `=`, separators, and the final newline are literal ASCII bytes; values use the canonical UTF-8 wire forms of the validated request and scope and may not contain `=` or a newline. A retry must match this intent exactly; a changed intent under the same request ID returns `IDEMPOTENCY_CONFLICT`. ```text + joinIntentDigestVersion=v1 + operationKind=JOIN + requestId= + accountId= + callerBinding= + connectScopeId= + scopeDigest= + tenantId= + worldSlug= + realmSlug= + realmId= + playableStateNamespaceId= + playableStateScope= + gameInstanceId= + catalogRevision= + pointerVersion= + ``` + + The canonical policy-bound `JOIN` request digest is `SHA-256` over the UTF-8 bytes of this exact newline-delimited preimage, including the final newline and preserving this field order. It is computed only after a fresh authoritative entitlement evaluation returns `AVAILABLE` with an exact `allowPublicJoin` result and positive `entitlementVersion`: + + ```text + joinDigestVersion=v1 operationKind=JOIN accountId= callerBinding= @@ -282,13 +304,17 @@ These modes are complementary: public browse remains available before authentica realmSlug= playableStateNamespaceId= playableStateScope= + gameInstanceId= connectScopeId= catalogRevision= pointerVersion= + entitlementAuthorityAvailability=AVAILABLE + allowPublicJoin= + entitlementVersion= ``` - Field names, separators, and the final newline are literal ASCII bytes; values are the exact canonical UTF-8 wire strings from the authenticated caller binding and verified scope and may not contain `=` or a newline. No trimming, case folding, Unicode normalization, alternate serialization, or client-supplied replacement is permitted. Account stores the resulting `requestDigest` with the `requestId`; an exact retry replays the stored outcome and a different digest returns `IDEMPOTENCY_CONFLICT`. -- Account validates the caller binding, `connectScopeId`/`connectScopeSnapshotDigest`, scope validity, expiry, and exact bound routing snapshot `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` before applying the join operation; `evaluatedAt` is the same immutable, canonical UTC RFC3339 value committed in the scope record and hashed by `connectScopeSnapshotDigest/v1`. A non-public target additionally requires exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public production omits both. A missing, expired, or mismatched retained scope fails closed and requires fresh authenticated `REALMS` discovery. An unavailable authority dependency returns `AUTH_UNAVAILABLE` and does not permit selector fallback; reachable invalid or contradictory scope evidence returns the applicable scope failure. The server must not re-resolve a stale selector or accept client-supplied target fields as fallback. +- Field names, separators, and the final newline are literal ASCII bytes; values are the exact canonical UTF-8 wire strings from the authenticated caller binding and verified scope and may not contain `=` or a newline. No trimming, case folding, Unicode normalization, alternate serialization, or client-supplied replacement is permitted. `allowPublicJoin` is lowercase `true` or `false`; `entitlementVersion` is a positive canonical decimal. Account stores the intent digest/version before evaluation, then stores the request digest/version and exact policy evidence only after `AVAILABLE` authority has supplied both policy values. If entitlement authority is unavailable, Account records the attempt failure and availability while leaving the operation `PENDING`; it does not create a policy-bound request digest or invent a policy result/version. A retry with the same intent may reconcile that pending operation when authority is available. At the membership commit gate Account re-evaluates policy and requires the exact same digest and evidence; changed policy returns `IDEMPOTENCY_CONFLICT` without committing membership or its transition event. Exact retries replay the stored operation result after their required current-policy check. No earlier JOIN digest was persisted, so no version-compatibility path is required. +- Account validates the caller binding, `connectScopeId`/`connectScopeSnapshotDigest`, scope validity, expiry, and exact bound routing snapshot `{tenantId, realmId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` before applying the join operation; `evaluatedAt` is the same immutable, canonical UTC RFC3339 value committed in the scope record and hashed by `connectScopeSnapshotDigest/v1`. A non-public target additionally requires exact `playtestLifecycleId` and positive `playtestStateGeneration`, while public production omits both. A missing, expired, or mismatched retained scope fails closed and requires fresh authenticated `REALMS` discovery; for a retained `PENDING` operation, an expired scope terminally returns `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. An unavailable authority dependency returns `AUTH_UNAVAILABLE` and does not permit selector fallback; reachable invalid or contradictory scope evidence returns the applicable scope failure. The server must not re-resolve a stale selector or accept client-supplied target fields as fallback. Normative semantic split: diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index b2c5844a2f..b8c0552065 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -25,7 +25,7 @@ Hosted creator-terms acceptance is an explicit current inventory gap. [ADR 0180] ## Implementation Status -- Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Current `PLAY` returns `JOIN_REQUIRED` for the documented eligible public-production case when the current adapter reports missing membership (`membershipExists=false`) or an existing membership with `gameplayAdmissionAllowed=false`; the current adapter does not expose `membershipLifecycleState`, so the latter response cannot be classified specifically as `INACTIVE` and its lifecycle interpretation/repair path remains target-only. `ACTIVE` membership does not require `JOIN`, while policy denial and unavailable/invalid authority remain distinct outcomes. Explicit `JOIN` remains unimplemented. +- Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Current `PLAY` returns `JOIN_REQUIRED` for the documented eligible public-production case when the Account runtime response reports missing membership (`membershipExists=false`) or an existing membership with `gameplayAdmissionAllowed=false`; Account now exposes `membershipLifecycleState` and `membershipAuthorityGeneration`, but the current Game Session `PLAY` consumer does not yet consume those fields, so the latter response is not classified specifically as `INACTIVE` and its lifecycle interpretation/repair path remains target-only. `ACTIVE` membership does not require `JOIN`, while policy denial and unavailable/invalid authority remain distinct outcomes. Account's explicit JOIN writer is implemented locally, but Game Session text dispatch and direct text-client end-to-end proof remain unavailable in this stage; first-party `Join & Play` and durable unknown-outcome recovery remain incomplete. - `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes requiring the exact Game Session or World Management caller policy in rows 260-261. Current Account development and production configuration incorrectly lists both methods as public gRPC bypasses, and their handlers accept caller-supplied identifiers without typed workload context or tenant binding. Remove the bypass and add missing-token, wrong-workload, and cross-tenant denial proof before runtime readiness is claimed. - The current `IssueConnectToken` route requires existing caller-bound membership for every realm and never creates it; its required membership-authority-generation reread is missing. A realm grant never substitutes for membership. - `privileged_control` is target-only and currently unavailable; route branches that authorize through a global `platformAdmin` or cross-tenant `billingAdmin` role therefore fail closed, while the `support` branch of `cross_tenant_support_safe` does not require `privileged_control`. Operator mutation rows that require an Account-issued authorization reference or this privileged-control window are normative target rows, not current availability claims. @@ -229,6 +229,8 @@ For every first public-production text entry, the target command sequence is `LO | Logging & Admin | `POST /feature-flags/toggle`, `POST /tick-remediation/pause`, `POST /tick-remediation/resume` | `tenant_regular` operator ingress | **Target; not currently routable.** Exact `control-ui` profile and current operator role. Tenant-role branches require live membership and membership-generation freshness; privileged global-role branches require live `current_global_role` and `role_appropriate_assurance`, while the global `platformAdmin` branch uses target-tenant generation without target membership. Each mutation also requires its action schema, shared `mutationDigest/v1` golden vectors, and Account authorization-reference issuance/redemption before enablement. | | Logging & Admin | `POST /moderation/actions` | `tenant_regular` operator ingress for `gameplay_ban`, `chat_mute`, and `chat_ban`; `account_scoped` platform-jurisdiction ingress for `platform_access_ban` | **Target; unavailable/gated.** The closed `action` selector selects exactly one matrix variant and rejects `account_security_lock`, unknown, and legacy values before branch authorization. Tenant-scoped categories retain the `tenant_regular` branch: `moderator`, `tenantAdmin`, and `platformAdmin` use the existing tenant membership/tenant-generation or global target-tenant-generation consequences. `platform_access_ban` uses the separate `account_scoped` branch: only global `platformAdmin` with `privileged_control`, explicit global target-account binding and platform scope, no `tenantId`, no tenant billing generation, and no membership or tenant-generation checks. Both variants link the root moderation policy-intent authorization contract: Logging & Admin redeems the local Account reference at its receiving boundary; any later owner-enforcement command uses a distinct identity/digest/reference/fingerprint and is redeemed by the selected owner. Target mutation contract: `durable_intent_then_moderation_record_idempotency`. Account remains the enforcement owner for the global restriction; target Game Session and Social & Groups enforcement reads the applicable owner-local durable restriction state or projection. **Current compatibility drift:** both consumers instead call the live `EvaluateModerationPolicy` read at their enforcement boundaries; that read is not a second target moderation authority. Owner-enforcement command coverage remains a recorded gap. | | Logging & Admin | `POST /reports` | `player_bootstrap_tenant` | **Target-only; not currently routable.** Accepts caller-bound `player-bootstrap`, derives `tenantId` and `reporterAccountId` from the authenticated caller and live membership, applies `moderation_report_policy`, and writes a caller-bound durable report record. | +| Logging & Admin | `CreateLogEvent` | `internal_workload` Account audit ingress | **Implemented locally; proof incomplete.** This gRPC method accepts only the exact Account Service workload mTLS identity (`spiffe://firemud/ns/{namespace}/sa/account-service`), with no bearer token or operator role. Account is the sole caller and producer; Logging & Admin validates and durably records the Account audit envelope/receipt. PostgreSQL runtime and direct text-client end-to-end proof remain open. | +| Logging & Admin | `ReadLogEventReceipt` | `internal_workload` Account audit receipt readback | **Implemented locally; proof incomplete.** This gRPC method uses the same exact Account Service mTLS-only caller boundary and no bearer token or operator role; it reads the Account audit receipt by the complete immutable envelope tuple and returns the bounded receipt outcome. PostgreSQL runtime and direct text-client end-to-end proof remain open. | | Logging & Admin | `POST /admission-pointers`, `POST /admission-pointers/cutover`, `POST /admission-pointers/version-upgrades` | `tenant_regular` operator ingress | **Target; not currently routable.** This is a target inventory row only: the public OpenAPI surface no longer exposes the admission-pointer open/close/cutover mutations, and the remaining controller/owner paths are implementation drift. The `GET` read/audit/proof-read routes remain live; the `POST` preparation operation is separately gated. Exact `control-ui` profile and current operator role are required for any future ingress. Tenant-role branches require live membership and membership-generation freshness; privileged global-role branches require live `current_global_role` and `role_appropriate_assurance`, while the global `platformAdmin` branch uses target-tenant generation without target membership. Action schemas, shared `mutationDigest/v1` vectors, and Account authorization-reference issuance/redemption are required before external support; the global branch additionally requires target-only `privileged_control`. | | Game Session Service | `ToggleFeatureFlag`, `PauseTicksForScope`, `ResumeTicksForScope`, `SetAdmissionPointer`, `PrepareVersionUpgrade`, `ExecutePreparedVersionCutover` | `internal_workload` mirrored owner RPCs | **Target; not currently routable.** Exact Logging & Admin mTLS workload identity plus an Account-redeemed bounded operator authorization reference; no end-user JWT. These owner RPCs cannot be enabled until the corresponding action schema, shared `mutationDigest/v1` golden vectors, and Account authorization-reference issuance/redemption flow exist. | | Game Session Service | `StartSession` / `RestartSession` / `StopSession` | `internal_workload` operator RPCs | **Status: `target_not_currently_routable` as external operator support.** Exact Logging & Admin mTLS workload identity plus an Account-redeemed bounded operator authorization reference; no end-user JWT. The canonical external ingress is Logging & Admin; direct owner edge exposure is denied during migration. | @@ -242,7 +244,8 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `EnterPrivilegedControlWindow` | `account_scoped` | **Target; not currently implemented.** Exact `control-ui` profile plus recent ordinary reauthentication and independent TOTP; this route creates the bounded role-scoped window and does not require an existing elevation window | | Account Service | `IssueHumanOperatorAuthorizationReference` | `internal_workload` | **Target; not currently routable.** Logging & Admin only: exact allowlisted mTLS workload plus a forwarded `control-ui` token with its exact active Account issued-token registry record; Account rereads current account/token generation, operator roles, role-appropriate assurance, the applicable tenant or target-tenant generation, and required `privileged_control` predicate before issuing the bounded reference | | Account Service | `IssueAutomationOperatorAuthorizationReference` | `internal_workload` | **Target; not currently routable.** Logging & Admin only: exact allowlisted mTLS workload plus current versioned automation policy; no end-user JWT or user impersonation. The current branch is tenant-scoped only, binds the exact current tenant generation, and rejects global-role or `privileged_control` action families | -| Account Service | `JoinPublicProductionMembership` | `internal_workload` | **Target-only; not currently implemented.** Canonical operation is defined by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). The local route is called only by the exact Game Session mTLS workload with typed caller-bound player execution context, accepts no end-user token, and requires `verified_connectScopeId_exact_target`. Account revalidates the exact `connectScopeId`, `catalogRevision`, `pointerVersion`, and resolved target immediately before commit; silent retargeting is forbidden. The obsolete implicit membership writer is removed. | +| Account Service | `IssueDirectTextConnectScope` | `internal_workload` | **Implemented locally; end-to-end proof incomplete.** Exact Game Session mTLS and typed caller/target context are required; Account rereads the public-production target and current gameplay entitlement before retaining an opaque short-lived scope. The scope is not caller authority or a JOIN policy decision; see [Authentication](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) | +| Account Service | `JoinPublicProductionMembership` | `internal_workload` | **Implemented locally; proof incomplete.** Account's explicit writer is the sole membership mutation path; the canonical contract and current transaction consequences are defined by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority). Target-only membership-generation snapshot proof, unknown-outcome recovery/reconciliation, audit receipt/retention proof, PostgreSQL runtime proof, and direct-text end-to-end proof remain open. The obsolete implicit membership writer is removed. | | Account Service | `DELETE /tenants/{tenantId}/memberships/me` | `caller_membership_scoped` | Caller-bound membership exit remains available while billing-blocked to any current member role, requires live subject-bound membership, and advances membership authority atomically | | Account Service | `AuthLogout` / `AuthLogoutAll` | `account_scoped` | Accepts `control-ui` (`audience: control-ui`) or `player-bootstrap` (`audience: player-bootstrap`) with registry-backed authenticated account scope. Bounded retries may return no-op success only from a durable committed exact-token tombstone (`AuthLogout`) or durable proof that a prior logout-all superseded the token (`AuthLogoutAll`); registry absence alone is insufficient and the retry exception grants no reusable authorization context | | Account Service | `GET /accounts/{accountId}/deletion` | `pending_deletion_scoped` | **Target; not currently implemented.** `actionFamily=deletion_status`; the Account-issued credential is bound to the account and deletion workflow and returns deletion status only | diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 16ef35c108..388b2834a0 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -393,7 +393,7 @@ required_live_check_vocabulary: - security_lock_export_action_family implementation_status: known_drift: - - explicit_public_production_JOIN_is_not_implemented; current_PLAY_returns_JOIN_REQUIRED_for_missing_or_existing_non_admitting_public_production_membership; the_live_adapter_uses_membershipExists_false_for_missing_and_gameplayAdmissionAllowed_false_for_existing_non_admitting_membership_without_classifying_the_latter_as_INACTIVE; current_PLAY_returns_WORLD_ACCESS_DENIED_for_missing_non_public_membership; connect_token_issuance_requires_existing_membership_and_never_creates_it; connect_token_membership_authority_generation_reread_remains_unimplemented + - Account_explicit_public_production_JOIN_writer_is_implemented_locally_but_Game_Session_text_dispatch_and_direct_text_end_to_end_proof_remain_unavailable; first_party_Join_and_Play_remains_unimplemented; Account_runtime_membership_response_exposes_membershipLifecycleState_and_membershipAuthorityGeneration_but_current_PLAY_consumer_still_uses_membershipExists_gameplayAdmissionAllowed_membershipVersion_and_evaluatedAt_without_consuming_the_new_fields; current_PLAY_returns_JOIN_REQUIRED_for_missing_or_existing_non_admitting_public_production_membership; current_PLAY_returns_WORLD_ACCESS_DENIED_for_missing_non_public_membership; connect_token_issuance_requires_existing_membership_and_never_creates_it; connect_token_membership_authority_generation_reread_remains_unimplemented - protected_cookie_ws_game_and_bootstrap_bare_LOGIN_are_implemented_but_non_promotable_until_Gateway_carrier_requirements_replay_marker_durability_replay_quarantine_continuity_and_Account_planned_rotation_compromise_cutover_evidence_are_complete - privileged_control_is_target_only_and_unavailable_in_current_runtime; platformAdmin_and_cross_tenant_billingAdmin_branches_requiring_it_fail_closed_while_the_support_branch_does_not_require_it - operator_mutation_rows_are_normative_target_contracts_not_current_availability; action_schema_mutationDigest_v1_vectors_and_account_issued_authorization_reference_flow_are_required_before_external_support @@ -1930,11 +1930,40 @@ routes: mutation_contract: explicit_public_membership_atomic membership_creation: caller_bound_after_validation route_status: target_not_currently_routable + - service: account-service + route: IssueDirectTextConnectScope + scope: tenant + classification: internal_workload + auth_path: exact_mtls_workload_plus_caller_specific_context + issued_token_state: none + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [game-session-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/game-session-service"] + delegated_subject: typed_player_execution_context + target_binding: typed_caller_context_and_exact_resolved_target + tenant_billing_authority_generation_applies: false + membership_authority_generation_applies: false + required_live_checks: [account_state_bootstrap_eligible, pending_deletion_state, public_production_visibility, public_production_admission, runtime_entitlements, admission_pointer] + canonical_errors: + any_of: [ADMISSION_POINTER_UNAVAILABLE, CONNECT_SCOPE_INVALID, CONNECT_SCOPE_MISMATCH, REALM_UNAVAILABLE, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, AUTH_UNAVAILABLE] + end_user_token_required: false + issuance_contract: + result: opaque_short_lived_connect_scope_id + binds: [caller_account, resolved_target, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt] + silent_retarget: forbidden + implementation_status: + known_drift: + - direct_text_client_end_to_end_proof_unavailable - service: account-service route: JoinPublicProductionMembership scope: tenant classification: internal_workload - route_status: target_not_currently_routable auth_path: exact_mtls_workload issued_token_state: none accepted_token_profiles: [] @@ -1968,7 +1997,10 @@ routes: membership_creation: caller_bound_after_validation implementation_status: known_drift: - - explicit_JOIN_and_Join_And_Play_are_not_currently_implemented; connect_token_and_play_now_require_existing_membership_and_do_not_invoke_this_writer + - membership_authority_generation_snapshot_and_consumer_proof_remains_target_only + - join_unknown_database_outcome_recovery_and_reconciliation_remains_target_only + - join_audit_receipt_retention_and_safe_watermark_proof_remains_target_only + - postgresql_runtime_and_direct_text_end_to_end_proof_unavailable - service: account-service route: DELETE /tenants/{tenantId}/memberships/me scope: tenant @@ -3624,6 +3656,40 @@ routes: any_of: [IDEMPOTENCY_CONFLICT] roles: any_of: [tenantAdmin, platformAdmin] + - service: logging-admin-service + route: CreateLogEvent + transport: grpc + scope: account + classification: internal_workload + auth_path: exact_mtls_workload + issued_token_state: none + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [account-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/account-service"] + end_user_token_required: false + - service: logging-admin-service + route: ReadLogEventReceipt + transport: grpc + scope: account + classification: internal_workload + auth_path: exact_mtls_workload + issued_token_state: none + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [account-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/account-service"] + end_user_token_required: false - service: game-session-service route: ToggleFeatureFlag transport: grpc diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 408cd4aafc..b70063cb42 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. Explicit `JOIN`/`Join & Play`, the membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Game Session text dispatch for JOIN and direct text-client end-to-end proof remain unavailable in this stage. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. @@ -29,16 +29,16 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account identity and tenant-scoped profile CRUD and exports are live, but registration still requires a caller-selected tenant and creates an admission-enabled membership and profile before explicit JOIN; the ADR 0042 global-only registration target is not proved. The current profile GET/PUT routes now enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. Lifecycle-state retention is tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. Current non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; on fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved, and issuance does not validate the applicable non-public grant. Issuance requires existing membership and never creates it, but the current public registration writer creates an admitting membership from a caller-selected tenant before explicit JOIN. That row lets later issuance bypass `allowPublicJoin=false` on the existing-membership path; global-only registration and the separate explicit JOIN writer remain required. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current registration creates global Account identity plus platform audit outbox evidence only; it does not create a tenant membership or profile, and legacy tenant input is not authority. Source covers the zero-membership/profile registration boundary, but PostgreSQL runtime proof and deployment retained-row disposition/readback remain open. The current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. Lifecycle-state retention is tracked under AA-1.3. | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, rechecks fresh entitlement and public-join policy at the commit gate, binds a v1 digest to the verified caller/scope and policy evidence, and writes the membership, stored operation outcome, and tenant audit outbox evidence in one Account transaction. Global-only registration no longer creates an admitting membership. The durable recovery/reconciliation seam for JOIN left `PENDING` after an unknown database commit outcome remains unresolved under the Overseer decision and ADR 0025; do not mark ADR 0025 complete. PostgreSQL runtime proof and direct text-client end-to-end proof remain unclaimed. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. Generic payment scaffolds still retain provider-mutating drift. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Text `PLAY` validates current Account membership, entitlement, and applicable realm-grant evidence; connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. On missing or non-admitting public membership, current `PLAY` can return `JOIN_REQUIRED` before reading entitlement availability or `allowPublicJoin`; the 1B consumer must establish fresh entitlement and public-target policy before that outcome, and unavailable or denied authority must not be classified as a join opportunity. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Text `PLAY` validates current Account membership, entitlement, and applicable realm-grant evidence; connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. On missing or non-admitting public membership, current `PLAY` can return `JOIN_REQUIRED` before reading entitlement availability or `allowPublicJoin`; the 1B consumer must establish fresh entitlement and public-target policy before that outcome, and unavailable or denied authority must not be classified as a join opportunity. Account's explicit public-production JOIN writer exists locally, but Game Session text dispatch and direct text-client end-to-end proof remain unavailable in this stage; first-party `Join & Play`, membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. The JOIN `PENDING`/unknown-database-outcome recovery seam remains open under ADR 0025. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | -The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account's player-bootstrap character discovery requires an existing caller-bound membership that permits gameplay admission. `JOIN_REQUIRED` applies only to an otherwise eligible public-production realm after entitlement and public-join policy checks; membership loss on private/playtest targets remains a non-public denial. Neither outcome requires an Entity read; pre-membership world and realm discovery remains available. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Explicit JOIN, lifecycle-aware inactive membership, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. +The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary. Account's player-bootstrap character discovery requires an existing caller-bound membership that permits gameplay admission and returns `JOIN_REQUIRED` without an Entity read otherwise; pre-membership world and realm discovery remains available. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Explicit public-production JOIN is now implemented locally through Account, while the durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under ADR 0025; PostgreSQL runtime and direct text-client end-to-end proof are not claimed. Lifecycle-aware runtime membership reads, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. Reconnect prompt-setting precedence remains owned by [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#prompt-behavior); this tracker records only the current reconnect capability and proof gaps. @@ -61,7 +61,7 @@ Platform accounts are global identities. Tenant membership, tenant-scoped author `POST /auth/player-bootstrap` now authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; `PLAY` evaluates the same authorities independently. Current connect-token issuance revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target but does not revalidate the applicable non-public grant. Target issuance grant validation and its focused proof remain gaps. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). -The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Explicit `JOIN`/`Join & Play` and the membership-authority-generation reread at connect-token issuance remain unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). +The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. The canonical `JoinPublicProductionMembership` Account writer is implemented locally, including a policy-bound v1 digest and membership/audit outbox transaction. Game Session text `JOIN` dispatch and first-party `Join & Play` remain unavailable in this stage. The writer's `PENDING`/unknown-database-outcome recovery seam and direct text-client proof remain open, so ADR 0025 is not complete. The membership-authority-generation reread at connect-token issuance remains unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. @@ -173,7 +173,7 @@ No competing target state is currently recorded. Future design discussion is req | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | -| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and target explicit public-production join/leave | Account REST/gRPC APIs; bootstrap/connect-token APIs; runtime membership/grant/entitlement reads; target join/leave APIs remain unimplemented | +| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN | Account REST/gRPC APIs; bootstrap/connect-token APIs; runtime membership/grant/entitlement reads; local JOIN RPC is implemented, while leave and the public bootstrap join REST facade remain target-only | | Common Security | **Current:** JWT/signed-token claims, current-account and tenant access, gameplay-elevated roles, legacy session attestation, current service-identity handling, and downstream caller authorization. **Target:** certificate-derived mTLS workload identity and method allowlists authorize services, while typed `PlayerExecutionContext` carries player scope | `JwtClaims`, `SessionClaims`, session-context helpers, target `PlayerExecutionContext`, certificate-derived mTLS caller identity, caller allowlists, and shared authorization checks; legacy attestation/service-identity code is implementation debt, not target player authority | | TCP Proxy | Telnet transport, hidden bootstrap envelope, bounded connection-local ordered input buffering during edge rebind, disconnect notification, and Telnet close taxonomy | Telnet bridge; `TelnetRoutingBundle`; Game Session `NotifyDisconnect` | | Spring Cloud Gateway | Trusted proxy/first-party handshake validation, signed connect context, stable edge socket/session id, upstream gameplay bridge and rebind | `/ws/game/**`; `TrustedTcpProxyIdentity`; connect-token and first-party context headers | diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index be4d6e9e94..a898f3033b 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -3961,6 +3961,16 @@ def service_consumer_documents(): }, {"name": "FIREMUD_GRPC_CA_CERT_PATH", "value": "/tls/ca.crt"}, ] + if service == "logging-admin-service": + container["env"].insert( + 0, + { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": { + "fieldRef": {"fieldPath": "metadata.namespace"} + }, + }, + ) if service == "spring-cloud-gateway": container["env"] = validator._expected_gateway_container_env("pr-42") container["envFrom"] = copy.deepcopy(validator.EXPECTED_GATEWAY_ENV_FROM) @@ -4724,7 +4734,20 @@ for service in shared_services: assert_paths_and_mount( container, service, "/tls/client.crt", "/tls/client.key", "/tls/ca.crt" ) - if "FIREMUD_GRPC_WORKLOAD_NAMESPACE" in env_map(container, service): + namespace_identity = env_map(container, service).get( + "FIREMUD_GRPC_WORKLOAD_NAMESPACE" + ) + if service == "logging-admin-service": + if namespace_identity != { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, + }: + fail( + "Deployment/logging-admin-service must derive " + "FIREMUD_GRPC_WORKLOAD_NAMESPACE from metadata.namespace, " + f"found {namespace_identity!r}" + ) + elif namespace_identity is not None: fail( f"Deployment/{service} shared transport unexpectedly declares " "FIREMUD_GRPC_WORKLOAD_NAMESPACE" @@ -4765,6 +4788,40 @@ for service in ( fail(f"Kustomize base Deployment/{service} must use non-rolling Recreate strategy") for service in publication_services: assert_distinct_workload_service(service, base_deployments, "Kustomize base") + +base_logging_admin = deployment_for("logging-admin-service", base_deployments) +base_logging_admin_container, base_logging_admin_pod = workload_container( + base_logging_admin, "logging-admin-service" +) +assert_paths_and_mount( + base_logging_admin_container, + "logging-admin-service", + "/tls/client.crt", + "/tls/client.key", + "/tls/ca.crt", +) +base_logging_admin_namespace = env_map( + base_logging_admin_container, "logging-admin-service" +).get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") +if base_logging_admin_namespace != { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, +}: + fail( + "Kustomize base Deployment/logging-admin-service must derive " + "FIREMUD_GRPC_WORKLOAD_NAMESPACE from metadata.namespace, " + f"found {base_logging_admin_namespace!r}" + ) +base_logging_admin_grpc_volume = named_entry( + base_logging_admin_pod.get("volumes"), + "grpc-tls", + "Kustomize base Deployment/logging-admin-service volumes", +) +if base_logging_admin_grpc_volume.get("secret", {}).get("secretName") != "firemud-grpc-tls": + fail( + "Kustomize base Deployment/logging-admin-service shared grpc-tls must use " + "firemud-grpc-tls" + ) PY python3 - "$resolved_values" "$namespace_gate_values" <<'PY' diff --git a/k8s/base/logging-admin-service.yaml b/k8s/base/logging-admin-service.yaml index 1bd8c367a1..324c6fb73a 100644 --- a/k8s/base/logging-admin-service.yaml +++ b/k8s/base/logging-admin-service.yaml @@ -24,6 +24,10 @@ spec: env: - name: SPRING_PROFILES_ACTIVE value: "prod" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace - name: FIREMUD_GRPC_CERT_CHAIN_PATH value: /tls/client.crt - name: FIREMUD_GRPC_PRIVATE_KEY_PATH diff --git a/k8s/helm/firemud/templates/apps.yaml b/k8s/helm/firemud/templates/apps.yaml index cbefb5c198..210a8f9dec 100644 --- a/k8s/helm/firemud/templates/apps.yaml +++ b/k8s/helm/firemud/templates/apps.yaml @@ -188,6 +188,12 @@ spec: - name: SERVICE_SCHEMA value: {{ default (replace "-" "_" $service.name) $service.schema | quote }} {{- if $service.mountGrpcTls }} + {{- if eq $service.name "logging-admin-service" }} + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + {{- end }} {{- if $usesGrpcWorkloadIdentity }} - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE valueFrom: diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index c16a7e416b..3ade2a26c0 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -3,6 +3,7 @@ syntax = "proto3"; package account.v1; import "shared/v1/errors.proto"; +import "shared/v1/player_execution_context.proto"; option java_package = "net.firedevops.firemud.account.v1"; option java_multiple_files = true; @@ -16,6 +17,8 @@ service AccountService { rpc GetTenantMembershipForRuntime(GetTenantMembershipForRuntimeRequest) returns (GetTenantMembershipForRuntimeResponse); rpc GetRealmAccessGrantForRuntime(GetRealmAccessGrantForRuntimeRequest) returns (GetRealmAccessGrantForRuntimeResponse); rpc GetTenantEntitlementsForRuntime(GetTenantEntitlementsForRuntimeRequest) returns (GetTenantEntitlementsForRuntimeResponse); + rpc IssueDirectTextConnectScope(IssueDirectTextConnectScopeRequest) returns (IssueDirectTextConnectScopeResponse); + rpc JoinPublicProductionMembership(JoinPublicProductionMembershipRequest) returns (JoinPublicProductionMembershipResponse); rpc GetProfile(GetProfileRequest) returns (GetProfileResponse); rpc ListPresenceVisibilityPolicies(ListPresenceVisibilityPoliciesRequest) returns (ListPresenceVisibilityPoliciesResponse); @@ -30,6 +33,45 @@ service AccountService { rpc VerifyEmail(VerifyEmailRequest) returns (VerifyEmailResponse); } +// Game Session supplies its authenticated, transport-local player context and +// exact catalog/pointer evidence. Account re-resolves the target before issuance. +message IssueDirectTextConnectScopeRequest { + shared.v1.PlayerExecutionContext player_context = 1; + string tenant_id = 2; + string world_slug = 3; + string realm_slug = 4; + string realm_id = 5; + string playable_state_namespace_id = 6; + string playable_state_scope = 7; + string game_instance_id = 8; + int64 catalog_revision = 9; + int64 pointer_version = 10; +} + +message IssueDirectTextConnectScopeResponse { + string connect_scope_id = 1; + string connect_scope_expires_at = 2; + shared.v1.ErrorDetail error = 3; +} + +message JoinPublicProductionMembershipRequest { + shared.v1.PlayerExecutionContext player_context = 1; + string connect_scope_id = 2; + string request_id = 3; +} + +message JoinPublicProductionMembershipResponse { + bool success = 1; + string outcome_code = 2; + string account_id = 3; + string tenant_id = 4; + string membership_id = 5; + int64 membership_version = 6; + int64 membership_authority_generation = 7; + bool replayed = 8; + shared.v1.ErrorDetail error = 9; +} + // Empty request used to verify that the service is reachable. message PingRequest {} @@ -43,8 +85,8 @@ message PingResponse { // Parameters required to register a new account. message CreateAccountRequest { - // Tenant that owns the new account. - string tenant_id = 1; + reserved 1; + reserved "tenant_id"; // Desired username for login and display. string username = 2; // Email address used for notifications and password recovery. @@ -108,6 +150,8 @@ message GetTenantMembershipForRuntimeResponse { string evaluated_at = 5; shared.v1.ErrorDetail error = 6; bool membership_exists = 7; + string membership_lifecycle_state = 8; + uint64 membership_authority_generation = 9; } message GetRealmAccessGrantForRuntimeRequest { diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index 4261870f11..f3e63f02bc 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -206,6 +206,9 @@ message GameplayRealm { string state_scope = 9; string character_creation_policy = 10; bool public_production_realm = 11; + int64 catalog_revision = 12; + string realm_id = 13; + string playable_state_namespace_id = 14; } message ListGameplayRealmsResponse { @@ -232,6 +235,9 @@ message GameplayAdmissionPointer { string state_scope = 10; string character_creation_policy = 11; bool public_production_realm = 12; + int64 catalog_revision = 13; + string realm_id = 14; + string playable_state_namespace_id = 15; } message GetAdmissionPointerResponse { diff --git a/protos/logging-admin/v1/logging_admin_service.proto b/protos/logging-admin/v1/logging_admin_service.proto index 2902aad35b..bb9c6e2c3a 100644 --- a/protos/logging-admin/v1/logging_admin_service.proto +++ b/protos/logging-admin/v1/logging_admin_service.proto @@ -3,6 +3,7 @@ syntax = "proto3"; package logging_admin.v1; import "shared/v1/errors.proto"; +import "google/protobuf/timestamp.proto"; option java_package = "net.firedevops.firemud.loggingadmin.v1"; option java_multiple_files = true; @@ -11,6 +12,7 @@ service LoggingAdminService { rpc Ping(PingRequest) returns (PingResponse); rpc QueryLogs(QueryLogsRequest) returns (QueryLogsResponse); rpc CreateLogEvent(CreateLogEventRequest) returns (CreateLogEventResponse); + rpc ReadLogEventReceipt(ReadLogEventReceiptRequest) returns (ReadLogEventReceiptResponse); rpc ApplyModerationAction(ApplyModerationActionRequest) returns (ApplyModerationActionResponse); rpc EvaluateModerationPolicy(EvaluateModerationPolicyRequest) returns (EvaluateModerationPolicyResponse); @@ -35,15 +37,76 @@ message QueryLogsResponse { } message CreateLogEventRequest { - string tenant_id = 1; - string account_id = 2; - string type = 3; - string message = 4; + AccountAuditScope scope = 1; + string tenant_id = 2; + string audit_event_id = 3; + string producer_service = 4; + string event_type = 5; + google.protobuf.Timestamp occurred_at = 6; + int32 schema_version = 7; + bytes payload = 8; + int32 payload_digest_version = 9; + string payload_digest = 10; } message CreateLogEventResponse { - string log_event_id = 1; - shared.v1.ErrorDetail error = 2; + AccountAuditScope scope = 1; + string tenant_id = 2; + string audit_event_id = 3; + string receipt_id = 4; + string log_event_id = 5; + int32 schema_version = 6; + int32 payload_digest_version = 7; + string payload_digest = 8; + AccountAuditReceiptStatus status = 9; + AccountAuditReceiptOutcome outcome = 10; +} + +message ReadLogEventReceiptRequest { + AccountAuditScope scope = 1; + string tenant_id = 2; + string audit_event_id = 3; + string producer_service = 4; + string event_type = 5; + google.protobuf.Timestamp occurred_at = 6; + int32 schema_version = 7; + bytes payload = 8; + int32 payload_digest_version = 9; + string payload_digest = 10; +} + +message ReadLogEventReceiptResponse { + AccountAuditScope scope = 1; + string tenant_id = 2; + string audit_event_id = 3; + string receipt_id = 4; + string log_event_id = 5; + int32 schema_version = 6; + int32 payload_digest_version = 7; + string payload_digest = 8; + AccountAuditReceiptStatus status = 9; + AccountAuditReceiptOutcome outcome = 10; +} + +enum AccountAuditScope { + ACCOUNT_AUDIT_SCOPE_UNSPECIFIED = 0; + ACCOUNT_AUDIT_SCOPE_PLATFORM = 1; + ACCOUNT_AUDIT_SCOPE_TENANT = 2; +} + +enum AccountAuditReceiptStatus { + ACCOUNT_AUDIT_RECEIPT_STATUS_UNSPECIFIED = 0; + ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED = 1; + ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED = 2; + ACCOUNT_AUDIT_RECEIPT_STATUS_CONFLICT = 3; +} + +enum AccountAuditReceiptOutcome { + ACCOUNT_AUDIT_RECEIPT_OUTCOME_UNSPECIFIED = 0; + ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED = 1; + ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE = 2; + ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE = 3; + ACCOUNT_AUDIT_RECEIPT_OUTCOME_IDEMPOTENCY_CONFLICT = 4; } message ApplyModerationActionRequest { diff --git a/protos/shared/v1/player_execution_context.proto b/protos/shared/v1/player_execution_context.proto new file mode 100644 index 0000000000..7dfbf61210 --- /dev/null +++ b/protos/shared/v1/player_execution_context.proto @@ -0,0 +1,20 @@ +syntax = "proto3"; + +package shared.v1; + +option java_package = "net.firedevops.firemud.shared.v1"; +option java_multiple_files = true; + +// Unsigned player scope carried only by an authenticated, allowlisted gameplay workload. +// Receivers validate the required subset and equality with their own authoritative target. +message PlayerExecutionContext { + string account_id = 1; + string tenant_id = 2; + string playable_state_namespace_id = 3; + string game_instance_id = 4; + string character_id = 5; + string session_id = 6; + string realm_id = 7; + string request_id = 8; + string playable_state_scope = 9; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java index 44e168eac5..da1fb6e9eb 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java @@ -1,14 +1,26 @@ package net.firedevops.firemud.accountservice.client; +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; import jakarta.annotation.PostConstruct; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditScope; import net.firedevops.firemud.loggingadmin.v1.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.v1.CreateLogEventResponse; import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; import org.springframework.stereotype.Component; @@ -47,27 +59,74 @@ protected LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub buildStub( LoggingAdminServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - /** Log that a new account was created. */ - public void logAccountCreation(long tenantId, long accountId) { - CreateLogEventRequest request = + /** Send one unchanged owner-local outbox envelope and verify the exact receiver receipt. */ + public AuditDeliveryResult deliver(AccountAuditEnvelope envelope) { + CreateLogEventRequest.Builder builder = CreateLogEventRequest.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setType("ACCOUNT_CREATED") - .setMessage("account created") - .build(); - stub().createLogEvent(request); + .setScope( + "platform".equals(envelope.scope()) + ? AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM + : AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setAuditEventId(envelope.auditEventId().toString()) + .setProducerService(envelope.producerService()) + .setEventType(envelope.eventType()) + .setOccurredAt( + Timestamp.newBuilder() + .setSeconds(envelope.occurredAt().getEpochSecond()) + .setNanos(envelope.occurredAt().getNano()) + .build()) + .setSchemaVersion(envelope.schemaVersion()) + .setPayload(ByteString.copyFrom(envelope.payload(), StandardCharsets.UTF_8)) + .setPayloadDigestVersion(envelope.payloadDigestVersion()) + .setPayloadDigest(envelope.payloadDigest()); + if (envelope.tenantId() != null) { + builder.setTenantId(envelope.tenantId().toString()); + } + CreateLogEventResponse response = + stub().withDeadlineAfter(5, TimeUnit.SECONDS).createLogEvent(builder.build()); + if (!response.getAuditEventId().equals(envelope.auditEventId().toString()) + || !response.getPayloadDigest().equals(envelope.payloadDigest()) + || response.getSchemaVersion() != envelope.schemaVersion() + || response.getPayloadDigestVersion() != envelope.payloadDigestVersion() + || response.getScope() != builder.getScope() + || !response.getTenantId().equals(builder.getTenantId())) { + throw new IllegalStateException( + "Account audit receiver returned mismatched receipt evidence"); + } + boolean minimized = + response.getStatus() == AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED + && response.getOutcome() + == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE; + boolean committed = + response.getStatus() == AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED + && (response.getOutcome() + == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED + || response.getOutcome() + == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE); + if ((!committed && !minimized) + || response.getReceiptId().isBlank() + || response.getLogEventId().isBlank()) { + throw new IllegalStateException("Account audit receiver did not prove a terminal receipt"); + } + return new AuditDeliveryResult(response.getReceiptId(), response.getLogEventId(), minimized); } - /** Log that a payment transaction occurred. */ + /** Existing deferred-commerce path remains best effort until its own outbox convergence. */ public void logPayment(long tenantId, long accountId, long transactionId) { - CreateLogEventRequest request = - CreateLogEventRequest.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setType("PAYMENT_TXN") - .setMessage("txId=" + transactionId) - .build(); - stub().createLogEvent(request); + String payload = "{\"accountId\":" + accountId + ",\"transactionId\":" + transactionId + "}"; + deliver( + new AccountAuditEnvelope( + UUID.randomUUID(), + "tenant", + tenantId, + "account-service", + "PAYMENT_TXN", + Instant.now(), + 1, + 1, + AccountAuditDigest.ofPayload(payload), + payload)); } + + public record AuditDeliveryResult(String receiptId, String logEventId, boolean minimized) {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java index afc1eec45a..e51178229b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java @@ -12,6 +12,8 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenResponse; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.EmailVerificationRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.LoginRequest; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapRequest; @@ -19,6 +21,7 @@ import net.firedevops.firemud.accountservice.dto.UsernameRecoveryRequest; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.ApiResponse; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseCookie; @@ -89,6 +92,19 @@ public ResponseEntity>> listBootstrapCha bootstrapToken, worldSlug, realmSlug, connectScopeId))); } + @PostMapping("/bootstrap/join") + public ResponseEntity> joinPublicProduction( + @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization, + @Valid @RequestBody JoinPublicProductionRequest request) { + JoinPublicProductionResult result = + accountService.joinPublicProduction(extractBearerToken(authorization), request); + if (!result.success()) { + throw new AuthenticationException( + result.outcomeCode(), "JOIN was denied for the selected realm"); + } + return ResponseEntity.ok(ApiResponse.success(result)); + } + @PostMapping("/connect-token") public ResponseEntity> connectToken( @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java index a3499696e7..a520d8ce5e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java @@ -60,6 +60,10 @@ public void run(ApplicationArguments args) { membership.setAccount(account); membership.setTenantId(DEMO_TENANT_ID); membership.setGameplayAdmissionAllowed(true); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(1); + membership.setMembershipAuthorityGeneration(1); + membership.setAuthorityProvenance("SEEDED_DEMO"); accountTenantMembershipRepository.save(membership); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java new file mode 100644 index 0000000000..ff5e2700d3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java @@ -0,0 +1,23 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** Receiver-version-1 digest over exact persisted UTF-8 payload bytes. */ +public final class AccountAuditDigest { + private AccountAuditDigest() {} + + public static String ofPayload(String payload) { + try { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(payload.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java new file mode 100644 index 0000000000..a99ebc70cb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java @@ -0,0 +1,17 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.time.Instant; +import java.util.UUID; + +/** The immutable Account-owned delivery envelope; the SQL outbox is its authority. */ +public record AccountAuditEnvelope( + UUID auditEventId, + String scope, + Long tenantId, + String producerService, + String eventType, + Instant occurredAt, + int schemaVersion, + int payloadDigestVersion, + String payloadDigest, + String payload) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java index d025e43865..ed43a78720 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java @@ -8,5 +8,5 @@ public record AccountDto( Long id, @NotNull @Size(max = 50) String username, @NotNull @Email @Size(max = 100) String email, - @NotNull @Size(max = 20) String role, + @Size(max = 20) String role, boolean emailVerified) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java new file mode 100644 index 0000000000..bf2147fa79 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java @@ -0,0 +1,107 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** Canonical exact-byte digests for retained public-production scope and JOIN attempts. */ +public final class AccountJoinDigest { + private AccountJoinDigest() {} + + public static String scope(VerifiedJoinScope scope) { + return hash( + "scopeDigestVersion=v1\n" + + field("accountId", scope.accountId()) + + "targetClass=PUBLIC_PRODUCTION\n" + + field("connectScopeId", scope.connectScopeId()) + + field("tenantId", scope.tenantId()) + + field("realmId", scope.realmId().toString()) + + field("worldSlug", scope.worldSlug()) + + field("realmSlug", scope.realmSlug()) + + field("playableStateNamespaceId", scope.playableStateNamespaceId()) + + field("playableStateScope", scope.playableStateScope()) + + field("gameInstanceId", scope.gameInstanceId()) + + field("catalogRevision", scope.catalogRevision()) + + field("pointerVersion", scope.pointerVersion()) + + field("evaluatedAt", scope.evaluatedAt()) + + field("connectScopeExpiresAt", scope.connectScopeExpiresAt())); + } + + public static String request( + VerifiedJoinScope scope, + String callerBinding, + Boolean allowPublicJoin, + Long entitlementVersion) { + if (allowPublicJoin == null || entitlementVersion == null || entitlementVersion <= 0L) { + throw new IllegalArgumentException("A JOIN policy digest requires exact available evidence"); + } + return hash( + "joinDigestVersion=v1\n" + + "operationKind=JOIN\n" + + field("accountId", scope.accountId()) + + field("callerBinding", callerBinding) + + field("tenantId", scope.tenantId()) + + field("worldSlug", scope.worldSlug()) + + field("realmSlug", scope.realmSlug()) + + field("playableStateNamespaceId", scope.playableStateNamespaceId()) + + field("playableStateScope", scope.playableStateScope()) + + field("gameInstanceId", scope.gameInstanceId()) + + field("connectScopeId", scope.connectScopeId()) + + field("catalogRevision", scope.catalogRevision()) + + field("pointerVersion", scope.pointerVersion()) + + field("entitlementAuthorityAvailability", "AVAILABLE") + + field("allowPublicJoin", allowPublicJoin) + + field("entitlementVersion", entitlementVersion)); + } + + public static String intent(String requestId, VerifiedJoinScope scope, String callerBinding) { + return hash( + "joinIntentDigestVersion=v1\n" + + "operationKind=JOIN\n" + + field("requestId", requestId) + + field("accountId", scope.accountId()) + + field("callerBinding", callerBinding) + + field("connectScopeId", scope.connectScopeId()) + + field("scopeDigest", scope.snapshotDigest()) + + field("tenantId", scope.tenantId()) + + field("worldSlug", scope.worldSlug()) + + field("realmSlug", scope.realmSlug()) + + field("realmId", scope.realmId().toString()) + + field("playableStateNamespaceId", scope.playableStateNamespaceId()) + + field("playableStateScope", scope.playableStateScope()) + + field("gameInstanceId", scope.gameInstanceId()) + + field("catalogRevision", scope.catalogRevision()) + + field("pointerVersion", scope.pointerVersion())); + } + + public static String tokenHash(String connectScopeId) { + return hash(connectScopeId); + } + + private static String field(String name, Object value) { + if (value == null) { + throw new IllegalArgumentException(name + " is required"); + } + String wire = value.toString(); + if (wire.isEmpty() + || wire.indexOf('=') >= 0 + || wire.indexOf('\n') >= 0 + || wire.indexOf('\r') >= 0) { + throw new IllegalArgumentException(name + " has an invalid canonical wire value"); + } + return name + "=" + wire + "\n"; + } + + private static String hash(String preimage) { + try { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(preimage.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java index 796fe0ad76..51b97cb66e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java @@ -4,6 +4,7 @@ public record BootstrapRealmDto( String worldSlug, String realmSlug, + String realmId, String displayName, long tenantId, long gameInstanceId, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CreateAccountRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CreateAccountRequest.java index 37bdfe1ea7..9cf32940dd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CreateAccountRequest.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CreateAccountRequest.java @@ -2,11 +2,9 @@ import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Positive; import jakarta.validation.constraints.Size; public record CreateAccountRequest( - @NotNull @Positive Long tenantId, @NotNull @Size(max = 50) String username, @NotNull @Email @Size(max = 100) String email, @NotNull @Size(min = 6, max = 100) String password) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java new file mode 100644 index 0000000000..2638dc9cfb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextCallerContext.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.UUID; + +/** Parsed scope data from a verified Game Session mTLS call, never an independent capability. */ +public record DirectTextCallerContext( + long accountId, + long tenantId, + UUID realmId, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + String sessionId, + String requestId) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java new file mode 100644 index 0000000000..0f1a2a90ca --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinScope.java @@ -0,0 +1,6 @@ +package net.firedevops.firemud.accountservice.dto; + +/** + * Opaque, short-lived Account-issued target scope retained only by Game Session transport state. + */ +public record DirectTextJoinScope(String connectScopeId, String connectScopeExpiresAt) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java new file mode 100644 index 0000000000..b4273bf5b5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DirectTextJoinTarget.java @@ -0,0 +1,17 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.UUID; + +/** + * Game Session's complete selected-target evidence, re-resolved by Account before scope issuance. + */ +public record DirectTextJoinTarget( + long tenantId, + UUID realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + long catalogRevision, + long pointerVersion) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionRequest.java new file mode 100644 index 0000000000..f184617738 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionRequest.java @@ -0,0 +1,9 @@ +package net.firedevops.firemud.accountservice.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +/** Only the Account-issued target scope and caller-stable attempt ID cross the public API. */ +public record JoinPublicProductionRequest( + @NotBlank @Size(max = 2048) String connectScopeId, + @NotBlank @Size(max = 128) String requestId) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java new file mode 100644 index 0000000000..a5696c235d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/JoinPublicProductionResult.java @@ -0,0 +1,12 @@ +package net.firedevops.firemud.accountservice.dto; + +/** Durable explicit-JOIN outcome; a failure is returned so its receipt can commit first. */ +public record JoinPublicProductionResult( + boolean success, + String outcomeCode, + long accountId, + long tenantId, + long membershipId, + long membershipVersion, + long membershipAuthorityGeneration, + boolean replayed) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipDto.java index 50901a2b28..41ed6a0fd3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipDto.java @@ -6,4 +6,6 @@ public record RuntimeMembershipDto( boolean membershipExists, boolean gameplayAdmissionAllowed, long membershipVersion, + String membershipLifecycleState, + long membershipAuthorityGeneration, String evaluatedAt) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java new file mode 100644 index 0000000000..3d96e8c217 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/VerifiedJoinScope.java @@ -0,0 +1,20 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.UUID; + +/** Immutable Account-owned target snapshot retained for an explicit public-production JOIN. */ +public record VerifiedJoinScope( + String connectScopeId, + long accountId, + long tenantId, + UUID realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + long catalogRevision, + long pointerVersion, + String evaluatedAt, + String connectScopeExpiresAt, + String snapshotDigest) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java index 95038fd526..2fb0e62afe 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java @@ -8,7 +8,7 @@ public class Account { private String username; private String email; private String passwordHash; - private String role = "player"; + private String role; private boolean emailVerified = false; private String loginAuthModes = AccountLoginAuthModes.DEFAULT_SERIALIZED; private AccountLifecycleState lifecycleState = AccountLifecycleState.ACTIVE; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java index 2e1f4a1a38..737251b618 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java @@ -16,6 +16,10 @@ public class AccountTenantMembership { private Long tenantId; private boolean gameplayAdmissionAllowed = true; + private String lifecycleState; + private long membershipVersion; + private long membershipAuthorityGeneration; + private String authorityProvenance; @SuppressFBWarnings( value = "EI_EXPOSE_REP", diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java index db6345c66a..2d4daa7a85 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java @@ -27,4 +27,5 @@ public class Subscription { private LocalDateTime startedAt; private LocalDateTime endedAt; private Long tenantId; + private long entitlementVersion = 1L; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java new file mode 100644 index 0000000000..2829a20873 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java @@ -0,0 +1,105 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.jooq.tables.AccountAuditOutbox.ACCOUNT_AUDIT_OUTBOX; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.jooq.tables.records.AccountAuditOutboxRecord; +import org.jooq.DSLContext; +import org.springframework.stereotype.Repository; + +/** Owner-local audit identity, immutable envelope, and durable delivery state. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountAuditOutboxRepository { + private final DSLContext dsl; + + public AccountAuditOutboxRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public AccountAuditEnvelope append( + UUID auditEventId, String scope, Long tenantId, String eventType, String payload) { + if (!("platform".equals(scope) && tenantId == null) + && !("tenant".equals(scope) && tenantId != null && tenantId > 0)) { + throw new IllegalArgumentException("Audit scope and tenant ID must match"); + } + Instant occurredAt = Instant.now(); + String digest = AccountAuditDigest.ofPayload(payload); + AccountAuditOutboxRecord row = dsl.newRecord(ACCOUNT_AUDIT_OUTBOX); + row.setAuditEventId(auditEventId); + row.setScope(scope); + row.setTenantId(tenantId); + row.setProducerService("account-service"); + row.setEventType(eventType); + row.setOccurredAt(toLocalDateTime(occurredAt)); + row.setSchemaVersion(1); + row.setPayloadDigestVersion(1); + row.setPayloadDigest(digest); + row.setPayload(payload); + row.setDeliveryStatus("PENDING"); + row.store(); + return toEnvelope(row); + } + + public List pending(int limit) { + return dsl.selectFrom(ACCOUNT_AUDIT_OUTBOX) + .where(ACCOUNT_AUDIT_OUTBOX.DELIVERY_STATUS.eq("PENDING")) + .orderBy(ACCOUNT_AUDIT_OUTBOX.CREATED_AT.asc(), ACCOUNT_AUDIT_OUTBOX.AUDIT_EVENT_ID.asc()) + .limit(limit) + .fetch(this::toEnvelope); + } + + public void markDelivered( + UUID auditEventId, String receiptId, String logEventId, boolean minimized) { + var update = + dsl.update(ACCOUNT_AUDIT_OUTBOX) + .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_RECEIPT_ID, receiptId) + .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_LOG_EVENT_ID, logEventId) + .set(ACCOUNT_AUDIT_OUTBOX.DELIVERY_STATUS, minimized ? "MINIMIZED" : "COMMITTED") + .set(ACCOUNT_AUDIT_OUTBOX.LAST_ATTEMPT_AT, toLocalDateTime(Instant.now())); + if (minimized) { + update.set(ACCOUNT_AUDIT_OUTBOX.PAYLOAD, (String) null); + } + int changed = + update + .where( + ACCOUNT_AUDIT_OUTBOX + .AUDIT_EVENT_ID + .eq(auditEventId) + .and(ACCOUNT_AUDIT_OUTBOX.DELIVERY_STATUS.eq("PENDING"))) + .execute(); + if (changed != 1) { + throw new IllegalStateException("Audit delivery state changed concurrently"); + } + } + + public void recordAttempt(UUID auditEventId) { + dsl.update(ACCOUNT_AUDIT_OUTBOX) + .set(ACCOUNT_AUDIT_OUTBOX.LAST_ATTEMPT_AT, toLocalDateTime(Instant.now())) + .where(ACCOUNT_AUDIT_OUTBOX.AUDIT_EVENT_ID.eq(auditEventId)) + .execute(); + } + + private AccountAuditEnvelope toEnvelope(AccountAuditOutboxRecord row) { + return new AccountAuditEnvelope( + row.getAuditEventId(), + row.getScope(), + row.getTenantId(), + row.getProducerService(), + row.getEventType(), + toInstant(row.getOccurredAt()), + row.getSchemaVersion(), + row.getPayloadDigestVersion(), + row.getPayloadDigest(), + row.getPayload()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java new file mode 100644 index 0000000000..79de6c47e6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java @@ -0,0 +1,82 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNT_CONNECT_SCOPE_RECORDS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +/** Durable, exact-byte scope evidence; its token hash is only a lookup key, never authority. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountConnectScopeRepository { + private final DSLContext dsl; + + public AccountConnectScopeRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public void insert(VerifiedJoinScope scope) { + dsl.insertInto(ACCOUNT_CONNECT_SCOPE_RECORDS) + .set( + ACCOUNT_CONNECT_SCOPE_RECORDS.SCOPE_TOKEN_HASH, + AccountJoinDigest.tokenHash(scope.connectScopeId())) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.ACCOUNT_ID, scope.accountId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.TARGET_CLASS, "PUBLIC_PRODUCTION") + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.TENANT_ID, scope.tenantId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_ID, scope.realmId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.WORLD_SLUG, scope.worldSlug()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_SLUG, scope.realmSlug()) + .set( + ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_NAMESPACE_ID, + scope.playableStateNamespaceId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_SCOPE, scope.playableStateScope()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.GAME_INSTANCE_ID, scope.gameInstanceId()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.CATALOG_REVISION, scope.catalogRevision()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.POINTER_VERSION, scope.pointerVersion()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.EVALUATED_AT, scope.evaluatedAt()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.CONNECT_SCOPE_EXPIRES_AT, scope.connectScopeExpiresAt()) + .set(ACCOUNT_CONNECT_SCOPE_RECORDS.SNAPSHOT_DIGEST, scope.snapshotDigest()) + .execute(); + } + + public Optional find(String connectScopeId) { + return dsl.selectFrom(ACCOUNT_CONNECT_SCOPE_RECORDS) + .where( + ACCOUNT_CONNECT_SCOPE_RECORDS.SCOPE_TOKEN_HASH.eq( + AccountJoinDigest.tokenHash(connectScopeId))) + .fetchOptional(record -> toScope(record, connectScopeId)); + } + + private VerifiedJoinScope toScope(Record record, String connectScopeId) { + if (!"PUBLIC_PRODUCTION".equals(record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.TARGET_CLASS))) { + throw new IllegalStateException("JOIN scope is not public production"); + } + VerifiedJoinScope scope = + new VerifiedJoinScope( + connectScopeId, + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.ACCOUNT_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.TENANT_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.WORLD_SLUG), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.REALM_SLUG), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_NAMESPACE_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.PLAYABLE_STATE_SCOPE), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.GAME_INSTANCE_ID), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.CATALOG_REVISION), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.POINTER_VERSION), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.EVALUATED_AT), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.CONNECT_SCOPE_EXPIRES_AT), + record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.SNAPSHOT_DIGEST)); + if (!scope.snapshotDigest().equals(AccountJoinDigest.scope(scope))) { + throw new IllegalStateException("JOIN scope digest mismatch"); + } + return scope; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java new file mode 100644 index 0000000000..a43a4b536b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -0,0 +1,257 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS; +import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNT_JOIN_OPERATIONS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; +import org.jooq.DSLContext; +import org.springframework.stereotype.Repository; + +/** Serializes explicit JOIN on the global account row and retains exact operation outcomes. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountJoinOperationRepository { + private final DSLContext dsl; + + public AccountJoinOperationRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public void lockAccount(long accountId) { + Long locked = + dsl.select(ACCOUNTS.ID) + .from(ACCOUNTS) + .where(ACCOUNTS.ID.eq(accountId)) + .forUpdate() + .fetchOne(ACCOUNTS.ID); + if (locked == null) { + throw new IllegalArgumentException("JOIN account does not exist"); + } + } + + public Optional find(String requestId) { + return dsl.selectFrom(ACCOUNT_JOIN_OPERATIONS) + .where(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID.eq(requestId)) + .fetchOptional(AccountJoinOperationRepository::toJoinOperation); + } + + public Optional findForUpdate(String requestId) { + return dsl.selectFrom(ACCOUNT_JOIN_OPERATIONS) + .where(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID.eq(requestId)) + .forUpdate() + .fetchOptional(AccountJoinOperationRepository::toJoinOperation); + } + + public boolean hasRetainedOperation(long accountId) { + return dsl.fetchExists( + ACCOUNT_JOIN_OPERATIONS, ACCOUNT_JOIN_OPERATIONS.ACCOUNT_ID.eq(accountId)); + } + + public boolean insertIntent( + String requestId, VerifiedJoinScope scope, String callerBinding, String intentDigest) { + int inserted = + dsl.insertInto(ACCOUNT_JOIN_OPERATIONS) + .set(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID, requestId) + .set(ACCOUNT_JOIN_OPERATIONS.ACCOUNT_ID, scope.accountId()) + .set(ACCOUNT_JOIN_OPERATIONS.TENANT_ID, scope.tenantId()) + .set(ACCOUNT_JOIN_OPERATIONS.VERIFIED_CALLER_BINDING, callerBinding) + .set( + ACCOUNT_JOIN_OPERATIONS.SCOPE_TOKEN_HASH, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( + scope.connectScopeId())) + .set(ACCOUNT_JOIN_OPERATIONS.CONNECT_SCOPE_DIGEST, scope.snapshotDigest()) + .set(ACCOUNT_JOIN_OPERATIONS.WORLD_SLUG, scope.worldSlug()) + .set(ACCOUNT_JOIN_OPERATIONS.REALM_SLUG, scope.realmSlug()) + .set(ACCOUNT_JOIN_OPERATIONS.REALM_ID, scope.realmId()) + .set( + ACCOUNT_JOIN_OPERATIONS.PLAYABLE_STATE_NAMESPACE_ID, + scope.playableStateNamespaceId()) + .set(ACCOUNT_JOIN_OPERATIONS.PLAYABLE_STATE_SCOPE, scope.playableStateScope()) + .set(ACCOUNT_JOIN_OPERATIONS.GAME_INSTANCE_ID, scope.gameInstanceId()) + .set(ACCOUNT_JOIN_OPERATIONS.CATALOG_REVISION, scope.catalogRevision()) + .set(ACCOUNT_JOIN_OPERATIONS.POINTER_VERSION, scope.pointerVersion()) + .set(ACCOUNT_JOIN_OPERATIONS.INTENT_DIGEST_VERSION, 1) + .set(ACCOUNT_JOIN_OPERATIONS.INTENT_DIGEST, intentDigest) + .set(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY, "NOT_EVALUATED") + .set(ACCOUNT_JOIN_OPERATIONS.CALLER_BOUND_AUTHORITY_INVALIDATED, false) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY, "NOT_EVALUATED") + .set(ACCOUNT_JOIN_OPERATIONS.STATUS, "PENDING") + .onConflict(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID) + .doNothing() + .execute(); + return inserted == 1; + } + + public void bindPolicyEvidence( + String requestId, String requestDigest, Long entitlementVersion, Boolean allowPublicJoin) { + int updated = + dsl.update(ACCOUNT_JOIN_OPERATIONS) + .set(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY, "AVAILABLE") + .set(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_VERSION, entitlementVersion) + .set(ACCOUNT_JOIN_OPERATIONS.ALLOW_PUBLIC_JOIN, allowPublicJoin) + .set(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST_VERSION, 1) + .set(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST, requestDigest) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY, "AVAILABLE") + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_FAILURE_CODE, (String) null) + .set(ACCOUNT_JOIN_OPERATIONS.UPDATED_AT, org.jooq.impl.DSL.currentLocalDateTime()) + .where( + ACCOUNT_JOIN_OPERATIONS + .REQUEST_ID + .eq(requestId) + .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING")) + .and(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST.isNull())) + .execute(); + if (updated != 1) { + throw new IllegalStateException("JOIN operation changed before policy binding"); + } + } + + public void recordAttemptFailure( + String requestId, String authorityAvailability, String failureCode) { + if (failureCode == null || failureCode.isBlank()) { + throw new IllegalArgumentException("JOIN attempt failure code is required"); + } + if (!"AVAILABLE".equals(authorityAvailability) + && !"UNAVAILABLE".equals(authorityAvailability) + && !"NOT_EVALUATED".equals(authorityAvailability)) { + throw new IllegalArgumentException("JOIN attempt authority availability is invalid"); + } + int updated = + dsl.update(ACCOUNT_JOIN_OPERATIONS) + .set( + ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY, + org.jooq + .impl + .DSL + .when(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST.isNull(), authorityAvailability) + .otherwise(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY)) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY, authorityAvailability) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_FAILURE_CODE, failureCode) + .set(ACCOUNT_JOIN_OPERATIONS.UPDATED_AT, org.jooq.impl.DSL.currentLocalDateTime()) + .where( + ACCOUNT_JOIN_OPERATIONS + .REQUEST_ID + .eq(requestId) + .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING"))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("JOIN operation changed while recording attempt failure"); + } + } + + public void finish( + String requestId, + String status, + String outcome, + Long membershipId, + Long membershipVersion, + Long membershipAuthorityGeneration) { + if (!"COMMITTED".equals(status) && !"FAILED".equals(status)) { + throw new IllegalArgumentException("JOIN terminal status is invalid"); + } + if (outcome == null || outcome.isBlank()) { + throw new IllegalArgumentException("JOIN terminal outcome is required"); + } + int updated = + dsl.update(ACCOUNT_JOIN_OPERATIONS) + .set(ACCOUNT_JOIN_OPERATIONS.STATUS, status) + .set(ACCOUNT_JOIN_OPERATIONS.OUTCOME, outcome) + .set( + ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY, + org.jooq + .impl + .DSL + .when(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST.isNull(), "NOT_EVALUATED") + .otherwise(ACCOUNT_JOIN_OPERATIONS.ENTITLEMENT_AUTHORITY_AVAILABILITY)) + .set( + ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY, + org.jooq + .impl + .DSL + .when(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST.isNull(), "NOT_EVALUATED") + .otherwise(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_AUTHORITY_AVAILABILITY)) + .set(ACCOUNT_JOIN_OPERATIONS.MEMBERSHIP_ID, membershipId) + .set(ACCOUNT_JOIN_OPERATIONS.OUTCOME_MEMBERSHIP_VERSION, membershipVersion) + .set( + ACCOUNT_JOIN_OPERATIONS.OUTCOME_MEMBERSHIP_AUTHORITY_GENERATION, + membershipAuthorityGeneration) + .set(ACCOUNT_JOIN_OPERATIONS.LAST_ATTEMPT_FAILURE_CODE, (String) null) + .set(ACCOUNT_JOIN_OPERATIONS.UPDATED_AT, org.jooq.impl.DSL.currentLocalDateTime()) + .where( + ACCOUNT_JOIN_OPERATIONS + .REQUEST_ID + .eq(requestId) + .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING"))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("JOIN operation changed concurrently"); + } + } + + public void recordCallerBoundAuthorityInvalidation(String requestId) { + int updated = + dsl.update(ACCOUNT_JOIN_OPERATIONS) + .set(ACCOUNT_JOIN_OPERATIONS.CALLER_BOUND_AUTHORITY_INVALIDATED, true) + .where( + ACCOUNT_JOIN_OPERATIONS + .REQUEST_ID + .eq(requestId) + .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING"))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("JOIN operation changed concurrently"); + } + } + + public record JoinOperation( + long accountId, + long tenantId, + UUID realmId, + String callerBinding, + String scopeTokenHash, + String connectScopeDigest, + String entitlementAuthorityAvailability, + Boolean allowPublicJoin, + Long entitlementVersion, + Integer requestDigestVersion, + String requestDigest, + String status, + String outcome, + Long membershipId, + Long membershipVersion, + Long membershipAuthorityGeneration, + int intentDigestVersion, + String intentDigest, + String lastAttemptFailureCode, + String lastAttemptAuthorityAvailability) {} + + private static JoinOperation toJoinOperation( + net.firedevops.firemud.accountservice.jooq.tables.records.AccountJoinOperationsRecord row) { + return new JoinOperation( + row.getAccountId(), + row.getTenantId(), + row.getRealmId(), + row.getVerifiedCallerBinding(), + row.getScopeTokenHash(), + row.getConnectScopeDigest(), + row.getEntitlementAuthorityAvailability(), + row.getAllowPublicJoin(), + row.getEntitlementVersion(), + row.getRequestDigestVersion(), + row.getRequestDigest(), + row.getStatus(), + row.getOutcome(), + row.getMembershipId(), + row.getOutcomeMembershipVersion(), + row.getOutcomeMembershipAuthorityGeneration(), + row.getIntentDigestVersion(), + row.getIntentDigest(), + row.getLastAttemptFailureCode(), + row.getLastAttemptAuthorityAvailability()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java index 086e84468c..1a4b5e3e10 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java @@ -65,6 +65,12 @@ public AccountTenantMembership save(AccountTenantMembership entity) { .set( ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED, entity.isGameplayAdmissionAllowed()) + .set(ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE, entity.getLifecycleState()) + .set(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION, entity.getMembershipVersion()) + .set( + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION, + entity.getMembershipAuthorityGeneration()) + .set(ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE, entity.getAuthorityProvenance()) .returningResult(ACCOUNT_TENANT_MEMBERSHIP.ID) .fetchOne(ACCOUNT_TENANT_MEMBERSHIP.ID); entity.setId(id); @@ -77,6 +83,12 @@ public AccountTenantMembership save(AccountTenantMembership entity) { .set( ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED, entity.isGameplayAdmissionAllowed()) + .set(ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE, entity.getLifecycleState()) + .set(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION, entity.getMembershipVersion()) + .set( + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION, + entity.getMembershipAuthorityGeneration()) + .set(ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE, entity.getAuthorityProvenance()) .where(ACCOUNT_TENANT_MEMBERSHIP.ID.eq(entity.getId())) .execute(); if (updated != 1) { @@ -119,6 +131,10 @@ private org.jooq.SelectOnConditionStep baseSelect() { ACCOUNT_TENANT_MEMBERSHIP.ACCOUNT_ID, ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID, ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED, + ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE, + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION, + ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION, + ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE, ACCOUNTS.ID, ACCOUNTS.USERNAME, ACCOUNTS.EMAIL, @@ -146,6 +162,11 @@ private AccountTenantMembership toEntity(Record record) { membership.setTenantId(record.get(ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID)); membership.setGameplayAdmissionAllowed( Boolean.TRUE.equals(record.get(ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED))); + membership.setLifecycleState(record.get(ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE)); + membership.setMembershipVersion(record.get(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION)); + membership.setMembershipAuthorityGeneration( + record.get(ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_AUTHORITY_GENERATION)); + membership.setAuthorityProvenance(record.get(ACCOUNT_TENANT_MEMBERSHIP.AUTHORITY_PROVENANCE)); return membership; } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java index 1954a5e2e5..1b5084e019 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java @@ -28,6 +28,15 @@ public List findByTenantId(Long tenantId) { .fetch(this::toEntity); } + /** Shares the row lock with subscription writers through the JOIN commit boundary. */ + public List findByTenantIdForUpdate(Long tenantId) { + return baseSelect() + .where(SUBSCRIPTION.TENANT_ID.eq(tenantId)) + .orderBy(SUBSCRIPTION.ID.asc()) + .forUpdate() + .fetch(this::toEntity); + } + public List findByAccountId(Long accountId) { return baseSelect() .where(SUBSCRIPTION.ACCOUNT_ID.eq(accountId)) @@ -46,9 +55,11 @@ public Subscription save(Subscription entity) { .set(SUBSCRIPTION.STARTED_AT, entity.getStartedAt()) .set(SUBSCRIPTION.ENDED_AT, entity.getEndedAt()) .set(SUBSCRIPTION.TENANT_ID, entity.getTenantId()) + .set(SUBSCRIPTION.ENTITLEMENT_VERSION, 1L) .returningResult(SUBSCRIPTION.ID) .fetchOne(SUBSCRIPTION.ID); entity.setId(id); + entity.setEntitlementVersion(1L); return entity; } int updated = @@ -59,11 +70,17 @@ public Subscription save(Subscription entity) { .set(SUBSCRIPTION.STARTED_AT, entity.getStartedAt()) .set(SUBSCRIPTION.ENDED_AT, entity.getEndedAt()) .set(SUBSCRIPTION.TENANT_ID, entity.getTenantId()) - .where(SUBSCRIPTION.ID.eq(entity.getId())) + .set(SUBSCRIPTION.ENTITLEMENT_VERSION, SUBSCRIPTION.ENTITLEMENT_VERSION.add(1L)) + .where( + SUBSCRIPTION + .ID + .eq(entity.getId()) + .and(SUBSCRIPTION.ENTITLEMENT_VERSION.eq(entity.getEntitlementVersion()))) .execute(); if (updated != 1) { throw JooqAccountRepositorySupport.staleWrite("subscription", entity.getId()); } + entity.setEntitlementVersion(entity.getEntitlementVersion() + 1L); return entity; } @@ -86,6 +103,7 @@ private org.jooq.SelectOnConditionStep baseSelect() { SUBSCRIPTION.STARTED_AT, SUBSCRIPTION.ENDED_AT, SUBSCRIPTION.TENANT_ID, + SUBSCRIPTION.ENTITLEMENT_VERSION, ACCOUNTS.ID, ACCOUNTS.USERNAME, ACCOUNTS.EMAIL, @@ -115,6 +133,7 @@ private Subscription toEntity(Record record) { entity.setStartedAt(record.get(SUBSCRIPTION.STARTED_AT)); entity.setEndedAt(record.get(SUBSCRIPTION.ENDED_AT)); entity.setTenantId(record.get(SUBSCRIPTION.TENANT_ID)); + entity.setEntitlementVersion(record.get(SUBSCRIPTION.ENTITLEMENT_VERSION)); return entity; } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java new file mode 100644 index 0000000000..c57c6b8ec9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** At-least-once delivery of Account's immutable audit outbox envelopes. */ +@Component +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected collaborators are internal Spring singletons.") +public class AccountAuditDeliveryJob { + private static final Logger logger = LoggerFactory.getLogger(AccountAuditDeliveryJob.class); + private final AccountAuditOutboxRepository outbox; + private final LoggingAdminClient loggingAdminClient; + + public AccountAuditDeliveryJob( + AccountAuditOutboxRepository outbox, LoggingAdminClient loggingAdminClient) { + this.outbox = outbox; + this.loggingAdminClient = loggingAdminClient; + } + + @Scheduled(fixedDelayString = "${firemud.account.audit-delivery-delay-ms:5000}") + public void deliverPending() { + for (var envelope : outbox.pending(50)) { + try { + var receipt = loggingAdminClient.deliver(envelope); + outbox.markDelivered( + envelope.auditEventId(), + receipt.receiptId(), + receipt.logEventId(), + receipt.minimized()); + } catch (RuntimeException ex) { + outbox.recordAttempt(envelope.auditEventId()); + logger.warn("Account audit delivery remains pending for event {}", envelope.auditEventId()); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java index 83f8fe3f7a..c3d2909abc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java @@ -10,6 +10,11 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.ProfileDto; @@ -47,6 +52,15 @@ java.util.List listBootstrapCharacters( ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenRequest request); + JoinPublicProductionResult joinPublicProduction( + String bootstrapToken, JoinPublicProductionRequest request); + + DirectTextJoinScope issueDirectTextConnectScope( + DirectTextCallerContext caller, DirectTextJoinTarget target); + + JoinPublicProductionResult joinPublicProductionFromGameSession( + DirectTextCallerContext caller, JoinPublicProductionRequest request); + RuntimeMembershipDto getTenantMembershipForRuntime( Long accountId, Long tenantId, String requestId); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 56f1696b35..a7a2e57849 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -4,6 +4,7 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; @@ -24,6 +25,10 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.account.v1.PingRequest; import net.firedevops.firemud.account.v1.PingResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpRequest; @@ -32,6 +37,9 @@ import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.account.v1.VerifyEmailLoginOtpRequest; import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.service.AccountService; @@ -41,12 +49,14 @@ import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.RequestIdValidation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.grpc.server.service.GrpcService; import tools.jackson.databind.JsonNode; import tools.jackson.databind.json.JsonMapper; @@ -58,9 +68,15 @@ public class AccountGrpcService extends AccountServiceGrpc.AccountServiceImplBas private final PingService pingService; private final AccountService accountService; private final MeterRegistry meterRegistry; + private final String workloadNamespace; public AccountGrpcService(PingService pingService, AccountService accountService) { - this(pingService, accountService, null); + this(pingService, accountService, null, null); + } + + public AccountGrpcService( + PingService pingService, AccountService accountService, MeterRegistry meterRegistry) { + this(pingService, accountService, meterRegistry, null); } @Autowired @@ -68,10 +84,151 @@ public AccountGrpcService(PingService pingService, AccountService accountService value = "EI_EXPOSE_REP2", justification = "Injected services and registry remain internal collaborators.") public AccountGrpcService( - PingService pingService, AccountService accountService, MeterRegistry meterRegistry) { + PingService pingService, + AccountService accountService, + MeterRegistry meterRegistry, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.pingService = pingService; this.accountService = accountService; this.meterRegistry = meterRegistry; + this.workloadNamespace = workloadNamespace; + } + + @Override + @Timed(value = "accountGrpc.issueDirectTextConnectScope") + public void issueDirectTextConnectScope( + IssueDirectTextConnectScopeRequest request, + StreamObserver responseObserver) { + IssueDirectTextConnectScopeResponse.Builder response = + IssueDirectTextConnectScopeResponse.newBuilder(); + try { + requireGameSessionPeer(); + DirectTextCallerContext caller = directTextCaller(request.getPlayerContext()); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + UUID realmId = requireCanonicalRealmId(request.getRealmId()); + long gameInstanceId = requirePositiveRequestId(request.getGameInstanceId(), "gameInstanceId"); + if (caller.tenantId() != tenantId + || !caller.realmId().equals(realmId) + || caller.gameInstanceId() != gameInstanceId + || !caller.playableStateNamespaceId().equals(request.getPlayableStateNamespaceId()) + || !caller.playableStateScope().equals(request.getPlayableStateScope())) { + throw new InvalidRequestException("Player context and selected realm disagree", null); + } + var scope = + accountService.issueDirectTextConnectScope( + caller, + new DirectTextJoinTarget( + tenantId, + realmId, + requireText(request.getWorldSlug(), "worldSlug"), + requireText(request.getRealmSlug(), "realmSlug"), + requireText(request.getPlayableStateNamespaceId(), "playableStateNamespaceId"), + requireText(request.getPlayableStateScope(), "playableStateScope"), + gameInstanceId, + request.getCatalogRevision(), + request.getPointerVersion())); + response + .setConnectScopeId(scope.connectScopeId()) + .setConnectScopeExpiresAt(scope.connectScopeExpiresAt()); + } catch (AdminAuthorizationException ex) { + response.setError( + appError("IssueDirectTextConnectScope", "PERMISSION_DENIED", ex.getMessage())); + } catch (AuthenticationException ex) { + response.setError(appError("IssueDirectTextConnectScope", ex.getCode(), ex.getMessage())); + } catch (InvalidRequestException | IllegalArgumentException ex) { + response.setError( + appError("IssueDirectTextConnectScope", "INVALID_ARGUMENT", ex.getMessage())); + } + responseObserver.onNext(response.build()); + responseObserver.onCompleted(); + } + + @Override + @Timed(value = "accountGrpc.joinPublicProductionMembership") + public void joinPublicProductionMembership( + JoinPublicProductionMembershipRequest request, + StreamObserver responseObserver) { + JoinPublicProductionMembershipResponse.Builder response = + JoinPublicProductionMembershipResponse.newBuilder(); + try { + requireGameSessionPeer(); + DirectTextCallerContext caller = directTextCaller(request.getPlayerContext()); + String requestId = requireText(request.getRequestId(), "requestId"); + if (!requestId.equals(caller.requestId())) { + throw new InvalidRequestException("Player context and JOIN request ID disagree", null); + } + var result = + accountService.joinPublicProductionFromGameSession( + caller, + new JoinPublicProductionRequest( + requireText(request.getConnectScopeId(), "connectScopeId"), requestId)); + response + .setSuccess(result.success()) + .setOutcomeCode(result.outcomeCode()) + .setAccountId(Long.toString(result.accountId())) + .setTenantId(Long.toString(result.tenantId())) + .setMembershipId(Long.toString(result.membershipId())) + .setMembershipVersion(result.membershipVersion()) + .setMembershipAuthorityGeneration(result.membershipAuthorityGeneration()) + .setReplayed(result.replayed()); + } catch (AdminAuthorizationException ex) { + response.setError( + appError("JoinPublicProductionMembership", "PERMISSION_DENIED", ex.getMessage())); + } catch (AuthenticationException ex) { + response.setError(appError("JoinPublicProductionMembership", ex.getCode(), ex.getMessage())); + } catch (InvalidRequestException | IllegalArgumentException ex) { + response.setError( + appError("JoinPublicProductionMembership", "INVALID_ARGUMENT", ex.getMessage())); + } + responseObserver.onNext(response.build()); + responseObserver.onCompleted(); + } + + private void requireGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || workloadNamespace == null + || workloadNamespace.isBlank() + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service")) { + throw new AdminAuthorizationException("Verified Game Session workload identity is required"); + } + } + + private DirectTextCallerContext directTextCaller( + net.firedevops.firemud.shared.v1.PlayerExecutionContext context) { + return new DirectTextCallerContext( + requirePositiveRequestId(context.getAccountId(), "accountId"), + requirePositiveRequestId(context.getTenantId(), "tenantId"), + requireCanonicalRealmId(context.getRealmId()), + requireText(context.getPlayableStateNamespaceId(), "playableStateNamespaceId"), + requireText(context.getPlayableStateScope(), "playableStateScope"), + requirePositiveRequestId(context.getGameInstanceId(), "gameInstanceId"), + requireText(context.getSessionId(), "sessionId"), + context.getRequestId()); + } + + private UUID requireCanonicalRealmId(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("realmId is required"); + } + try { + UUID realmId = UUID.fromString(value); + if (!realmId.toString().equals(value)) { + throw new IllegalArgumentException("realmId must be a canonical UUID"); + } + return realmId; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("realmId must be a canonical UUID", ex); + } + } + + private String requireText(String value, String fieldName) { + int maxLength = "connectScopeId".equals(fieldName) ? 2048 : 128; + if (value == null || value.isBlank() || value.length() > maxLength) { + throw new InvalidRequestException(fieldName + " is required and bounded", null); + } + return value; } @Override @@ -90,10 +247,7 @@ public void createAccount( try { net.firedevops.firemud.accountservice.dto.CreateAccountRequest dto = new net.firedevops.firemud.accountservice.dto.CreateAccountRequest( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - request.getUsername(), - request.getEmail(), - request.getPassword()); + request.getUsername(), request.getEmail(), request.getPassword()); var account = accountService.createAccount(dto); CreateAccountResponse response = CreateAccountResponse.newBuilder().setAccountId(account.id().toString()).build(); @@ -222,6 +376,8 @@ public void getTenantMembershipForRuntime( .setMembershipExists(dto.membershipExists()) .setGameplayAdmissionAllowed(dto.gameplayAdmissionAllowed()) .setMembershipVersion(dto.membershipVersion()) + .setMembershipLifecycleState(dto.membershipLifecycleState()) + .setMembershipAuthorityGeneration(dto.membershipAuthorityGeneration()) .setEvaluatedAt(dto.evaluatedAt()) .build(); responseObserver.onNext(response); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 8eeeeaa183..c6edd91b3e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -20,11 +20,11 @@ import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; -import net.firedevops.firemud.accountservice.client.LoggingAdminClient; import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.config.MailProperties; import net.firedevops.firemud.accountservice.dto.AccountDataExportDto; import net.firedevops.firemud.accountservice.dto.AccountDto; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; import net.firedevops.firemud.accountservice.dto.BootstrapCharacterDto; import net.firedevops.firemud.accountservice.dto.BootstrapRealmDto; @@ -33,6 +33,11 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.ProfileDto; @@ -44,6 +49,7 @@ import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; import net.firedevops.firemud.accountservice.dto.UpdateProfileRequest; import net.firedevops.firemud.accountservice.dto.UsernameRecoveryRequest; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; @@ -57,7 +63,11 @@ import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.mapper.AccountMapper; import net.firedevops.firemud.accountservice.mapper.ProfileMapper; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -75,9 +85,6 @@ import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.LoggingUtil; -import net.firedevops.firemud.common.saga.SagaBuilder; -import net.firedevops.firemud.common.saga.SagaException; -import net.firedevops.firemud.common.saga.SagaRunner; import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; @@ -87,11 +94,15 @@ import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.StringUtils; import org.springframework.web.server.ResponseStatusException; +import tools.jackson.databind.json.JsonMapper; @Service public class AccountServiceImpl implements AccountService { @@ -105,8 +116,12 @@ public class AccountServiceImpl implements AccountService { private static final String GAMEPLAY_DELEGATION_AUDIENCE = "account-service"; private static final int EMAIL_LOGIN_OTP_MAX_ATTEMPTS = 5; private static final SecureRandom EMAIL_LOGIN_OTP_RANDOM = new SecureRandom(); + private static final JsonMapper AUDIT_JSON = JsonMapper.builder().build(); private final AccountRepository accountRepository; + private final AccountAuditOutboxRepository accountAuditOutboxRepository; + private final AccountConnectScopeRepository accountConnectScopeRepository; + private final AccountJoinOperationRepository accountJoinOperationRepository; private final AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; private final AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; private final AccountTenantMembershipRepository accountTenantMembershipRepository; @@ -123,18 +138,20 @@ public class AccountServiceImpl implements AccountService { private final MailProperties mailProperties; private final AccountTokenProperties tokenProperties; private final JwtAuthProperties jwtAuthProperties; - private final LoggingAdminClient loggingAdminClient; private final GameSessionClient gameSessionClient; private final EntityManagementClient entityManagementClient; private final JwtUtil jwtUtil; private final net.firedevops.firemud.accountservice.service.session.SessionService sessionService; - private final SagaRunner sagaRunner; + private final TransactionTemplate joinTransactionTemplate; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Dependencies are injected and kept internal") public AccountServiceImpl( AccountRepository accountRepository, + AccountAuditOutboxRepository accountAuditOutboxRepository, + AccountConnectScopeRepository accountConnectScopeRepository, + AccountJoinOperationRepository accountJoinOperationRepository, AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository, AccountRealmAccessGrantRepository accountRealmAccessGrantRepository, AccountTenantMembershipRepository accountTenantMembershipRepository, @@ -151,13 +168,15 @@ public AccountServiceImpl( MailProperties mailProperties, AccountTokenProperties tokenProperties, JwtAuthProperties jwtAuthProperties, - LoggingAdminClient loggingAdminClient, GameSessionClient gameSessionClient, EntityManagementClient entityManagementClient, JwtUtil jwtUtil, net.firedevops.firemud.accountservice.service.session.SessionService sessionService, - SagaRunner sagaRunner) { + PlatformTransactionManager transactionManager) { this.accountRepository = accountRepository; + this.accountAuditOutboxRepository = accountAuditOutboxRepository; + this.accountConnectScopeRepository = accountConnectScopeRepository; + this.accountJoinOperationRepository = accountJoinOperationRepository; this.accountEmailLoginChallengeRepository = accountEmailLoginChallengeRepository; this.accountRealmAccessGrantRepository = accountRealmAccessGrantRepository; this.accountTenantMembershipRepository = accountTenantMembershipRepository; @@ -174,65 +193,37 @@ public AccountServiceImpl( this.mailProperties = mailProperties; this.tokenProperties = tokenProperties; this.jwtAuthProperties = jwtAuthProperties; - this.loggingAdminClient = loggingAdminClient; this.gameSessionClient = gameSessionClient; this.entityManagementClient = entityManagementClient; this.jwtUtil = jwtUtil; this.sessionService = sessionService; - this.sagaRunner = sagaRunner; + this.joinTransactionTemplate = new TransactionTemplate(transactionManager); + this.joinTransactionTemplate.setPropagationBehavior( + TransactionDefinition.PROPAGATION_REQUIRES_NEW); } @Override @Transactional @Timed(value = "account.create") public AccountDto createAccount(CreateAccountRequest request) { - logger.info("Creating account {} for tenant {}", request.username(), request.tenantId()); + logger.info("Creating global account {}", request.username()); Account account = new Account(); account.setUsername(request.username()); account.setEmail(EmailCanonicalization.normalize(request.email())); account.setPasswordHash(hashPassword(request.password())); - account.setRole("player"); - Profile profile = new Profile(); - profile.setTenantId(request.tenantId()); - profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); - AccountTenantMembership membership = new AccountTenantMembership(); - membership.setTenantId(request.tenantId()); - membership.setGameplayAdmissionAllowed(true); - - SagaBuilder builder = new SagaBuilder("accountCreation"); - builder.step( - "persistAccount", - () -> { - Account saved; - try { - saved = accountRepository.save(account); - } catch (IntegrityConstraintViolationException | DataIntegrityViolationException ex) { - throw new AccountAlreadyExistsException(ex); - } - account.setId(saved.getId()); - membership.setAccount(saved); - accountTenantMembershipRepository.save(membership); - profile.setAccount(saved); - profileRepository.save(profile); - }, - () -> { - profileRepository.delete(profile); - accountTenantMembershipRepository.delete(membership); - accountRepository.delete(account); - }); - var saga = builder.build(); + Account saved; try { - sagaRunner.run(saga); - } catch (SagaException e) { - if (e.getCause() instanceof AccountAlreadyExistsException alreadyExists) { - throw alreadyExists; - } - logger.warn("Account creation saga failed", e); - throw new IllegalStateException("Account creation failed", e); + saved = accountRepository.save(account); + } catch (IntegrityConstraintViolationException | DataIntegrityViolationException ex) { + throw new AccountAlreadyExistsException(ex); } - runAfterCommit(() -> safeLogAccountCreation(request.tenantId(), account.getId())); - - return accountMapper.toDto(account); + accountAuditOutboxRepository.append( + UUID.randomUUID(), + "platform", + null, + "ACCOUNT_REGISTERED", + "{\"accountId\":" + saved.getId() + "}"); + return accountMapper.toDto(saved); } @Override @@ -383,27 +374,27 @@ public PlayerBootstrapResult issuePlayerBootstrap(String accountIdentifier, Stri @Timed(value = "account.bootstrap_worlds") public List listBootstrapWorlds(String bootstrapToken) { BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); - return gameSessionClient.listGameplayWorlds().stream() + return listGameplayWorlds().stream() .filter(world -> hasAdmissibleRealm(bootstrapContext, world.getWorldSlug())) .map(world -> new BootstrapWorldDto(world.getWorldSlug(), world.getDisplayName())) .toList(); } @Override - @Transactional(readOnly = true) + @Transactional @Timed(value = "account.bootstrap_realms") public List listBootstrapRealms(String bootstrapToken, String worldSlug) { BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); Instant evaluatedAt = Instant.now(); Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); - return gameSessionClient.listGameplayRealms(worldSlug).stream() - .map(realm -> readAdmissibleDiscoveryRealm(bootstrapContext, realm)) - .flatMap(Optional::stream) + return listAdmissibleRuntimeRealmTargets(bootstrapContext, worldSlug).stream() + .map(realm -> requireRealmTarget(realm.tenantId(), realm.worldSlug(), realm.realmSlug())) .map( realm -> new BootstrapRealmDto( realm.worldSlug(), realm.realmSlug(), + realm.realmId().toString(), realm.displayName(), realm.tenantId(), realm.gameInstanceId(), @@ -413,7 +404,7 @@ public List listBootstrapRealms(String bootstrapToken, String realm.characterCreationPolicy(), evaluatedAt.toString(), expiresAt.toString(), - mintConnectScopeId(bootstrapContext, realm, evaluatedAt, expiresAt))) + mintAndRetainConnectScope(bootstrapContext, realm, evaluatedAt, expiresAt))) .toList(); } @@ -447,6 +438,544 @@ public List listBootstrapCharacters( .toList(); } + @Override + @Timed(value = "account.public_production_join") + public JoinPublicProductionResult joinPublicProduction( + String bootstrapToken, JoinPublicProductionRequest request) { + BootstrapContext caller = requireBootstrapContext(bootstrapToken); + Claims callerClaims = + requireSignedTokenClaims( + bootstrapToken, + "player-bootstrap", + "CONNECT_CONTEXT_INVALID", + "Missing bootstrap token", + "Invalid bootstrap token"); + String callerBinding; + try { + callerBinding = JwtClaims.requireText(callerClaims.get("jti"), "jti"); + } catch (IllegalArgumentException ex) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Bootstrap caller binding is missing", ex); + } + requireAuthenticationEligible(requireAccount(caller.accountId())); + return joinPublicProductionForTrustedCaller(caller.accountId(), callerBinding, null, request); + } + + @Override + @Transactional + @Timed(value = "account.direct_text_connect_scope") + public DirectTextJoinScope issueDirectTextConnectScope( + DirectTextCallerContext caller, DirectTextJoinTarget target) { + if (caller == null + || target == null + || caller.accountId() <= 0L + || caller.tenantId() != target.tenantId() + || !caller.realmId().equals(target.realmId()) + || caller.gameInstanceId() != target.gameInstanceId() + || !caller.playableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !caller.playableStateScope().equals(target.playableStateScope())) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } + requireAuthenticationEligible(requireAccount(caller.accountId())); + RuntimeRealmTarget current = + requireRealmTarget(target.tenantId(), target.worldSlug(), target.realmSlug()); + if (!isPublicProductionRealm(current)) { + throw new AuthenticationException( + "REALM_UNAVAILABLE", "Selected public realm is unavailable"); + } + if (!current.realmId().equals(target.realmId()) + || !current.playableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !current.stateScope().equals(target.playableStateScope()) + || current.gameInstanceId() != target.gameInstanceId() + || current.catalogRevision() != target.catalogRevision() + || current.pointerVersion() != target.pointerVersion()) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + RuntimeEntitlementsDto entitlements = + getTenantEntitlementsForRuntime(current.tenantId(), caller.requestId()); + if (!entitlements.gameplayAvailable()) { + throw new AuthenticationException( + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + } + Instant evaluatedAt = Instant.now(); + Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); + String scopeId = + mintAndRetainConnectScope( + new BootstrapContext(caller.accountId()), current, evaluatedAt, expiresAt); + return new DirectTextJoinScope(scopeId, expiresAt.toString()); + } + + @Override + @Timed(value = "account.public_production_join_internal") + public JoinPublicProductionResult joinPublicProductionFromGameSession( + DirectTextCallerContext caller, JoinPublicProductionRequest request) { + if (caller == null + || caller.accountId() <= 0L + || !StringUtils.hasText(caller.sessionId()) + || request == null + || !caller.requestId().equals(request.requestId())) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "JOIN caller context is missing"); + } + requireAuthenticationEligible(requireAccount(caller.accountId())); + return joinPublicProductionForTrustedCaller( + caller.accountId(), caller.sessionId(), caller, request); + } + + private JoinPublicProductionResult joinPublicProductionForTrustedCaller( + long accountId, + String callerBinding, + DirectTextCallerContext directTextCaller, + JoinPublicProductionRequest request) { + if (request == null + || !StringUtils.hasText(request.connectScopeId()) + || !StringUtils.hasText(request.requestId())) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } + String requestId = request.requestId(); + String scopeTokenHash = AccountJoinDigest.tokenHash(request.connectScopeId()); + Optional existing = accountJoinOperationRepository.find(requestId); + VerifiedJoinScope retained; + if (existing.isPresent()) { + JoinOperation operation = existing.orElseThrow(); + if (operation.accountId() != accountId + || !operation.callerBinding().equals(callerBinding) + || !operation.scopeTokenHash().equals(scopeTokenHash)) { + throw new AuthenticationException( + "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); + } + retained = retainedJoinScope(request.connectScopeId()); + validateDirectTextJoinScope(directTextCaller, retained); + requireMatchingJoinIntent(operation, requestId, callerBinding, retained); + } else { + ConnectScopeContext signedScope = requireConnectScopeContext(request.connectScopeId()); + retained = retainedJoinScope(request.connectScopeId()); + validateDirectTextJoinScope(directTextCaller, retained); + validateSignedJoinScope(signedScope, retained, accountId); + String intentDigest = AccountJoinDigest.intent(requestId, retained, callerBinding); + try { + joinTransactionTemplate.execute( + transactionStatus -> + accountJoinOperationRepository.insertIntent( + requestId, retained, callerBinding, intentDigest)); + } catch (RuntimeException ex) { + Optional claimReadback = safeFindJoinOperation(requestId); + if (claimReadback.isEmpty()) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "JOIN request claim is uncertain; retry the same request", ex); + } + requireMatchingJoinIntent(claimReadback.orElseThrow(), requestId, callerBinding, retained); + } + JoinOperation claimed = + accountJoinOperationRepository + .find(requestId) + .orElseThrow( + () -> + new AuthenticationException( + "AUTH_UNAVAILABLE", "JOIN request claim is not yet readable")); + requireMatchingJoinIntent(claimed, requestId, callerBinding, retained); + } + + try { + return joinTransactionTemplate.execute( + transactionStatus -> executeJoinAttempt(accountId, callerBinding, requestId, retained)); + } catch (AuthenticationException ex) { + if ("IDEMPOTENCY_CONFLICT".equals(ex.getCode())) { + throw ex; + } + recordJoinAttemptFailureAfterRollback(requestId, ex.getCode()); + return pendingJoinFailure(retained, ex.getCode()); + } catch (RuntimeException ex) { + Optional outcomeReadback = safeFindJoinOperation(requestId); + if (outcomeReadback.isPresent()) { + JoinOperation operation = outcomeReadback.orElseThrow(); + requireMatchingJoinIntent(operation, requestId, callerBinding, retained); + if (!"PENDING".equals(operation.status())) { + return resultFromJoinOperation(operation, true); + } + recordJoinAttemptFailureAfterRollback(requestId, "AUTH_UNAVAILABLE"); + } + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "JOIN outcome is uncertain; retry the same request", ex); + } + } + + private JoinPublicProductionResult executeJoinAttempt( + long accountId, String callerBinding, String requestId, VerifiedJoinScope scope) { + accountJoinOperationRepository.lockAccount(accountId); + JoinOperation operation = + accountJoinOperationRepository + .findForUpdate(requestId) + .orElseThrow(() -> new IllegalStateException("JOIN request claim disappeared")); + requireMatchingJoinIntent(operation, requestId, callerBinding, scope); + + if (!"PENDING".equals(operation.status())) { + return replayJoinOperation(operation, callerBinding, scope); + } + + if (isConnectScopeExpired(scope)) { + return failedJoin(requestId, scope, "CONNECT_SCOPE_INVALID"); + } + + JoinEvaluation evaluation = evaluateJoin(scope); + if (evaluation.failureCode() != null) { + if (isRetryableJoinAuthorityFailure(evaluation)) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, evaluation.authorityAvailability(), evaluation.failureCode()); + return pendingJoinFailure(scope, evaluation.failureCode()); + } + return failedJoin(requestId, scope, evaluation.failureCode()); + } + if (!"AVAILABLE".equals(evaluation.authorityAvailability()) + || evaluation.allowPublicJoin() == null + || evaluation.entitlementVersion() == null) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, evaluation.authorityAvailability(), "ENTITLEMENT_UNAVAILABLE"); + return pendingJoinFailure(scope, "ENTITLEMENT_UNAVAILABLE"); + } + String requestDigest = + AccountJoinDigest.request( + scope, callerBinding, evaluation.allowPublicJoin(), evaluation.entitlementVersion()); + if (operation.requestDigest() != null + && (!Integer.valueOf(1).equals(operation.requestDigestVersion()) + || !operation.requestDigest().equals(requestDigest))) { + return failedJoin(requestId, scope, "IDEMPOTENCY_CONFLICT"); + } + if (operation.requestDigest() == null) { + accountJoinOperationRepository.bindPolicyEvidence( + requestId, requestDigest, evaluation.entitlementVersion(), evaluation.allowPublicJoin()); + } + if (!evaluation.gameplayAvailable()) { + return failedJoin(requestId, scope, "TENANT_BILLING_BLOCKED"); + } + if (!evaluation.allowPublicJoin()) { + return failedJoin(requestId, scope, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + } + + JoinEvaluation commitEvaluation = evaluateJoin(scope); + if (commitEvaluation.failureCode() != null) { + if (isRetryableJoinAuthorityFailure(commitEvaluation)) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, commitEvaluation.authorityAvailability(), commitEvaluation.failureCode()); + return pendingJoinFailure(scope, commitEvaluation.failureCode()); + } + return failedJoin(requestId, scope, commitEvaluation.failureCode()); + } + if (!"AVAILABLE".equals(commitEvaluation.authorityAvailability())) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, commitEvaluation.authorityAvailability(), "ENTITLEMENT_UNAVAILABLE"); + return pendingJoinFailure(scope, "ENTITLEMENT_UNAVAILABLE"); + } + String commitDigest = + AccountJoinDigest.request( + scope, + callerBinding, + commitEvaluation.allowPublicJoin(), + commitEvaluation.entitlementVersion()); + if (!requestDigest.equals(commitDigest)) { + return failedJoin(requestId, scope, "IDEMPOTENCY_CONFLICT"); + } + if (!commitEvaluation.gameplayAvailable()) { + return failedJoin(requestId, scope, "TENANT_BILLING_BLOCKED"); + } + if (!commitEvaluation.allowPublicJoin()) { + return failedJoin(requestId, scope, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + } + AccountTenantMembership membership = + accountTenantMembershipRepository + .findByAccountIdAndTenantId(accountId, scope.tenantId()) + .orElse(null); + boolean transitioned = false; + if (membership == null) { + membership = new AccountTenantMembership(); + membership.setAccount(requireAccount(accountId)); + membership.setTenantId(scope.tenantId()); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(1L); + membership.setLifecycleState("ACTIVE"); + membership.setGameplayAdmissionAllowed(true); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + accountTenantMembershipRepository.save(membership); + transitioned = true; + } else if ("INACTIVE".equals(membership.getLifecycleState())) { + accountJoinOperationRepository.recordCallerBoundAuthorityInvalidation(requestId); + membership.setLifecycleState("ACTIVE"); + membership.setGameplayAdmissionAllowed(true); + membership.setMembershipVersion(membership.getMembershipVersion() + 1L); + membership.setMembershipAuthorityGeneration( + membership.getMembershipAuthorityGeneration() + 1L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + accountTenantMembershipRepository.save(membership); + transitioned = true; + } else if (!"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed()) { + return failedJoin(requestId, scope, "MEMBERSHIP_RECONCILIATION_REQUIRED"); + } + if (transitioned) { + String payload = + AUDIT_JSON.writeValueAsString( + new JoinAuditPayload( + accountId, + scope.tenantId(), + scope.worldSlug(), + scope.realmSlug(), + membership.getMembershipVersion(), + requestId)); + UUID auditEventId = + UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); + accountAuditOutboxRepository.append( + auditEventId, "tenant", scope.tenantId(), "ACCOUNT_JOINED_PUBLIC_PRODUCTION", payload); + } + accountJoinOperationRepository.finish( + requestId, + "COMMITTED", + transitioned ? "JOINED" : "ALREADY_ACTIVE", + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration()); + return new JoinPublicProductionResult( + true, + transitioned ? "JOINED" : "ALREADY_ACTIVE", + accountId, + scope.tenantId(), + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + false); + } + + private JoinPublicProductionResult failedJoin( + String requestId, VerifiedJoinScope scope, String outcomeCode) { + accountJoinOperationRepository.finish(requestId, "FAILED", outcomeCode, null, null, null); + return new JoinPublicProductionResult( + false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); + } + + private JoinPublicProductionResult pendingJoinFailure( + VerifiedJoinScope scope, String outcomeCode) { + return new JoinPublicProductionResult( + false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); + } + + private boolean isConnectScopeExpired(VerifiedJoinScope scope) { + try { + return !Instant.parse(scope.connectScopeExpiresAt()).isAfter(Instant.now()); + } catch (RuntimeException ex) { + return true; + } + } + + private boolean isRetryableJoinAuthorityFailure(JoinEvaluation evaluation) { + return "UNAVAILABLE".equals(evaluation.authorityAvailability()) + || "ADMISSION_POINTER_UNAVAILABLE".equals(evaluation.failureCode()) + || "AUTH_UNAVAILABLE".equals(evaluation.failureCode()) + || "ENTITLEMENT_UNAVAILABLE".equals(evaluation.failureCode()); + } + + private VerifiedJoinScope retainedJoinScope(String connectScopeId) { + return accountConnectScopeRepository + .find(connectScopeId) + .orElseThrow( + () -> + new AuthenticationException( + "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable")); + } + + private void validateSignedJoinScope( + ConnectScopeContext signedScope, VerifiedJoinScope retained, long accountId) { + if (retained.accountId() != accountId + || signedScope.accountId() != accountId + || signedScope.tenantId() != retained.tenantId() + || !signedScope.realmId().equals(retained.realmId()) + || !signedScope.playableStateNamespaceId().equals(retained.playableStateNamespaceId()) + || !signedScope.playableStateScope().equals(retained.playableStateScope()) + || signedScope.gameInstanceId() != retained.gameInstanceId() + || signedScope.catalogRevision() != retained.catalogRevision() + || signedScope.pointerVersion() != retained.pointerVersion() + || !signedScope.worldSlug().equals(retained.worldSlug()) + || !signedScope.realmSlug().equals(retained.realmSlug()) + || !signedScope.evaluatedAt().toString().equals(retained.evaluatedAt()) + || !signedScope + .connectScopeExpiresAt() + .toString() + .equals(retained.connectScopeExpiresAt())) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + } + + private void requireMatchingJoinIntent( + JoinOperation operation, String requestId, String callerBinding, VerifiedJoinScope scope) { + String expectedIntentDigest = AccountJoinDigest.intent(requestId, scope, callerBinding); + if (operation.accountId() != scope.accountId() + || !operation.realmId().equals(scope.realmId()) + || !operation.callerBinding().equals(callerBinding) + || !operation.scopeTokenHash().equals(AccountJoinDigest.tokenHash(scope.connectScopeId())) + || !operation.connectScopeDigest().equals(scope.snapshotDigest()) + || operation.intentDigestVersion() != 1 + || !operation.intentDigest().equals(expectedIntentDigest)) { + throw new AuthenticationException( + "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); + } + } + + private JoinPublicProductionResult replayJoinOperation( + JoinOperation operation, String callerBinding, VerifiedJoinScope scope) { + if (operation.requestDigest() != null) { + JoinEvaluation evaluation = evaluateJoin(scope); + if (evaluation.failureCode() != null) { + throw new AuthenticationException( + evaluation.failureCode(), "Current JOIN authority could not be revalidated"); + } + if (!"AVAILABLE".equals(evaluation.authorityAvailability())) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Current JOIN policy could not be revalidated"); + } + String currentDigest = + AccountJoinDigest.request( + scope, callerBinding, evaluation.allowPublicJoin(), evaluation.entitlementVersion()); + if (!Integer.valueOf(1).equals(operation.requestDigestVersion()) + || !operation.requestDigest().equals(currentDigest)) { + throw new AuthenticationException("IDEMPOTENCY_CONFLICT", "JOIN request digest changed"); + } + } + return resultFromJoinOperation(operation, true); + } + + private JoinPublicProductionResult resultFromJoinOperation( + JoinOperation operation, boolean replayed) { + return new JoinPublicProductionResult( + "COMMITTED".equals(operation.status()), + operation.outcome(), + operation.accountId(), + operation.tenantId(), + operation.membershipId() == null ? 0L : operation.membershipId(), + operation.membershipVersion() == null ? 0L : operation.membershipVersion(), + operation.membershipAuthorityGeneration() == null + ? 0L + : operation.membershipAuthorityGeneration(), + replayed); + } + + private Optional safeFindJoinOperation(String requestId) { + try { + return accountJoinOperationRepository.find(requestId); + } catch (RuntimeException ignored) { + return Optional.empty(); + } + } + + private void recordJoinAttemptFailureAfterRollback(String requestId, String failureCode) { + String availability = + "ENTITLEMENT_UNAVAILABLE".equals(failureCode) ? "UNAVAILABLE" : "NOT_EVALUATED"; + try { + joinTransactionTemplate.execute( + transactionStatus -> { + accountJoinOperationRepository + .findForUpdate(requestId) + .ifPresent( + operation -> { + if ("PENDING".equals(operation.status())) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, availability, failureCode); + } + }); + return null; + }); + } catch (RuntimeException ignored) { + // The durable intent stays pending, and the caller retries the same request ID. + } + } + + private void validateDirectTextJoinScope( + DirectTextCallerContext caller, VerifiedJoinScope scope) { + if (caller != null + && (caller.accountId() != scope.accountId() + || caller.tenantId() != scope.tenantId() + || !caller.realmId().equals(scope.realmId()) + || caller.gameInstanceId() != scope.gameInstanceId() + || !caller.playableStateNamespaceId().equals(scope.playableStateNamespaceId()) + || !caller.playableStateScope().equals(scope.playableStateScope()))) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + } + + private JoinEvaluation evaluateJoin(VerifiedJoinScope scope) { + return evaluateJoin( + new ConnectScopeContext( + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + Instant.parse(scope.evaluatedAt()), + Instant.parse(scope.connectScopeExpiresAt()))); + } + + private JoinEvaluation evaluateJoin(ConnectScopeContext scope) { + RuntimeRealmTarget target; + try { + target = requireCurrentConnectScopeTarget(scope); + } catch (AuthenticationException ex) { + if ("CONNECT_SCOPE_MISMATCH".equals(ex.getCode()) + || "ADMISSION_POINTER_UNAVAILABLE".equals(ex.getCode())) { + return new JoinEvaluation("NOT_EVALUATED", null, null, false, ex.getCode()); + } + throw ex; + } + if (!isPublicProductionRealm(target)) { + return new JoinEvaluation( + "NOT_EVALUATED", null, null, false, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + } + try { + RuntimeEntitlementsDto entitlement = lockedJoinEntitlement(scope.tenantId()); + return new JoinEvaluation( + "AVAILABLE", + entitlement.allowPublicJoin(), + entitlement.entitlementVersion(), + entitlement.gameplayAvailable(), + null); + } catch (AuthenticationException ex) { + if ("ENTITLEMENT_UNAVAILABLE".equals(ex.getCode())) { + return new JoinEvaluation("UNAVAILABLE", null, null, false, ex.getCode()); + } + throw ex; + } + } + + private record JoinEvaluation( + String authorityAvailability, + Boolean allowPublicJoin, + Long entitlementVersion, + boolean gameplayAvailable, + String failureCode) {} + + private RuntimeEntitlementsDto lockedJoinEntitlement(long tenantId) { + List rows = + subscriptionRepository.findByTenantIdForUpdate(tenantId); + if (rows.size() != 1) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous"); + } + var subscription = rows.getFirst(); + if (subscription.getEntitlementVersion() <= 0L) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Entitlement version is missing"); + } + return new RuntimeEntitlementsDto( + tenantId, + isGameplayAvailableStatus(subscription.getStatus()), + isPublicJoinAllowedStatus(subscription.getStatus()), + subscription.getEntitlementVersion(), + subscription.getEntitlementVersion(), + Instant.now().toString()); + } + @Override @Transactional(readOnly = true) @Timed(value = "account.connect_token") @@ -517,6 +1046,12 @@ private ConnectTokenResult issueConnectTokenFresh( getTenantMembershipForRuntime( bootstrapContext.accountId(), scopeContext.tenantId(), request.requestId()); + if (membership.membershipExists() + && !"ACTIVE".equals(membership.membershipLifecycleState()) + && !"INACTIVE".equals(membership.membershipLifecycleState())) { + throw new AuthenticationException( + "CONNECT_TOKEN_REJECTED", "Membership authority requires reconciliation"); + } if (membership.membershipExists() && !membership.gameplayAdmissionAllowed()) { throw new AuthenticationException( "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); @@ -625,7 +1160,9 @@ public RuntimeMembershipDto getTenantMembershipForRuntime( tenantId, membership.isPresent(), membership.map(AccountTenantMembership::isGameplayAdmissionAllowed).orElse(false), - membership.map(AccountTenantMembership::getId).orElse(0L), + membership.map(AccountTenantMembership::getMembershipVersion).orElse(0L), + membership.map(AccountTenantMembership::getLifecycleState).orElse("MISSING"), + membership.map(AccountTenantMembership::getMembershipAuthorityGeneration).orElse(0L), Instant.now().toString()); } @@ -714,7 +1251,7 @@ public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, Str subscriptions.getFirst(); boolean gameplayAvailable = isGameplayAvailableStatus(subscription.getStatus()); boolean allowPublicJoin = isPublicJoinAllowedStatus(subscription.getStatus()); - long version = subscription.getId() == null ? 0L : subscription.getId(); + long version = subscription.getEntitlementVersion(); return new RuntimeEntitlementsDto( tenantId, gameplayAvailable, allowPublicJoin, version, version, Instant.now().toString()); } @@ -756,10 +1293,9 @@ private RuntimeRealmTarget requireRealmTarget( Long expectedTenantId, String worldSlug, String realmSlug) { try { List candidates = - gameSessionClient.listGameplayRealms(worldSlug).stream() - .filter(realm -> java.util.Objects.equals(worldSlug, realm.getWorldSlug())) - .filter(realm -> java.util.Objects.equals(realmSlug, realm.getRealmSlug())) - .map(this::readRuntimeRealmTarget) + listRuntimeRealmTargets(worldSlug, realmSlug).stream() + .filter(realm -> java.util.Objects.equals(worldSlug, realm.worldSlug())) + .filter(realm -> java.util.Objects.equals(realmSlug, realm.realmSlug())) .filter(realm -> expectedTenantId == null || realm.tenantId() == expectedTenantId) .toList(); if (candidates.size() != 1) { @@ -770,6 +1306,14 @@ private RuntimeRealmTarget requireRealmTarget( readRuntimeRealmTarget( gameSessionClient.getAdmissionPointer(candidate.tenantId(), worldSlug, realmSlug)); if (realm.tenantId() != candidate.tenantId() + || !realm.realmId().equals(candidate.realmId()) + || !realm.playableStateNamespaceId().equals(candidate.playableStateNamespaceId()) + || !realm.stateScope().equals(candidate.stateScope()) + || realm.gameInstanceId() != candidate.gameInstanceId() + || realm.visible() != candidate.visible() + || realm.publicProductionRealm() != candidate.publicProductionRealm() + || realm.catalogRevision() != candidate.catalogRevision() + || realm.pointerVersion() != candidate.pointerVersion() || !java.util.Objects.equals(worldSlug, realm.worldSlug()) || !java.util.Objects.equals(realmSlug, realm.realmSlug())) { throw new AuthenticationException( @@ -777,29 +1321,104 @@ private RuntimeRealmTarget requireRealmTarget( "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"); } return realm; - } catch (IllegalArgumentException | IllegalStateException ex) { - throw new AuthenticationException( - "ADMISSION_POINTER_UNAVAILABLE", - "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", - ex); + } catch (AuthenticationException ex) { + throw ex; + } catch (RuntimeException ex) { + throw admissionPointerUnavailable(ex); } } - private boolean hasAdmissibleRealm(BootstrapContext bootstrapContext, String worldSlug) { + private List listGameplayWorlds() { try { - return gameSessionClient.listGameplayRealms(worldSlug).stream() - .map(realm -> readAdmissibleDiscoveryRealm(bootstrapContext, realm)) - .flatMap(Optional::stream) - .findAny() - .isPresent(); - } catch (IllegalStateException ex) { - return false; + List worlds = + gameSessionClient.listGameplayWorlds(); + if (worlds == null) { + throw new IllegalStateException("Gameplay world discovery returned no authority"); + } + return worlds; + } catch (AuthenticationException ex) { + throw ex; + } catch (RuntimeException ex) { + throw admissionPointerUnavailable(ex); } } - private Optional readAdmissibleDiscoveryRealm( + private List listAdmissibleRuntimeRealmTargets( + BootstrapContext bootstrapContext, String worldSlug) { + try { + List realms = + gameSessionClient.listGameplayRealms(worldSlug); + if (realms == null) { + throw new IllegalStateException("Gameplay realm discovery returned no authority"); + } + List targets = + realms.stream() + .map(realm -> readReachableDiscoveryRealm(bootstrapContext, realm)) + .flatMap(Optional::stream) + .toList(); + validatePublicRealmCardinality(targets); + return targets.stream() + .filter(realm -> isRealmAdmissible(bootstrapContext, realm)) + .toList(); + } catch (AuthenticationException ex) { + throw ex; + } catch (RuntimeException ex) { + throw admissionPointerUnavailable(ex); + } + } + + private List listRuntimeRealmTargets( + String worldSlug, String selectedRealmSlug) { + try { + List realms = + gameSessionClient.listGameplayRealms(worldSlug); + if (realms == null) { + throw new IllegalStateException("Gameplay realm discovery returned no authority"); + } + var realmStream = realms.stream(); + if (selectedRealmSlug != null) { + realmStream = + realmStream.filter( + realm -> + realm != null + && java.util.Objects.equals(selectedRealmSlug, realm.getRealmSlug())); + } + List targets = realmStream.map(this::readRuntimeRealmTarget).toList(); + validatePublicRealmCardinality(targets); + return targets; + } catch (AuthenticationException ex) { + throw ex; + } catch (RuntimeException ex) { + throw admissionPointerUnavailable(ex); + } + } + + private void validatePublicRealmCardinality(List realms) { + // The RPC is world-local: zero local public realms may be a valid private-only world when the + // tenant's public realm is in another world. Game Session owns the tenant-global zero check; + // Account can defensively reject only duplicate visible public targets returned here. + Map visiblePublicRealmCounts = + realms.stream() + .filter(this::isPublicProductionRealm) + .collect( + java.util.stream.Collectors.groupingBy( + RuntimeRealmTarget::tenantId, java.util.stream.Collectors.counting())); + if (realms.stream() + .map(RuntimeRealmTarget::tenantId) + .distinct() + .anyMatch(tenantId -> visiblePublicRealmCounts.getOrDefault(tenantId, 0L) > 1L)) { + throw admissionPointerUnavailable( + new IllegalStateException("Public production realm authority is ambiguous")); + } + } + + private Optional readReachableDiscoveryRealm( BootstrapContext bootstrapContext, net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { + if (realm == null) { + throw admissionPointerUnavailable( + new IllegalArgumentException("Gameplay realm discovery returned a null realm")); + } final RuntimeRealmTarget target; try { target = readRuntimeRealmTarget(realm); @@ -809,7 +1428,7 @@ private Optional readAdmissibleDiscoveryRealm( } return Optional.empty(); } - return isRealmAdmissible(bootstrapContext, target) ? Optional.of(target) : Optional.empty(); + return Optional.of(target); } private boolean isMalformedRealmReachable( @@ -845,6 +1464,10 @@ private AuthenticationException admissionPointerUnavailable(Throwable cause) { cause); } + private boolean hasAdmissibleRealm(BootstrapContext bootstrapContext, String worldSlug) { + return !listAdmissibleRuntimeRealmTargets(bootstrapContext, worldSlug).isEmpty(); + } + private boolean isRealmAdmissible(BootstrapContext bootstrapContext, RuntimeRealmTarget realm) { long tenantId = realm.tenantId(); if (!isPublicProductionRealm(realm)) { @@ -877,34 +1500,70 @@ private String mintConnectScopeId( return mintToken( String.valueOf(bootstrapContext.accountId()), expirationMs, - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - bootstrapContext.accountId(), - "tenantId", - realm.tenantId(), - "worldSlug", - realm.worldSlug(), - "realmSlug", - realm.realmSlug(), - "gameInstanceId", - realm.gameInstanceId(), - "pointerVersion", - realm.pointerVersion(), - "evaluatedAt", - evaluatedAt.toString(), - "connectScopeExpiresAt", - expiresAt.toString(), - "jti", - stableId( - "connect-scope", - bootstrapContext.accountId(), - Long.toString(realm.tenantId()), - realm.worldSlug(), - realm.realmSlug(), - realm.pointerVersion(), - evaluatedAt.toString()))); + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", bootstrapContext.accountId()), + Map.entry("tenantId", realm.tenantId()), + Map.entry("realmId", realm.realmId().toString()), + Map.entry("worldSlug", realm.worldSlug()), + Map.entry("realmSlug", realm.realmSlug()), + Map.entry("playableStateNamespaceId", realm.playableStateNamespaceId()), + Map.entry("playableStateScope", realm.stateScope()), + Map.entry("gameInstanceId", realm.gameInstanceId()), + Map.entry("catalogRevision", realm.catalogRevision()), + Map.entry("pointerVersion", realm.pointerVersion()), + Map.entry("evaluatedAt", evaluatedAt.toString()), + Map.entry("connectScopeExpiresAt", expiresAt.toString()), + Map.entry( + "jti", + stableId( + "connect-scope", + bootstrapContext.accountId(), + Long.toString(realm.tenantId()), + realm.worldSlug(), + realm.realmSlug(), + realm.pointerVersion(), + evaluatedAt.toString())))); + } + + private String mintAndRetainConnectScope( + BootstrapContext caller, RuntimeRealmTarget realm, Instant evaluatedAt, Instant expiresAt) { + String connectScopeId = mintConnectScopeId(caller, realm, evaluatedAt, expiresAt); + if (isPublicProductionRealm(realm)) { + VerifiedJoinScope pending = + new VerifiedJoinScope( + connectScopeId, + caller.accountId(), + realm.tenantId(), + realm.realmId(), + realm.worldSlug(), + realm.realmSlug(), + realm.playableStateNamespaceId(), + realm.stateScope(), + realm.gameInstanceId(), + realm.catalogRevision(), + realm.pointerVersion(), + evaluatedAt.toString(), + expiresAt.toString(), + ""); + accountConnectScopeRepository.insert( + new VerifiedJoinScope( + pending.connectScopeId(), + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.worldSlug(), + pending.realmSlug(), + pending.playableStateNamespaceId(), + pending.playableStateScope(), + pending.gameInstanceId(), + pending.catalogRevision(), + pending.pointerVersion(), + pending.evaluatedAt(), + pending.connectScopeExpiresAt(), + AccountJoinDigest.scope(pending))); + } + return connectScopeId; } private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { @@ -920,16 +1579,25 @@ private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { JwtClaims.requireSignedGameplayRoutingClaims( claims, "signed token account subject mismatch"); Instant connectScopeExpiresAt = parseInstant(claims.get("connectScopeExpiresAt")); + Instant evaluatedAt = parseInstant(claims.get("evaluatedAt")); if (connectScopeExpiresAt == null) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); } + if (evaluatedAt == null) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } return new ConnectScopeContext( routingClaims.accountId(), routingClaims.tenantId(), + requireCanonicalRealmId(claims.get("realmId")), routingClaims.worldSlug(), routingClaims.realmSlug(), + JwtClaims.requireText(claims.get("playableStateNamespaceId"), "playableStateNamespaceId"), + JwtClaims.requireText(claims.get("playableStateScope"), "playableStateScope"), routingClaims.gameInstanceId(), + requirePositiveLong(claims.get("catalogRevision"), "catalogRevision"), routingClaims.pointerVersion(), + evaluatedAt, connectScopeExpiresAt); } catch (IllegalArgumentException ex) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE, ex); @@ -985,7 +1653,11 @@ private RuntimeRealmTarget requireCurrentConnectScopeTarget(ConnectScopeContext requireRealmTarget( scopeContext.tenantId(), scopeContext.worldSlug(), scopeContext.realmSlug()); if (currentRealm.tenantId() != scopeContext.tenantId() + || !currentRealm.realmId().equals(scopeContext.realmId()) + || !currentRealm.playableStateNamespaceId().equals(scopeContext.playableStateNamespaceId()) + || !currentRealm.stateScope().equals(scopeContext.playableStateScope()) || currentRealm.gameInstanceId() != scopeContext.gameInstanceId() + || currentRealm.catalogRevision() != scopeContext.catalogRevision() || currentRealm.pointerVersion() != scopeContext.pointerVersion()) { throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); } @@ -1149,13 +1821,17 @@ private String mintToken(String subject, long expirationMs, Map } private Map authenticationTokenClaims(String audience, Account account) { + List globalRoles = + account.getRole() == null || account.getRole().isBlank() + ? List.of() + : List.of(account.getRole()); return Map.of( "aud", audience, "accountId", account.getId(), "globalRoles", - List.of(account.getRole()), + globalRoles, "jti", UUID.randomUUID().toString()); } @@ -1210,14 +1886,6 @@ private boolean isPublicJoinAllowedStatus(String status) { }; } - private void safeLogAccountCreation(Long tenantId, Long accountId) { - try { - loggingAdminClient.logAccountCreation(tenantId, accountId); - } catch (RuntimeException ex) { - logger.warn("Account creation logging failed for account {}", accountId, ex); - } - } - @Override @Transactional(readOnly = true) @Timed(value = "account.get_profile") @@ -1328,6 +1996,11 @@ public TenantDataExportDto exportTenantData(Long tenantId, Long accountId) { @Timed(value = "account.delete") public void deleteAccount(Long accountId) { Account account = requireAccount(accountId); + if (accountJoinOperationRepository.hasRetainedOperation(accountId)) { + throw new AccountLifecycleException( + "ACCOUNT_DELETE_JOIN_RECEIPT_RETAINED", + "Account JOIN receipts require retention and deletion reconciliation"); + } List subscriptions = subscriptionRepository.findByAccountId(accountId); Optional blockingSubscription = @@ -1589,6 +2262,14 @@ public void afterCommit() { private record BootstrapContext(long accountId) {} + private record JoinAuditPayload( + long accountId, + long tenantId, + String worldSlug, + String realmSlug, + long membershipVersion, + String requestId) {} + private ConnectTokenResult replayedConnectTokenResult(ConnectTokenResult result) { return new ConnectTokenResult( result.accountId(), @@ -1608,7 +2289,10 @@ private RuntimeRealmTarget readRuntimeRealmTarget( net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { return buildRuntimeRealmTarget( realm.getTenantId(), + realm.getRealmId(), + realm.getPlayableStateNamespaceId(), realm.getGameInstanceId(), + realm.getCatalogRevision(), realm.getPointerVersion(), realm.getWorldSlug(), realm.getRealmSlug(), @@ -1624,7 +2308,10 @@ private RuntimeRealmTarget readRuntimeRealmTarget( net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer realm) { return buildRuntimeRealmTarget( realm.getTenantId(), + realm.getRealmId(), + realm.getPlayableStateNamespaceId(), realm.getGameInstanceId(), + realm.getCatalogRevision(), realm.getPointerVersion(), realm.getWorldSlug(), realm.getRealmSlug(), @@ -1638,7 +2325,10 @@ private RuntimeRealmTarget readRuntimeRealmTarget( private RuntimeRealmTarget buildRuntimeRealmTarget( String tenantIdText, + String realmIdText, + String playableStateNamespaceId, String gameInstanceIdText, + long catalogRevision, long pointerVersion, String worldSlug, String realmSlug, @@ -1649,7 +2339,14 @@ private RuntimeRealmTarget buildRuntimeRealmTarget( boolean requiresCharacterSelection, String displayName) { long tenantId = requirePositiveLong(tenantIdText, "tenantId"); + UUID realmId = requireCanonicalRealmId(realmIdText); long gameInstanceId = requirePositiveLong(gameInstanceIdText, "gameInstanceId"); + if (!StringUtils.hasText(playableStateNamespaceId)) { + throw new IllegalArgumentException("playableStateNamespaceId is required"); + } + if (catalogRevision <= 0) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } if (pointerVersion <= 0) { throw new IllegalArgumentException("pointerVersion must be positive"); } @@ -1664,10 +2361,13 @@ private RuntimeRealmTarget buildRuntimeRealmTarget( } return new RuntimeRealmTarget( tenantId, + realmId, + playableStateNamespaceId, gameInstanceId, worldSlug, realmSlug, pointerVersion, + catalogRevision, visible, publicProductionRealm, stateScope, @@ -1690,21 +2390,44 @@ private long requirePositiveLong(Object value, String field) { return JwtClaims.requireLong(value, field, false); } + private UUID requireCanonicalRealmId(Object value) { + if (!(value instanceof String text) || text.isBlank()) { + throw new IllegalArgumentException("realmId must be a canonical UUID"); + } + try { + UUID realmId = UUID.fromString(text); + if (!realmId.toString().equals(text)) { + throw new IllegalArgumentException("realmId must be a canonical UUID"); + } + return realmId; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("realmId must be a canonical UUID", ex); + } + } + private record ConnectScopeContext( long accountId, long tenantId, + UUID realmId, String worldSlug, String realmSlug, + String playableStateNamespaceId, + String playableStateScope, long gameInstanceId, + long catalogRevision, long pointerVersion, + Instant evaluatedAt, Instant connectScopeExpiresAt) {} private record RuntimeRealmTarget( long tenantId, + UUID realmId, + String playableStateNamespaceId, long gameInstanceId, String worldSlug, String realmSlug, long pointerVersion, + long catalogRevision, boolean visible, boolean publicProductionRealm, String stateScope, diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 8ff9882a2d..9ac4dcca75 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -74,6 +74,8 @@ firemud: - account.v1.AccountService/Ping - account.v1.AccountService/GetTenantMembershipForRuntime - account.v1.AccountService/GetTenantEntitlementsForRuntime + - account.v1.AccountService/IssueDirectTextConnectScope + - account.v1.AccountService/JoinPublicProductionMembership 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/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 14e509c126..320f48b2c5 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -96,6 +96,8 @@ firemud: - account.v1.AccountService/Ping - account.v1.AccountService/GetTenantMembershipForRuntime - account.v1.AccountService/GetTenantEntitlementsForRuntime + - account.v1.AccountService/IssueDirectTextConnectScope + - account.v1.AccountService/JoinPublicProductionMembership management: endpoints: diff --git a/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql b/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql new file mode 100644 index 0000000000..7a9d11b724 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql @@ -0,0 +1,270 @@ +-- The legacy tenant column is retained as source evidence. New global accounts +-- must not silently acquire tenant 1 through the V3 default. +CREATE TABLE account_legacy_tenant_sources ( + account_id BIGINT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE, + legacy_tenant_id BIGINT NOT NULL, + matching_membership_id BIGINT, + matching_membership_admission_allowed BOOLEAN, + profile_tenant_count BIGINT NOT NULL, + matching_profile_count BIGINT NOT NULL, + disposition VARCHAR(32) NOT NULL, + captured_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_legacy_tenant_sources_disposition_check + CHECK (disposition IN ('UNVERIFIED', 'TENANT_MISMATCH', 'CONFLICT')) +); + +INSERT INTO account_legacy_tenant_sources ( + account_id, + legacy_tenant_id, + matching_membership_id, + matching_membership_admission_allowed, + profile_tenant_count, + matching_profile_count, + disposition +) +SELECT a.id, + a.tenant_id, + m.id, + m.gameplay_admission_allowed, + (SELECT COUNT(*) FROM profiles p WHERE p.account_id = a.id), + (SELECT COUNT(*) FROM profiles p WHERE p.account_id = a.id AND p.tenant_id = a.tenant_id), + CASE + WHEN EXISTS ( + SELECT 1 FROM account_tenant_membership other + WHERE other.account_id = a.id AND other.tenant_id <> a.tenant_id + ) OR EXISTS ( + SELECT 1 FROM profiles p + WHERE p.account_id = a.id AND p.tenant_id <> a.tenant_id + ) THEN 'TENANT_MISMATCH' + WHEN m.id IS NULL THEN 'CONFLICT' + ELSE 'UNVERIFIED' + END +FROM accounts a +LEFT JOIN account_tenant_membership m + ON m.account_id = a.id AND m.tenant_id = a.tenant_id; + +CREATE TABLE account_legacy_membership_sources ( + membership_id BIGINT PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + tenant_id BIGINT NOT NULL, + original_gameplay_admission_allowed BOOLEAN NOT NULL, + matches_account_legacy_tenant BOOLEAN NOT NULL, + disposition VARCHAR(32) NOT NULL DEFAULT 'UNVERIFIED', + captured_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_legacy_membership_disposition_check + CHECK (disposition IN ('UNVERIFIED', 'VERIFIED', 'QUARANTINED')) +); + +INSERT INTO account_legacy_membership_sources ( + membership_id, account_id, tenant_id, original_gameplay_admission_allowed, + matches_account_legacy_tenant +) +SELECT m.id, m.account_id, m.tenant_id, m.gameplay_admission_allowed, + m.tenant_id = a.tenant_id +FROM account_tenant_membership m +JOIN accounts a ON a.id = m.account_id; + +CREATE TABLE account_legacy_profile_sources ( + profile_id BIGINT PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + tenant_id BIGINT NOT NULL, + matches_account_legacy_tenant BOOLEAN NOT NULL, + disposition VARCHAR(32) NOT NULL DEFAULT 'UNVERIFIED', + captured_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_legacy_profile_disposition_check + CHECK (disposition IN ('UNVERIFIED', 'VERIFIED', 'QUARANTINED')) +); + +INSERT INTO account_legacy_profile_sources ( + profile_id, account_id, tenant_id, matches_account_legacy_tenant +) +SELECT p.id, p.account_id, p.tenant_id, p.tenant_id = a.tenant_id +FROM profiles p +JOIN accounts a ON a.id = p.account_id; + +ALTER TABLE accounts ALTER COLUMN tenant_id DROP DEFAULT; +ALTER TABLE accounts ALTER COLUMN tenant_id DROP NOT NULL; +ALTER TABLE accounts ALTER COLUMN role DROP DEFAULT; +ALTER TABLE accounts ALTER COLUMN role DROP NOT NULL; + +-- A subscription row ID is not a policy revision. Retained policy begins at +-- version one and supported writers advance the monotonic value. +ALTER TABLE subscription ADD COLUMN entitlement_version BIGINT NOT NULL DEFAULT 1; +ALTER TABLE subscription ADD CONSTRAINT subscription_entitlement_version_positive + CHECK (entitlement_version > 0); + +-- No pre-JOIN writer proves player intent. Retain every old membership row, +-- but quarantine its authority until an explicit reconciliation disposition. +ALTER TABLE account_tenant_membership + ADD COLUMN lifecycle_state VARCHAR(32), + ADD COLUMN membership_version BIGINT, + ADD COLUMN membership_authority_generation BIGINT, + ADD COLUMN authority_provenance VARCHAR(32); + +UPDATE account_tenant_membership +SET lifecycle_state = 'LEGACY_UNVERIFIED', + membership_version = 1, + membership_authority_generation = 1, + authority_provenance = 'LEGACY_UNVERIFIED', + gameplay_admission_allowed = FALSE; + +ALTER TABLE account_tenant_membership ALTER COLUMN lifecycle_state SET NOT NULL; +ALTER TABLE account_tenant_membership ALTER COLUMN membership_version SET NOT NULL; +ALTER TABLE account_tenant_membership ALTER COLUMN membership_authority_generation SET NOT NULL; +ALTER TABLE account_tenant_membership ALTER COLUMN authority_provenance SET NOT NULL; +ALTER TABLE account_tenant_membership ADD CONSTRAINT account_membership_lifecycle_check + CHECK (lifecycle_state IN ('ACTIVE', 'INACTIVE', 'LEGACY_UNVERIFIED')); +ALTER TABLE account_tenant_membership ADD CONSTRAINT account_membership_provenance_check + CHECK (authority_provenance IN ('EXPLICIT_JOIN', 'LEGACY_UNVERIFIED', 'SEEDED_DEMO')); +ALTER TABLE account_tenant_membership ADD CONSTRAINT account_membership_versions_positive_check + CHECK (membership_version > 0 AND membership_authority_generation > 0); +ALTER TABLE account_tenant_membership ADD CONSTRAINT account_membership_unverified_not_admitting_check + CHECK (lifecycle_state <> 'LEGACY_UNVERIFIED' OR gameplay_admission_allowed = FALSE); + +CREATE TABLE account_connect_scope_records ( + scope_token_hash VARCHAR(71) PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + target_class VARCHAR(20) NOT NULL, + tenant_id BIGINT NOT NULL, + realm_id UUID NOT NULL, + world_slug VARCHAR(128) NOT NULL, + realm_slug VARCHAR(128) NOT NULL, + playable_state_namespace_id VARCHAR(128) NOT NULL, + playable_state_scope VARCHAR(32) NOT NULL, + game_instance_id BIGINT NOT NULL, + catalog_revision BIGINT NOT NULL, + pointer_version BIGINT NOT NULL, + evaluated_at VARCHAR(40) NOT NULL, + connect_scope_expires_at VARCHAR(40) NOT NULL, + playtest_lifecycle_id VARCHAR(128), + playtest_state_generation BIGINT, + snapshot_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_connect_scope_target_check + CHECK ((target_class = 'PUBLIC_PRODUCTION' + AND playtest_lifecycle_id IS NULL AND playtest_state_generation IS NULL) + OR (target_class = 'NON_PUBLIC' + AND playtest_lifecycle_id IS NOT NULL AND playtest_state_generation > 0)), + CONSTRAINT account_connect_scope_positive_check + CHECK (tenant_id > 0 AND game_instance_id > 0 + AND catalog_revision > 0 AND pointer_version > 0) +); + +CREATE INDEX idx_account_connect_scope_account_expiry + ON account_connect_scope_records(account_id, connect_scope_expires_at); + +CREATE TABLE account_join_operations ( + request_id VARCHAR(128) PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id), + tenant_id BIGINT NOT NULL, + verified_caller_binding VARCHAR(128) NOT NULL, + scope_token_hash VARCHAR(71) NOT NULL, + connect_scope_digest VARCHAR(71) NOT NULL, + world_slug VARCHAR(128) NOT NULL, + realm_slug VARCHAR(128) NOT NULL, + realm_id UUID NOT NULL, + playable_state_namespace_id VARCHAR(128) NOT NULL, + playable_state_scope VARCHAR(32) NOT NULL, + game_instance_id BIGINT NOT NULL, + catalog_revision BIGINT NOT NULL, + pointer_version BIGINT NOT NULL, + intent_digest_version INTEGER NOT NULL, + intent_digest VARCHAR(71) NOT NULL, + entitlement_version BIGINT, + allow_public_join BOOLEAN, + entitlement_authority_availability VARCHAR(16) NOT NULL DEFAULT 'NOT_EVALUATED', + caller_bound_authority_invalidated BOOLEAN NOT NULL, + request_digest_version INTEGER, + request_digest VARCHAR(71), + last_attempt_failure_code VARCHAR(64), + last_attempt_authority_availability VARCHAR(16) NOT NULL DEFAULT 'NOT_EVALUATED', + status VARCHAR(16) NOT NULL, + outcome VARCHAR(64), + membership_id BIGINT REFERENCES account_tenant_membership(id), + outcome_membership_version BIGINT, + outcome_membership_authority_generation BIGINT, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_join_operation_status_check + CHECK (status IN ('PENDING', 'COMMITTED', 'FAILED')), + CONSTRAINT account_join_operation_positive_versions_check + CHECK (tenant_id > 0 AND game_instance_id > 0 AND catalog_revision > 0 + AND pointer_version > 0 + AND (entitlement_version IS NULL OR entitlement_version > 0)), + CONSTRAINT account_join_operation_policy_evidence_check + CHECK ((entitlement_authority_availability = 'AVAILABLE' + AND entitlement_version IS NOT NULL AND allow_public_join IS NOT NULL) + OR (entitlement_authority_availability IN ('UNAVAILABLE', 'NOT_EVALUATED') + AND entitlement_version IS NULL AND allow_public_join IS NULL)), + CONSTRAINT account_join_last_attempt_availability_check + CHECK (last_attempt_authority_availability IN ('AVAILABLE', 'UNAVAILABLE', 'NOT_EVALUATED')), + CONSTRAINT account_join_intent_digest_version_check + CHECK (intent_digest_version = 1 AND length(intent_digest) = 71 + AND intent_digest LIKE 'sha256:%'), + CONSTRAINT account_join_policy_digest_check + CHECK ((request_digest_version IS NULL AND request_digest IS NULL + AND entitlement_authority_availability <> 'AVAILABLE' + AND entitlement_version IS NULL AND allow_public_join IS NULL) + OR (request_digest_version = 1 AND request_digest IS NOT NULL + AND length(request_digest) = 71 AND request_digest LIKE 'sha256:%' + AND entitlement_authority_availability = 'AVAILABLE' + AND entitlement_version IS NOT NULL AND allow_public_join IS NOT NULL)), + CONSTRAINT account_join_outcome_state_check + CHECK ((status = 'PENDING' AND outcome IS NULL + AND membership_id IS NULL AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL) + OR (status = 'COMMITTED' AND outcome IS NOT NULL + AND membership_id IS NOT NULL + AND outcome_membership_version IS NOT NULL + AND outcome_membership_version > 0 + AND outcome_membership_authority_generation IS NOT NULL + AND outcome_membership_authority_generation > 0) + OR (status = 'FAILED' AND outcome IS NOT NULL + AND membership_id IS NULL AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL)), + CONSTRAINT account_join_pending_attempt_failure_check + CHECK (last_attempt_failure_code IS NULL + OR (status = 'PENDING' AND btrim(last_attempt_failure_code) <> '')), + CONSTRAINT account_join_committed_policy_check + CHECK (status <> 'COMMITTED' OR (entitlement_version IS NOT NULL + AND entitlement_version > 0 AND allow_public_join = TRUE + AND membership_id IS NOT NULL AND outcome_membership_version IS NOT NULL + AND outcome_membership_version > 0 + AND outcome_membership_authority_generation IS NOT NULL + AND outcome_membership_authority_generation > 0)) +); + +CREATE INDEX idx_account_join_operations_account_tenant + ON account_join_operations(account_id, tenant_id); + +CREATE TABLE account_audit_outbox ( + audit_event_id UUID PRIMARY KEY, + scope VARCHAR(8) NOT NULL, + tenant_id BIGINT, + producer_service VARCHAR(64) NOT NULL, + event_type VARCHAR(64) NOT NULL, + occurred_at TIMESTAMP NOT NULL, + schema_version INTEGER NOT NULL, + payload_digest_version INTEGER NOT NULL, + payload_digest VARCHAR(71) NOT NULL, + payload TEXT, + receiver_receipt_id VARCHAR(128), + receiver_log_event_id VARCHAR(128), + delivery_status VARCHAR(32) NOT NULL DEFAULT 'PENDING', + last_attempt_at TIMESTAMP, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_audit_outbox_scope_check + CHECK ((scope = 'platform' AND tenant_id IS NULL) + OR (scope = 'tenant' AND tenant_id > 0)), + CONSTRAINT account_audit_outbox_version_check + CHECK (schema_version > 0 AND payload_digest_version = 1), + CONSTRAINT account_audit_outbox_delivery_check + CHECK (delivery_status IN ('PENDING', 'COMMITTED', 'MINIMIZED')), + CONSTRAINT account_audit_outbox_payload_state_check + CHECK ((delivery_status = 'MINIMIZED' AND payload IS NULL) + OR (delivery_status IN ('PENDING', 'COMMITTED') AND payload IS NOT NULL)) +); + +CREATE INDEX idx_account_audit_outbox_pending + ON account_audit_outbox(created_at, audit_event_id) + WHERE delivery_status = 'PENDING'; diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 35419178b4..ecb448c374 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -37,26 +37,20 @@ components: schemas: CreateAccountRequest: type: object - description: Current API shape requires tenantId; target global registration with explicit JOIN remains unimplemented. + description: Creates a global account. Tenant membership and profiles are established separately. properties: - tenantId: - type: integer - format: int64 - minimum: 1 username: type: string email: type: string password: type: string - required: [tenantId, username, email, password] + required: [username, email, password] AccountDto: type: object properties: id: type: integer - tenantId: - type: string username: type: string email: @@ -136,6 +130,35 @@ components: requestId: type: string required: [connectScopeId, requestId] + JoinPublicProductionRequest: + type: object + properties: + connectScopeId: + type: string + description: Account-issued, caller-bound realm discovery scope + requestId: + type: string + description: Stable ID for this explicit join attempt; use a new ID for a new attempt + required: [connectScopeId, requestId] + JoinPublicProductionResult: + type: object + properties: + success: + type: boolean + outcomeCode: + type: string + accountId: + type: integer + tenantId: + type: integer + membershipId: + type: integer + membershipVersion: + type: integer + membershipAuthorityGeneration: + type: integer + replayed: + type: boolean ConnectTokenResponse: type: object properties: @@ -168,11 +191,15 @@ components: type: string BootstrapRealmDto: type: object + required: [worldSlug, realmSlug, realmId] properties: worldSlug: type: string realmSlug: type: string + realmId: + type: string + format: uuid displayName: type: string tenantId: @@ -439,6 +466,34 @@ paths: $ref: '#/components/schemas/ErrorDetail' '401': description: Invalid or expired bootstrap token + /auth/bootstrap/join: + post: + summary: Explicitly join the selected public-production realm from a player-bootstrap scope + operationId: joinPublicProduction + security: + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/JoinPublicProductionRequest' + responses: + '200': + description: Durable membership snapshot after a successful join or exact replay + content: + application/json: + schema: + type: object + properties: + status: + $ref: '#/components/schemas/ResultStatus' + data: + $ref: '#/components/schemas/JoinPublicProductionResult' + error: + $ref: '#/components/schemas/ErrorDetail' + '401': + description: Scope, policy, or membership state denied the join '503': $ref: '#/components/responses/RetryableAuthenticationUnavailable' /auth/connect-token: @@ -560,8 +615,9 @@ paths: description: Invalid request /accounts: post: - summary: Create a new account + summary: Create a new global account operationId: createAccount + description: Registration creates global account and security state only; it does not join a tenant or create a profile. security: [] requestBody: required: true diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index d7f8f2e8c9..7348a5ed68 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -6,6 +6,7 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.util.UUID; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; @@ -13,6 +14,7 @@ import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.HttpTestSupport; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -57,6 +59,7 @@ static void configure(DynamicPropertyRegistry registry) { @LocalServerPort private int port; @Autowired private JwtUtil jwtUtil; + @Autowired private DSLContext dsl; @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameSessionClient gameSessionClient; @@ -69,6 +72,51 @@ void pingEndpointReturnsPong() { assertThat(body).contains("pong"); } + @Test + void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String username = "global-" + suffix; + String email = username + "@example.com"; + HttpRequest request = + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/accounts")) + .header(HttpHeaders.CONTENT_TYPE, "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + "{\"username\":\"" + + username + + "\",\"email\":\"" + + email + + "\",\"password\":\"password123\",\"tenantId\":999}")) + .build(); + + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode()).isEqualTo(200); + Number accountId = + dsl.resultQuery("SELECT id FROM accounts WHERE email = ?", email).fetchOne(0, Number.class); + assertThat(accountId).isNotNull(); + assertThat(dsl.fetchValue("SELECT tenant_id FROM accounts WHERE id = ?", accountId.longValue())) + .isNull(); + assertThat(dsl.fetchValue("SELECT role FROM accounts WHERE id = ?", accountId.longValue())) + .isNull(); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ?", + accountId.longValue())) + .isEqualTo(0L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM profiles WHERE account_id = ?", accountId.longValue())) + .isEqualTo(0L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox " + + "WHERE scope = 'platform' AND tenant_id IS NULL " + + "AND event_type = 'ACCOUNT_REGISTERED' AND payload = ?", + "{\"accountId\":" + accountId.longValue() + "}")) + .isEqualTo(1L); + } + @Test void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws Exception { String token = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index 96242142ea..1b6005e154 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -5,8 +5,13 @@ import java.nio.file.Path; import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.FlywayException; import org.jooq.DSLContext; @@ -21,7 +26,11 @@ import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -30,6 +39,7 @@ @SuppressWarnings("resource") @TestInstance(TestInstance.Lifecycle.PER_CLASS) class AccountRepositoryIntegrationTest { + private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); private static final String MIGRATION_LOCATION = "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); private static final String MIGRATION_PROOF_SCHEMA = "account_migration_proof"; @@ -37,6 +47,8 @@ class AccountRepositoryIntegrationTest { "account_migration_collision_proof"; private static final String PROFILE_IDENTITY_MIGRATION_PROOF_SCHEMA = "account_profile_identity_migration_proof"; + private static final String GLOBAL_REGISTRATION_MIGRATION_PROOF_SCHEMA = + "account_global_registration_migration_proof"; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -61,9 +73,311 @@ void setUpRepository() { @BeforeEach void cleanTables() { + dsl.execute("TRUNCATE TABLE account_audit_outbox"); dsl.execute("TRUNCATE TABLE accounts RESTART IDENTITY CASCADE"); } + @Test + void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + DSLContext transactionAwareDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + AccountJoinOperationRepository joinOperations = + new AccountJoinOperationRepository(transactionAwareDsl); + AccountTenantMembershipRepository memberships = + new AccountTenantMembershipRepository(transactionAwareDsl); + AccountAuditOutboxRepository outbox = new AccountAuditOutboxRepository(transactionAwareDsl); + long accountId = + Objects.requireNonNull( + jdbc.queryForObject( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + Long.class, + "two-phase-join", + "two-phase-join@example.com", + "hash")); + VerifiedJoinScope scope = joinScope(accountId); + String callerBinding = "bootstrap-jti-two-phase"; + String requestId = "join-two-phase-1"; + String intentDigest = AccountJoinDigest.intent(requestId, scope, callerBinding); + + transaction.executeWithoutResult( + status -> joinOperations.insertIntent(requestId, scope, callerBinding, intentDigest)); + + assertThat(joinOperation(joinOperations, requestId).status()).isEqualTo("PENDING"); + assertThat(joinOperation(joinOperations, requestId).realmId()).isEqualTo(REALM_ID); + assertThat(joinOperation(joinOperations, requestId).outcome()).isNull(); + assertThat(joinOperation(joinOperations, requestId).intentDigest()).isEqualTo(intentDigest); + assertThat( + jdbc.queryForObject( + "SELECT realm_id FROM account_join_operations WHERE request_id = ?", + UUID.class, + requestId)) + .isEqualTo(REALM_ID); + assertThat(joinOperation(joinOperations, requestId).requestDigest()).isNull(); + assertThat(joinOperation(joinOperations, requestId).entitlementVersion()).isNull(); + assertThat(joinOperation(joinOperations, requestId).allowPublicJoin()).isNull(); + + String policyDigest = AccountJoinDigest.request(scope, callerBinding, true, 1L); + UUID auditEventId = UUID.randomUUID(); + Account account = new Account(); + account.setId(accountId); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> + commitJoinOutcome( + joinOperations, + memberships, + outbox, + account, + requestId, + scope, + policyDigest, + auditEventId, + true))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("simulate second-transaction rollback"); + + assertThat(joinOperation(joinOperations, requestId).status()).isEqualTo("PENDING"); + assertThat(joinOperation(joinOperations, requestId).outcome()).isNull(); + assertThat(joinOperation(joinOperations, requestId).requestDigest()).isNull(); + assertThat( + jdbc.queryForObject( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + Long.class, + accountId, + scope.tenantId())) + .isZero(); + assertThat( + jdbc.queryForObject( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ?", + Long.class, + auditEventId)) + .isZero(); + + transaction.executeWithoutResult( + status -> + commitJoinOutcome( + joinOperations, + memberships, + outbox, + account, + requestId, + scope, + policyDigest, + auditEventId, + false)); + + assertThat(joinOperation(joinOperations, requestId).status()).isEqualTo("COMMITTED"); + assertThat(joinOperation(joinOperations, requestId).outcome()).isEqualTo("JOINED"); + assertThat(joinOperation(joinOperations, requestId).intentDigest()).isEqualTo(intentDigest); + assertThat(joinOperation(joinOperations, requestId).requestDigest()).isEqualTo(policyDigest); + assertThat(joinOperation(joinOperations, requestId).entitlementVersion()).isEqualTo(1L); + assertThat(joinOperation(joinOperations, requestId).allowPublicJoin()).isEqualTo(true); + assertThat( + jdbc.queryForObject( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ? AND lifecycle_state = 'ACTIVE' AND authority_provenance = 'EXPLICIT_JOIN'", + Long.class, + accountId, + scope.tenantId())) + .isEqualTo(1L); + assertThat( + jdbc.queryForObject( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ? AND delivery_status = 'PENDING'", + Long.class, + auditEventId)) + .isEqualTo(1L); + } + + @Test + void minimizedAuditReceiptClearsPayloadAndRetainsCompactIdentity() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + AccountAuditOutboxRepository outbox = new AccountAuditOutboxRepository(dsl); + UUID minimizedEventId = UUID.randomUUID(); + String minimizedPayload = "{\"accountId\":42,\"requestId\":\"join-42\"}"; + String minimizedDigest = AccountAuditDigest.ofPayload(minimizedPayload); + UUID committedEventId = UUID.randomUUID(); + String committedPayload = "{\"accountId\":43}"; + + outbox.append( + minimizedEventId, "tenant", 7L, "ACCOUNT_JOINED_PUBLIC_PRODUCTION", minimizedPayload); + outbox.markDelivered(minimizedEventId, "receipt-minimized", "log-minimized", true); + outbox.append(committedEventId, "platform", null, "ACCOUNT_REGISTERED", committedPayload); + outbox.markDelivered(committedEventId, "receipt-committed", "log-committed", false); + + assertThat( + jdbc.queryForObject( + "SELECT payload FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isNull(); + assertThat( + jdbc.queryForObject( + "SELECT scope FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo("tenant"); + assertThat( + jdbc.queryForObject( + "SELECT audit_event_id FROM account_audit_outbox WHERE audit_event_id = ?", + UUID.class, + minimizedEventId)) + .isEqualTo(minimizedEventId); + assertThat( + jdbc.queryForObject( + "SELECT tenant_id FROM account_audit_outbox WHERE audit_event_id = ?", + Long.class, + minimizedEventId)) + .isEqualTo(7L); + assertThat( + jdbc.queryForObject( + "SELECT payload_digest FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo(minimizedDigest); + assertThat( + jdbc.queryForObject( + "SELECT receiver_receipt_id FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo("receipt-minimized"); + assertThat( + jdbc.queryForObject( + "SELECT receiver_log_event_id FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo("log-minimized"); + assertThat( + jdbc.queryForObject( + "SELECT delivery_status FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + minimizedEventId)) + .isEqualTo("MINIMIZED"); + assertThat( + jdbc.queryForObject( + "SELECT payload FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + committedEventId)) + .isEqualTo(committedPayload); + assertThat( + jdbc.queryForObject( + "SELECT delivery_status FROM account_audit_outbox WHERE audit_event_id = ?", + String.class, + committedEventId)) + .isEqualTo("COMMITTED"); + assertThat(outbox.pending(10)) + .noneMatch(envelope -> envelope.auditEventId().equals(minimizedEventId)) + .noneMatch(envelope -> envelope.auditEventId().equals(committedEventId)); + } + + @Test + void connectScopeRepositoryRetainsCanonicalRealmUuidAndDetectsTampering() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + long accountId = + Objects.requireNonNull( + jdbc.queryForObject( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + Long.class, + "scope-uuid", + "scope-uuid@example.com", + "hash")); + AccountConnectScopeRepository scopes = new AccountConnectScopeRepository(dsl); + VerifiedJoinScope scope = joinScope(accountId); + + scopes.insert(scope); + + assertThat(scopes.find(scope.connectScopeId()).orElseThrow().realmId()).isEqualTo(REALM_ID); + UUID changedRealmId = UUID.fromString("57c58f36-c5ea-4aa8-8ef7-91a45e407f01"); + jdbc.update( + "UPDATE account_connect_scope_records SET realm_id = ? WHERE scope_token_hash = ?", + changedRealmId, + AccountJoinDigest.tokenHash(scope.connectScopeId())); + + assertThatThrownBy(() -> scopes.find(scope.connectScopeId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("JOIN scope digest mismatch"); + } + + private void commitJoinOutcome( + AccountJoinOperationRepository joinOperations, + AccountTenantMembershipRepository memberships, + AccountAuditOutboxRepository outbox, + Account account, + String requestId, + VerifiedJoinScope scope, + String policyDigest, + UUID auditEventId, + boolean simulateRollback) { + joinOperations.bindPolicyEvidence(requestId, policyDigest, 1L, true); + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setAccount(account); + membership.setTenantId(scope.tenantId()); + membership.setGameplayAdmissionAllowed(true); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(1L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + memberships.save(membership); + outbox.append( + auditEventId, + "tenant", + scope.tenantId(), + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + "{\"requestId\":\"" + requestId + "\"}"); + joinOperations.finish( + requestId, + "COMMITTED", + "JOINED", + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration()); + if (simulateRollback) { + throw new IllegalStateException("simulate second-transaction rollback"); + } + } + + private AccountJoinOperationRepository.JoinOperation joinOperation( + AccountJoinOperationRepository joinOperations, String requestId) { + return joinOperations.find(requestId).orElseThrow(); + } + + private static VerifiedJoinScope joinScope(long accountId) { + VerifiedJoinScope base = + new VerifiedJoinScope( + "two-phase-connect-scope", + accountId, + 7L, + REALM_ID, + "demo", + "production", + "namespace-44", + "SHARED", + 44L, + 23L, + 17L, + "2026-09-24T10:00:00Z", + "2026-09-24T10:02:00Z", + "unused"); + String digest = AccountJoinDigest.scope(base); + return new VerifiedJoinScope( + base.connectScopeId(), + base.accountId(), + base.tenantId(), + base.realmId(), + base.worldSlug(), + base.realmSlug(), + base.playableStateNamespaceId(), + base.playableStateScope(), + base.gameInstanceId(), + base.catalogRevision(), + base.pointerVersion(), + base.evaluatedAt(), + base.connectScopeExpiresAt(), + digest); + } + @ParameterizedTest @EnumSource( value = AccountLifecycleState.class, @@ -286,6 +600,104 @@ void flywayRejectsRetainedDuplicateProfileTenantIdentityBeforeAddingConstraint() .isEqualTo(2L); } + @Test + void globalRegistrationMigrationPreservesAndQuarantinesUnprovenTenantRows() { + String schema = GLOBAL_REGISTRATION_MIGRATION_PROOF_SCHEMA; + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .target("25") + .load() + .migrate(); + + long legacyAccountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO " + + schema + + ".accounts (username, email, password_hash, tenant_id) " + + "VALUES ('legacy-global', 'legacy-global@example.com', 'hash', 1) RETURNING id")) + .longValue(); + dsl.execute( + "INSERT INTO " + schema + ".profiles (account_id, tenant_id) VALUES (?, ?)", + legacyAccountId, + 7L); + dsl.execute( + "INSERT INTO " + + schema + + ".account_tenant_membership (account_id, tenant_id, gameplay_admission_allowed) " + + "VALUES (?, ?, TRUE)", + legacyAccountId, + 7L); + + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .load() + .migrate(); + + assertThat( + dsl.fetchValue( + "SELECT tenant_id FROM " + schema + ".accounts WHERE id = ?", legacyAccountId)) + .isEqualTo(1L); + assertThat( + dsl.fetchValue( + "SELECT disposition FROM " + + schema + + ".account_legacy_tenant_sources " + + "WHERE account_id = ?", + legacyAccountId)) + .isEqualTo("TENANT_MISMATCH"); + assertThat( + dsl.fetchValue( + "SELECT original_gameplay_admission_allowed FROM " + + schema + + ".account_legacy_membership_sources WHERE account_id = ?", + legacyAccountId)) + .isEqualTo(true); + assertThat( + dsl.fetchValue( + "SELECT gameplay_admission_allowed FROM " + + schema + + ".account_tenant_membership WHERE account_id = ?", + legacyAccountId)) + .isEqualTo(false); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM " + schema + ".profiles WHERE account_id = ?", + legacyAccountId)) + .isEqualTo(1L); + + long newAccountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO " + + schema + + ".accounts (username, email, password_hash) " + + "VALUES ('new-global', 'new-global@example.com', 'hash') RETURNING id")) + .longValue(); + assertThat( + dsl.fetchValue( + "SELECT tenant_id FROM " + schema + ".accounts WHERE id = ?", newAccountId)) + .isNull(); + assertThat( + dsl.fetchValue("SELECT role FROM " + schema + ".accounts WHERE id = ?", newAccountId)) + .isNull(); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM " + + schema + + ".account_tenant_membership WHERE account_id = ?", + newAccountId)) + .isEqualTo(0L); + } + private Account account(String username, String email, AccountLifecycleState lifecycleState) { Account account = new Account(); account.setUsername(username); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index 8427a1ce49..a666f1fdad 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -64,8 +64,7 @@ void clear() { @Test void createAccountReturnsDto() throws Exception { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "password"); + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); AccountDto response = new AccountDto(1L, "demo", "demo@example.com", "player", true); when(accountService.createAccount(request)).thenReturn(response); @@ -81,8 +80,7 @@ void createAccountReturnsDto() throws Exception { @Test void createAccountConflictUsesCanonicalEnvelope() throws Exception { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "password"); + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); when(accountService.createAccount(request)) .thenThrow(new AccountAlreadyExistsException(new RuntimeException("duplicate"))); @@ -97,27 +95,9 @@ void createAccountConflictUsesCanonicalEnvelope() throws Exception { .andExpect(jsonPath("$.error.message").value("Account already exists")); } - @Test - void createAccountRejectsZeroTenantIdBeforeDispatch() throws Exception { - CreateAccountRequest request = - new CreateAccountRequest(0L, "demo", "demo@example.com", "password"); - - mockMvc - .perform( - post("/accounts") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(request))) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("tenantId must be positive")); - - verifyNoInteractions(accountService); - } - @Test void createAccountRetainsMinimumPasswordLength() throws Exception { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "12345"); + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "12345"); mockMvc .perform( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java index 4b9d9e131c..926a4dc7a4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java @@ -170,6 +170,7 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { new BootstrapRealmDto( "demo", "production", + "4c4b57d8-e3a2-48fe-9977-e7df0fdce901", "Live Realm", 1L, 42L, @@ -188,6 +189,7 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) .andExpect(jsonPath("$.data[0].realmSlug").value("production")) + .andExpect(jsonPath("$.data[0].realmId").value("4c4b57d8-e3a2-48fe-9977-e7df0fdce901")) .andExpect(jsonPath("$.data[0].connectScopeId").value("scope-1")); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java index acd3e499da..fda8d4325e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java @@ -56,7 +56,7 @@ void playerBootstrapRemainsPublicInProdProfile() throws Exception { @Test void accountCreationRemainsPublicInProdProfile() throws Exception { CreateAccountRequest request = - new CreateAccountRequest(1L, "demo", "demo@example.com", "swordfish"); + new CreateAccountRequest("demo", "demo@example.com", "swordfish"); when(accountService.createAccount(request)) .thenReturn(new AccountDto(1L, "demo", "demo@example.com", "player", true)); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java new file mode 100644 index 0000000000..0a9a029857 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.accountservice.dto; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AccountJoinDigestTest { + private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); + + @Test + void scopeAndRequestDigestsMatchUtf8CanonicalVectors() { + VerifiedJoinScope scope = scope("scope-token-α", "production"); + + assertEquals( + "sha256:15efd695569eca4a26589922c7ad128c3a2318203d1a2181666cc3ed6650f5b8", + AccountJoinDigest.scope(scope)); + assertEquals( + "sha256:764b03cbe948293517acb4ce201dbd24fc4d2a0a2306e853f2ab0a6c3775a768", + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L)); + assertNotEquals( + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L), + AccountJoinDigest.request(scope, "bootstrap-jti-α", false, 5L)); + assertNotEquals( + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L), + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 6L)); + assertNotEquals( + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L), + AccountJoinDigest.request(scope("scope-token-α", "preview"), "bootstrap-jti-α", true, 5L)); + assertNotEquals( + AccountJoinDigest.request(scope, "bootstrap-jti-α", true, 5L), + AccountJoinDigest.request(withGameInstance(scope, 45L), "bootstrap-jti-α", true, 5L)); + assertNotEquals( + AccountJoinDigest.scope(scope), + AccountJoinDigest.scope( + withRealm(scope, UUID.fromString("57c58f36-c5ea-4aa8-8ef7-91a45e407f01")))); + assertThrows( + IllegalArgumentException.class, + () -> AccountJoinDigest.request(scope, "bootstrap-jti-α", null, null)); + + assertEquals( + "sha256:13445ed45c66f0e149250f4101c95452a74f15e56dbf3b9b271852ff2d058776", + AccountJoinDigest.intent("join-request-α", scope, "bootstrap-jti-α")); + } + + @Test + void canonicalSerializationRejectsAmbiguousValues() { + assertThrows( + IllegalArgumentException.class, + () -> AccountJoinDigest.scope(scope("scope=token", "production"))); + assertThrows( + IllegalArgumentException.class, + () -> AccountJoinDigest.scope(scope("scope-token", "production\nJOIN"))); + assertThrows( + IllegalArgumentException.class, + () -> + AccountJoinDigest.request(scope("scope-token", "production"), "bad=binding", true, 1L)); + assertThrows( + IllegalArgumentException.class, + () -> AccountJoinDigest.request(scope("scope-token", "production"), "caller", true, null)); + } + + private static VerifiedJoinScope withGameInstance(VerifiedJoinScope scope, long gameInstanceId) { + return new VerifiedJoinScope( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + gameInstanceId, + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + scope.snapshotDigest()); + } + + private static VerifiedJoinScope withRealm(VerifiedJoinScope scope, UUID realmId) { + return new VerifiedJoinScope( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + realmId, + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + scope.snapshotDigest()); + } + + private static VerifiedJoinScope scope(String connectScopeId, String realmSlug) { + return new VerifiedJoinScope( + connectScopeId, + 11L, + 7L, + REALM_ID, + "demo", + realmSlug, + "namespace-44", + "SHARED", + 44L, + 23L, + 17L, + "2026-09-24T10:00:00Z", + "2026-09-24T10:02:00Z", + "unused-by-preimage"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java new file mode 100644 index 0000000000..1e7d2fc860 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class AccountAuditDeliveryJobTest { + private final AccountAuditOutboxRepository outbox = + Mockito.mock(AccountAuditOutboxRepository.class); + private final LoggingAdminClient client = Mockito.mock(LoggingAdminClient.class); + private final AccountAuditDeliveryJob job = new AccountAuditDeliveryJob(outbox, client); + + @Test + void marksOnlyAnExactReceiverReceiptDelivered() { + AccountAuditEnvelope envelope = platformRegistration(); + when(outbox.pending(50)).thenReturn(List.of(envelope)); + when(client.deliver(envelope)) + .thenReturn(new LoggingAdminClient.AuditDeliveryResult("receipt-1", "log-1", false)); + + job.deliverPending(); + + verify(outbox).markDelivered(envelope.auditEventId(), "receipt-1", "log-1", false); + verify(outbox, never()).recordAttempt(envelope.auditEventId()); + } + + @Test + void minimizedReceiverReceiptMarksSameIdentityTerminal() { + AccountAuditEnvelope envelope = platformRegistration(); + when(outbox.pending(50)).thenReturn(List.of(envelope)); + when(client.deliver(envelope)) + .thenReturn(new LoggingAdminClient.AuditDeliveryResult("receipt-2", "log-2", true)); + + job.deliverPending(); + + verify(outbox).markDelivered(envelope.auditEventId(), "receipt-2", "log-2", true); + verify(outbox, never()).recordAttempt(envelope.auditEventId()); + } + + @Test + void unavailableReceiverKeepsSameEnvelopePending() { + AccountAuditEnvelope envelope = platformRegistration(); + when(outbox.pending(50)).thenReturn(List.of(envelope)); + when(client.deliver(envelope)).thenThrow(new IllegalStateException("unavailable")); + + job.deliverPending(); + + verify(outbox).recordAttempt(envelope.auditEventId()); + verify(outbox, never()).markDelivered(envelope.auditEventId(), "receipt-1", "log-1", false); + } + + @Test + void digestBindsExactUtf8PayloadBytes() { + assertEquals( + "sha256:eee0f882a1fae6d1435a03d9e9508a3972f0c1f10495b4e3d5e388cebced63ef", + AccountAuditDigest.ofPayload("{\"accountId\":1}")); + assertNotEquals( + AccountAuditDigest.ofPayload("{\"accountId\":1}"), + AccountAuditDigest.ofPayload("{\"accountId\": 1}")); + } + + private static AccountAuditEnvelope platformRegistration() { + String payload = "{\"accountId\":1}"; + return new AccountAuditEnvelope( + UUID.fromString("e9659715-e257-4f88-847e-700653e101d1"), + "platform", + null, + "account-service", + "ACCOUNT_REGISTERED", + Instant.parse("2026-09-24T00:00:00Z"), + 1, + 1, + AccountAuditDigest.ofPayload(payload), + payload); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 62213d54ff..92d64949bd 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -5,9 +5,11 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateRequest; @@ -28,6 +30,10 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesRequest; import net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse; import net.firedevops.firemud.account.v1.PingRequest; @@ -38,17 +44,84 @@ import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.account.v1.VerifyEmailLoginOtpRequest; import net.firedevops.firemud.accountservice.dto.AccountDto; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.PingService; import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; class AccountGrpcServiceTest { + private static final String WORKLOAD_NAMESPACE = "test"; + private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; + private static final String OTHER_REALM_ID = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; + private static final GrpcPeerIdentity GAME_SESSION_PEER = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-session-service", + WORKLOAD_NAMESPACE, + "game-session-service"); + + private static PlayerExecutionContext validPlayerContext() { + return PlayerExecutionContext.newBuilder() + .setAccountId("10") + .setTenantId("20") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("realm-state-30") + .setPlayableStateScope("realm:30") + .setGameInstanceId("40") + .setSessionId("session-1") + .setRequestId("request-1") + .build(); + } + + private static IssueDirectTextConnectScopeRequest validScopeRequest() { + return IssueDirectTextConnectScopeRequest.newBuilder() + .setPlayerContext(validPlayerContext()) + .setTenantId("20") + .setRealmId(REALM_ID) + .setWorldSlug("world") + .setRealmSlug("public") + .setPlayableStateNamespaceId("realm-state-30") + .setPlayableStateScope("realm:30") + .setGameInstanceId("40") + .setCatalogRevision(5) + .setPointerVersion(8) + .build(); + } + + private static JoinPublicProductionMembershipRequest validJoinRequest() { + return JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(validPlayerContext()) + .setConnectScopeId("scope-1") + .setRequestId("request-1") + .build(); + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + Context context = Context.ROOT; + if (peer != null) { + context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + } + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + @AfterEach void tearDown() { SessionContext.clear(); @@ -80,6 +153,196 @@ public void onCompleted() {} assertEquals("pong", ref.get().getMessage()); } + @Test + void issueDirectTextConnectScopeAcceptsExactGameSessionPeerAndTypedTarget() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when( + accountService.issueDirectTextConnectScope( + Mockito.any(DirectTextCallerContext.class), + Mockito.any(DirectTextJoinTarget.class))) + .thenReturn(new DirectTextJoinScope("scope-1", "2026-09-24T12:00:00Z")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> service.issueDirectTextConnectScope(validScopeRequest(), observer)); + + assertTrue(observer.completed()); + assertEquals("scope-1", observer.response().getConnectScopeId()); + assertEquals("2026-09-24T12:00:00Z", observer.response().getConnectScopeExpiresAt()); + Mockito.verify(accountService) + .issueDirectTextConnectScope( + new DirectTextCallerContext( + 10L, + 20L, + UUID.fromString(REALM_ID), + "realm-state-30", + "realm:30", + 40L, + "session-1", + "request-1"), + new DirectTextJoinTarget( + 20L, + UUID.fromString(REALM_ID), + "world", + "public", + "realm-state-30", + "realm:30", + 40L, + 5L, + 8L)); + } + + @Test + void joinPublicProductionMembershipPreservesStoredFailureOutcome() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when( + accountService.joinPublicProductionFromGameSession( + Mockito.any(DirectTextCallerContext.class), + Mockito.any(JoinPublicProductionRequest.class))) + .thenReturn( + new JoinPublicProductionResult( + false, "ENTITLEMENT_UNAVAILABLE", 10L, 20L, 0L, 0L, 0L, true)); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> service.joinPublicProductionMembership(validJoinRequest(), observer)); + + assertTrue(observer.completed()); + assertFalse(observer.response().getSuccess()); + assertEquals("ENTITLEMENT_UNAVAILABLE", observer.response().getOutcomeCode()); + assertEquals("10", observer.response().getAccountId()); + assertEquals("20", observer.response().getTenantId()); + assertEquals("0", observer.response().getMembershipId()); + assertTrue(observer.response().getReplayed()); + assertFalse(observer.response().hasError()); + Mockito.verify(accountService) + .joinPublicProductionFromGameSession( + new DirectTextCallerContext( + 10L, + 20L, + UUID.fromString(REALM_ID), + "realm-state-30", + "realm:30", + 40L, + "session-1", + "request-1"), + new JoinPublicProductionRequest("scope-1", "request-1")); + } + + @Test + void protectedDirectTextMethodsRejectAbsentWrongSharedAndCrossNamespacePeers() { + List rejectedPeers = + java.util.Arrays.asList( + null, + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/world-management-service", + "test", + "world-management-service"), + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/account-service", "test", "account-service"), + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + "other", + "game-session-service")); + + for (GrpcPeerIdentity peer : rejectedPeers) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver issueObserver = + new RecordingObserver<>(); + RecordingObserver joinObserver = + new RecordingObserver<>(); + + withPeer(peer, () -> service.issueDirectTextConnectScope(validScopeRequest(), issueObserver)); + withPeer( + peer, () -> service.joinPublicProductionMembership(validJoinRequest(), joinObserver)); + + assertEquals("PERMISSION_DENIED", issueObserver.response().getError().getCode()); + assertEquals("PERMISSION_DENIED", joinObserver.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + } + + @Test + void directTextMethodsRejectMalformedOrMismatchedTypedContextBeforeServiceCall() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + + IssueDirectTextConnectScopeRequest mismatchedTarget = + validScopeRequest().toBuilder().setRealmId(OTHER_REALM_ID).build(); + PlayerExecutionContext malformedContext = + validPlayerContext().toBuilder().setAccountId("NaN").build(); + JoinPublicProductionMembershipRequest mismatchedJoin = + validJoinRequest().toBuilder().setRequestId("request-2").build(); + RecordingObserver targetObserver = + new RecordingObserver<>(); + RecordingObserver malformedObserver = + new RecordingObserver<>(); + RecordingObserver requestIdObserver = + new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> service.issueDirectTextConnectScope(mismatchedTarget, targetObserver)); + withPeer( + GAME_SESSION_PEER, + () -> + service.joinPublicProductionMembership( + validJoinRequest().toBuilder().setPlayerContext(malformedContext).build(), + malformedObserver)); + withPeer( + GAME_SESSION_PEER, + () -> service.joinPublicProductionMembership(mismatchedJoin, requestIdObserver)); + + assertEquals("INVALID_ARGUMENT", targetObserver.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", malformedObserver.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", requestIdObserver.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + + @ParameterizedTest + @ValueSource(strings = {"30", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) + void directTextScopeRejectsNoncanonicalRealmIdsAtBothIngressFields(String realmId) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver targetObserver = + new RecordingObserver<>(); + RecordingObserver contextObserver = + new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.issueDirectTextConnectScope( + validScopeRequest().toBuilder().setRealmId(realmId).build(), targetObserver)); + withPeer( + GAME_SESSION_PEER, + () -> + service.issueDirectTextConnectScope( + validScopeRequest().toBuilder() + .setPlayerContext(validPlayerContext().toBuilder().setRealmId(realmId).build()) + .build(), + contextObserver)); + + assertEquals("INVALID_ARGUMENT", targetObserver.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", contextObserver.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + @Test void authenticateFailureReturnsErrorDetail() { PingService pingService = Mockito.mock(PingService.class); @@ -227,7 +490,6 @@ void createAccountValidationErrorReturnsErrorDetail() { AtomicReference ref = new AtomicReference<>(); service.createAccount( CreateAccountRequest.newBuilder() - .setTenantId("7") .setUsername("demo") .setEmail("e@example.com") .setPassword("pass") @@ -260,7 +522,6 @@ void createAccountConflictReturnsApplicationError() { service.createAccount( CreateAccountRequest.newBuilder() - .setTenantId("7") .setUsername("demo") .setEmail("demo@example.com") .setPassword("pass") @@ -275,7 +536,7 @@ void createAccountConflictReturnsApplicationError() { } @Test - void createAccountReturnsAccountIdAndTenant() { + void createAccountReturnsAccountIdForGlobalRequest() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.createAccount(Mockito.any())) @@ -285,7 +546,6 @@ void createAccountReturnsAccountIdAndTenant() { AtomicReference ref = new AtomicReference<>(); service.createAccount( CreateAccountRequest.newBuilder() - .setTenantId("7") .setUsername("demo") .setEmail("e@example.com") .setPassword("pass") @@ -310,40 +570,8 @@ public void onCompleted() {} org.mockito.ArgumentCaptor.forClass( net.firedevops.firemud.accountservice.dto.CreateAccountRequest.class); Mockito.verify(accountService).createAccount(captor.capture()); - assertEquals(7L, captor.getValue().tenantId()); - } - - @Test - void createAccountRejectsZeroTenantIdBeforeCreate() { - PingService pingService = Mockito.mock(PingService.class); - AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); - - AtomicReference ref = new AtomicReference<>(); - service.createAccount( - CreateAccountRequest.newBuilder() - .setTenantId("0") - .setUsername("demo") - .setEmail("e@example.com") - .setPassword("pass") - .build(), - new StreamObserver() { - @Override - public void onNext(CreateAccountResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); + assertEquals("demo", captor.getValue().username()); + assertEquals("e@example.com", captor.getValue().email()); } @Test @@ -520,7 +748,7 @@ void getTenantMembershipForRuntimeReturnsResponse() { Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( - 2L, 1L, true, true, 44L, "2026-03-30T00:00:00Z")); + 2L, 1L, true, true, 44L, "ACTIVE", 9L, "2026-03-30T00:00:00Z")); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = new AtomicReference<>(); @@ -557,7 +785,7 @@ void getTenantMembershipForRuntimePreservesMissingMembershipAndAdmissionAllowed( Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( - 2L, 1L, false, true, 44L, "2026-03-30T00:00:00Z")); + 2L, 1L, false, true, 44L, "MISSING", 0L, "2026-03-30T00:00:00Z")); AccountGrpcService service = new AccountGrpcService(pingService, accountService); RecordingObserver observer = new RecordingObserver<>(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 7f191018a0..b50ed9d3c2 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -10,16 +10,15 @@ import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; -import io.grpc.Status; -import io.grpc.StatusRuntimeException; import java.util.Map; import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; -import net.firedevops.firemud.accountservice.client.LoggingAdminClient; import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.config.MailProperties; import net.firedevops.firemud.accountservice.dto.AccountDto; @@ -27,10 +26,16 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthMode; @@ -42,7 +47,10 @@ import net.firedevops.firemud.accountservice.entity.Subscription; import net.firedevops.firemud.accountservice.mapper.AccountMapper; import net.firedevops.firemud.accountservice.mapper.ProfileMapper; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -57,7 +65,6 @@ import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.session.SessionService; -import net.firedevops.firemud.common.saga.SagaRunner; import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.ReloadableJwtUtil; @@ -67,13 +74,21 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mapstruct.factory.Mappers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; class AccountServiceImplTest { private static final String JWT_SECRET = "mysecretkey123456789012345678901"; + private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; @Mock private AccountRepository accountRepository; + @Mock private AccountAuditOutboxRepository accountAuditOutboxRepository; + @Mock private AccountConnectScopeRepository accountConnectScopeRepository; + @Mock private AccountJoinOperationRepository accountJoinOperationRepository; @Mock private AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; @Mock private AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; @Mock private AccountTenantMembershipRepository accountTenantMembershipRepository; @@ -84,14 +99,13 @@ class AccountServiceImplTest { @Mock private MailProperties mailProperties; private final AccountTokenProperties tokenProperties = new AccountTokenProperties(); private final JwtAuthProperties jwtAuthProperties = new JwtAuthProperties(); - @Mock private LoggingAdminClient loggingAdminClient; @Mock private GameSessionClient gameSessionClient; @Mock private EntityManagementClient entityManagementClient; @Mock private SessionService sessionService; - @Mock private SagaRunner sagaRunner; @Mock private PaymentTransactionRepository paymentTransactionRepository; @Mock private SubscriptionRepository subscriptionRepository; @Mock private ExternalAccountRepository externalAccountRepository; + @Mock private PlatformTransactionManager transactionManager; @Mock private EmailVerificationTokenRepository emailVerificationTokenRepository; @@ -102,8 +116,11 @@ class AccountServiceImplTest { private AccountServiceImpl service; @BeforeEach - void setup() throws net.firedevops.firemud.common.saga.SagaException { + void setup() { MockitoAnnotations.openMocks(this); + when(transactionManager.getTransaction( + org.mockito.ArgumentMatchers.any(TransactionDefinition.class))) + .thenAnswer(invocation -> new SimpleTransactionStatus()); Subscription explicitActiveEntitlement = new Subscription(); explicitActiveEntitlement.setId(1L); explicitActiveEntitlement.setTenantId(7L); @@ -139,6 +156,9 @@ void setup() throws net.firedevops.firemud.common.saga.SagaException { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -155,6 +175,9 @@ void setup() throws net.firedevops.firemud.common.saga.SagaException { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -173,6 +196,9 @@ void setup() throws net.firedevops.firemud.common.saga.SagaException { service = new AccountServiceImpl( accountRepository, + accountAuditOutboxRepository, + accountConnectScopeRepository, + accountJoinOperationRepository, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository, @@ -189,28 +215,24 @@ void setup() throws net.firedevops.firemud.common.saga.SagaException { mailProperties, tokenProperties, jwtAuthProperties, - loggingAdminClient, gameSessionClient, entityManagementClient, jwtUtil, sessionService, - sagaRunner); - org.mockito.Mockito.doAnswer( - inv -> { - ((net.firedevops.firemud.common.saga.Saga) inv.getArgument(0)).run(); - return null; - }) - .when(sagaRunner) - .run(org.mockito.ArgumentMatchers.any()); + transactionManager); } @Test - void createAccountPersistsEntity() throws net.firedevops.firemud.common.saga.SagaException { + void createAccountPersistsOnlyGlobalIdentity() { CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", " DEMO@example.com ", "password"); - Account saved = new Account(); - saved.setId(1L); - when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))).thenReturn(saved); + new CreateAccountRequest("demo", " DEMO@example.com ", "password"); + when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) + .thenAnswer( + invocation -> { + Account saved = invocation.getArgument(0); + saved.setId(1L); + return saved; + }); AccountDto dto = service.createAccount(request); @@ -220,13 +242,21 @@ void createAccountPersistsEntity() throws net.firedevops.firemud.common.saga.Sag org.mockito.ArgumentCaptor.forClass(Account.class); org.mockito.Mockito.verify(accountRepository).save(accountCaptor.capture()); assertEquals("demo@example.com", accountCaptor.getValue().getEmail()); - org.mockito.Mockito.verify(sagaRunner).run(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountAuditOutboxRepository) + .append( + org.mockito.ArgumentMatchers.any(java.util.UUID.class), + org.mockito.ArgumentMatchers.eq("platform"), + org.mockito.ArgumentMatchers.isNull(), + org.mockito.ArgumentMatchers.eq("ACCOUNT_REGISTERED"), + org.mockito.ArgumentMatchers.eq("{\"accountId\":1}")); + assertEquals(null, accountCaptor.getValue().getRole()); + verifyNoInteractions(profileRepository, accountTenantMembershipRepository); } @Test void createAccountReturnsExplicitConflictForCanonicalIdentityCollision() { CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", " DEMO@EXAMPLE.COM ", "password"); + new CreateAccountRequest("demo", " DEMO@EXAMPLE.COM ", "password"); when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) .thenThrow(new org.jooq.exception.IntegrityConstraintViolationException("duplicate")); @@ -238,8 +268,7 @@ void createAccountReturnsExplicitConflictForCanonicalIdentityCollision() { @Test void createAccountMapsSpringDataIntegrityConflict() { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "password"); + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) .thenThrow(new org.springframework.dao.DataIntegrityViolationException("duplicate")); @@ -249,6 +278,797 @@ void createAccountMapsSpringDataIntegrityConflict() { assertEquals("Account already exists", exception.getMessage()); } + @Test + void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + AtomicReference joinedMembership = new AtomicReference<>(); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenAnswer(invocation -> Optional.ofNullable(joinedMembership.get())); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + joinedMembership.set(membership); + return membership; + }); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-attempt-1"); + + JoinPublicProductionResult first = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + JoinPublicProductionResult retried = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + ConnectTokenResult onboardingToken = + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "first-play-after-join")); + + assertTrue(first.success()); + assertEquals("JOINED", first.outcomeCode()); + assertEquals(701L, first.membershipId()); + assertEquals(1L, first.membershipVersion()); + assertTrue(retried.success()); + assertTrue(retried.replayed()); + assertNotNull(onboardingToken.connectToken()); + assertEquals(REALM_ID, retainedScope.get().realmId().toString()); + assertEquals( + first, + new JoinPublicProductionResult( + retried.success(), + retried.outcomeCode(), + retried.accountId(), + retried.tenantId(), + retried.membershipId(), + retried.membershipVersion(), + retried.membershipAuthorityGeneration(), + false)); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) + .append( + org.mockito.ArgumentMatchers.any(java.util.UUID.class), + org.mockito.ArgumentMatchers.eq("tenant"), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), + org.mockito.ArgumentMatchers.contains("join-attempt-1")); + assertEquals("COMMITTED", retainedOperation.get().status()); + + AuthenticationException changedDigest = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest("different-scope", "join-attempt-1"))); + assertEquals("IDEMPOTENCY_CONFLICT", changedDigest.getCode()); + } + + @ParameterizedTest + @CsvSource({ + "SECURITY_LOCKED, AUTH_ACCOUNT_LOCKED", + "DEACTIVATED_PENDING_DELETE, AUTH_INVALID_CREDENTIALS" + }) + void joinPublicProductionRejectsStillActiveBootstrapForIneligibleLifecycleState( + AccountLifecycleState lifecycleState, String expectedCode) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + account.setLifecycleState(lifecycleState); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-ineligible-1"))); + + assertEquals(expectedCode, exception.getCode()); + verifyNoInteractions( + accountJoinOperationRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + } + + @Test + void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription grace = new Subscription(); + grace.setId(22L); + grace.setTenantId(7L); + grace.setStatus("grace"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(grace)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-closed-1"); + + JoinPublicProductionResult denied = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + JoinPublicProductionResult retry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(denied.success()); + assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", denied.outcomeCode()); + assertFalse(retry.success()); + assertTrue(retry.replayed()); + assertEquals(denied.outcomeCode(), retry.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + grace.setStatus("active"); + grace.setEntitlementVersion(2L); + AuthenticationException changedPolicy = + assertThrows( + AuthenticationException.class, + () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); + assertEquals("IDEMPOTENCY_CONFLICT", changedPolicy.getCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) + .findByTenantIdForUpdate(7L); + } + + @ParameterizedTest + @CsvSource({"false", "true"}) + void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguous) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription recovered = new Subscription(); + recovered.setId(22L); + recovered.setTenantId(7L); + recovered.setStatus("active"); + recovered.setEntitlementVersion(1L); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenReturn( + ambiguous + ? java.util.List.of(new Subscription(), new Subscription()) + : java.util.List.of(), + java.util.List.of(recovered), + java.util.List.of(recovered)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + return membership; + }); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-unavailable-1"); + + JoinPublicProductionResult first = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertFalse(first.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", first.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(null, retainedOperation.get().outcome()); + assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + assertEquals("UNAVAILABLE", retainedOperation.get().lastAttemptAuthorityAvailability()); + assertNotNull(retainedOperation.get().intentDigest()); + assertEquals(null, retainedOperation.get().requestDigest()); + assertEquals(null, retainedOperation.get().requestDigestVersion()); + assertEquals(null, retainedOperation.get().allowPublicJoin()); + assertEquals(null, retainedOperation.get().entitlementVersion()); + + JoinPublicProductionResult retriedAfterRecovery = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertTrue(retriedAfterRecovery.success()); + assertEquals("JOINED", retriedAfterRecovery.outcomeCode()); + assertEquals("COMMITTED", retainedOperation.get().status()); + assertEquals("AVAILABLE", retainedOperation.get().entitlementAuthorityAvailability()); + assertEquals(1L, retainedOperation.get().entitlementVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertNotNull(retainedOperation.get().requestDigest()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) + .append( + org.mockito.ArgumentMatchers.any(java.util.UUID.class), + org.mockito.ArgumentMatchers.eq("tenant"), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), + org.mockito.ArgumentMatchers.contains("join-unavailable-1")); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) + .findByTenantIdForUpdate(7L); + } + + @Test + void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription initialPolicy = new Subscription(); + initialPolicy.setId(22L); + initialPolicy.setTenantId(7L); + initialPolicy.setStatus("active"); + initialPolicy.setEntitlementVersion(5L); + Subscription changedPolicy = new Subscription(); + changedPolicy.setId(22L); + changedPolicy.setTenantId(7L); + changedPolicy.setStatus("active"); + changedPolicy.setEntitlementVersion(6L); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenReturn(java.util.List.of(initialPolicy), java.util.List.of(changedPolicy)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + JoinPublicProductionResult result = + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-race-1")); + + assertFalse(result.success()); + assertEquals("IDEMPOTENCY_CONFLICT", result.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + assertEquals("IDEMPOTENCY_CONFLICT", retainedOperation.get().outcome()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertEquals(1, retainedOperation.get().requestDigestVersion()); + assertNotNull(retainedOperation.get().requestDigest()); + assertEquals(null, retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantIdForUpdate(7L); + } + + @Test + void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription initialPolicy = new Subscription(); + initialPolicy.setId(22L); + initialPolicy.setTenantId(7L); + initialPolicy.setStatus("active"); + initialPolicy.setEntitlementVersion(5L); + Subscription changedPolicy = new Subscription(); + changedPolicy.setId(22L); + changedPolicy.setTenantId(7L); + changedPolicy.setStatus("active"); + changedPolicy.setEntitlementVersion(6L); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenReturn( + java.util.List.of(initialPolicy), + java.util.List.of(), + java.util.List.of(changedPolicy)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-policy-retry-1"); + + JoinPublicProductionResult pending = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + String boundDigest = retainedOperation.get().requestDigest(); + String intentDigest = retainedOperation.get().intentDigest(); + + assertFalse(pending.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", pending.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + + JoinPublicProductionResult changedPolicyRetry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(changedPolicyRetry.success()); + assertEquals("IDEMPOTENCY_CONFLICT", changedPolicyRetry.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + assertEquals("IDEMPOTENCY_CONFLICT", retainedOperation.get().outcome()); + assertEquals(intentDigest, retainedOperation.get().intentDigest()); + assertEquals(boundDigest, retainedOperation.get().requestDigest()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertEquals(null, retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) + .findByTenantIdForUpdate(7L); + } + + @Test + void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenThrow(new IllegalStateException("entitlement storage unavailable")); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-txn-boundary-1"))); + + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(null, retainedOperation.get().outcome()); + assertNotNull(retainedOperation.get().intentDigest()); + assertEquals(null, retainedOperation.get().requestDigest()); + assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(2)) + .commit(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(1)) + .rollback(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + } + + @Test + void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTransition() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = "expired-connect-scope"; + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-expired-pending-1"); + + VerifiedJoinScope expiredScope = + new VerifiedJoinScope( + connectScopeId, + 11L, + 7L, + UUID.fromString(REALM_ID), + "demo", + "production", + "production-namespace-7", + "SHARED", + 44L, + 23L, + 17L, + "1999-12-31T23:59:00Z", + "2000-01-01T00:00:00Z", + ""); + expiredScope = + new VerifiedJoinScope( + expiredScope.connectScopeId(), + expiredScope.accountId(), + expiredScope.tenantId(), + expiredScope.realmId(), + expiredScope.worldSlug(), + expiredScope.realmSlug(), + expiredScope.playableStateNamespaceId(), + expiredScope.playableStateScope(), + expiredScope.gameInstanceId(), + expiredScope.catalogRevision(), + expiredScope.pointerVersion(), + expiredScope.evaluatedAt(), + expiredScope.connectScopeExpiresAt(), + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(expiredScope)); + retainedScope.set(expiredScope); + String callerBinding = + new JwtUtil(JWT_SECRET, 300000L) + .parseToken(bootstrap.bootstrapToken()) + .getPayload() + .get("jti") + .toString(); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + expiredScope.accountId(), + expiredScope.tenantId(), + expiredScope.realmId(), + callerBinding, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), + expiredScope.snapshotDigest(), + "UNAVAILABLE", + null, + null, + null, + null, + "PENDING", + null, + null, + null, + null, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + request.requestId(), expiredScope, callerBinding), + "ENTITLEMENT_UNAVAILABLE", + "UNAVAILABLE")); + + JoinPublicProductionResult expiredRetry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + JoinPublicProductionResult terminalReadback = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(expiredRetry.success()); + assertEquals("CONNECT_SCOPE_INVALID", expiredRetry.outcomeCode()); + assertFalse(terminalReadback.success()); + assertTrue(terminalReadback.replayed()); + assertEquals("CONNECT_SCOPE_INVALID", terminalReadback.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + assertEquals("CONNECT_SCOPE_INVALID", retainedOperation.get().outcome()); + verifyNoInteractions( + subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + } + + @Test + void joinPublicProductionReturnsConflictWhenGlobalRequestIdClaimIsLost() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + VerifiedJoinScope scope = retainedScope.get(); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + 12L, + scope.tenantId(), + scope.realmId(), + "different-caller", + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), + scope.snapshotDigest(), + "NOT_EVALUATED", + null, + null, + null, + null, + "PENDING", + null, + null, + null, + null, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + "join-global-collision-1", scope, "different-caller"), + null, + "NOT_EVALUATED")); + + AuthenticationException conflict = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-global-collision-1"))); + + assertEquals("IDEMPOTENCY_CONFLICT", conflict.getCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + } + + @Test + void quarantinedLegacyMembershipIsNeverRestoredByPublicJoin() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + AccountTenantMembership quarantined = membership(account, 7L); + quarantined.setLifecycleState("LEGACY_UNVERIFIED"); + quarantined.setGameplayAdmissionAllowed(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(quarantined)); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + JoinPublicProductionResult result = + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-legacy-1")); + + assertFalse(result.success()); + assertEquals("MEMBERSHIP_RECONCILIATION_REQUIRED", result.outcomeCode()); + assertEquals("LEGACY_UNVERIFIED", quarantined.getLifecycleState()); + assertFalse(quarantined.isGameplayAdmissionAllowed()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + } + + private void retainJoinEvidence( + AtomicReference retainedScope, + AtomicReference retainedOperation) { + org.mockito.Mockito.doAnswer( + invocation -> { + retainedScope.set(invocation.getArgument(0)); + return null; + }) + .when(accountConnectScopeRepository) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + when(accountConnectScopeRepository.find(org.mockito.ArgumentMatchers.anyString())) + .thenAnswer(invocation -> Optional.ofNullable(retainedScope.get())); + when(accountJoinOperationRepository.find(org.mockito.ArgumentMatchers.anyString())) + .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); + when(accountJoinOperationRepository.findForUpdate(org.mockito.ArgumentMatchers.anyString())) + .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); + org.mockito.Mockito.doAnswer( + invocation -> { + String requestId = invocation.getArgument(0); + VerifiedJoinScope scope = invocation.getArgument(1); + String callerBinding = invocation.getArgument(2); + String intentDigest = invocation.getArgument(3); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + scope.accountId(), + scope.tenantId(), + scope.realmId(), + callerBinding, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( + scope.connectScopeId()), + scope.snapshotDigest(), + "NOT_EVALUATED", + null, + null, + null, + null, + "PENDING", + null, + null, + null, + null, + 1, + intentDigest, + null, + "NOT_EVALUATED")); + return true; + }) + .when(accountJoinOperationRepository) + .insertIntent( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.doAnswer( + invocation -> { + var pending = retainedOperation.get(); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + "AVAILABLE", + invocation.getArgument(3), + invocation.getArgument(2), + 1, + invocation.getArgument(1), + pending.status(), + pending.outcome(), + pending.membershipId(), + pending.membershipVersion(), + pending.membershipAuthorityGeneration(), + pending.intentDigestVersion(), + pending.intentDigest(), + null, + "AVAILABLE")); + return null; + }) + .when(accountJoinOperationRepository) + .bindPolicyEvidence( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyBoolean()); + org.mockito.Mockito.doAnswer( + invocation -> { + var pending = retainedOperation.get(); + String availability = invocation.getArgument(1); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + pending.requestDigest() == null + ? availability + : pending.entitlementAuthorityAvailability(), + pending.allowPublicJoin(), + pending.entitlementVersion(), + pending.requestDigestVersion(), + pending.requestDigest(), + pending.status(), + pending.outcome(), + pending.membershipId(), + pending.membershipVersion(), + pending.membershipAuthorityGeneration(), + pending.intentDigestVersion(), + pending.intentDigest(), + invocation.getArgument(2), + availability)); + return null; + }) + .when(accountJoinOperationRepository) + .recordAttemptFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.doAnswer( + invocation -> { + var pending = retainedOperation.get(); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + pending.entitlementAuthorityAvailability(), + pending.allowPublicJoin(), + pending.entitlementVersion(), + pending.requestDigestVersion(), + pending.requestDigest(), + invocation.getArgument(1), + invocation.getArgument(2), + invocation.getArgument(3), + invocation.getArgument(4), + invocation.getArgument(5), + pending.intentDigestVersion(), + pending.intentDigest(), + null, + pending.lastAttemptAuthorityAvailability())); + return null; + }) + .when(accountJoinOperationRepository) + .finish( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class)); + } + @Test void emailLoginOtpRequestIsNeutralForUnknownEmail() { when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); @@ -497,25 +1317,6 @@ void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); } - @Test - void createAccountContinuesWhenAuditLoggingFails() - throws net.firedevops.firemud.common.saga.SagaException { - CreateAccountRequest request = - new CreateAccountRequest(7L, "demo", "demo@example.com", "password"); - Account saved = new Account(); - saved.setId(1L); - when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))).thenReturn(saved); - org.mockito.Mockito.doThrow(new StatusRuntimeException(Status.UNAVAILABLE)) - .when(loggingAdminClient) - .logAccountCreation(7L, 1L); - - AccountDto dto = service.createAccount(request); - - assertEquals(1L, dto.id()); - assertEquals("demo", dto.username()); - org.mockito.Mockito.verify(sagaRunner).run(org.mockito.ArgumentMatchers.any()); - } - @Test void authenticateReturnsControlUiTokenWithoutGameplayMembership() { Account account = new Account(); @@ -531,7 +1332,7 @@ void authenticateReturnsControlUiTokenWithoutGameplayMembership() { var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("control-ui", claims.getAudience().iterator().next()); assertEquals(1L, claims.get("accountId", Long.class)); - assertEquals(java.util.List.of("player"), claims.get("globalRoles")); + assertEquals(java.util.List.of(), claims.get("globalRoles")); assertNotNull(claims.get("jti")); assertFalse(claims.containsKey("tenantId")); org.mockito.Mockito.verify(sessionService) @@ -577,7 +1378,7 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("account-service", claims.getAudience().iterator().next()); assertEquals(1L, claims.get("accountId", Long.class)); - assertEquals(java.util.List.of("player"), claims.get("globalRoles")); + assertEquals(java.util.List.of(), claims.get("globalRoles")); assertNotNull(claims.get("jti")); org.mockito.Mockito.verify(sessionService) .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); @@ -734,6 +1535,9 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { service = new AccountServiceImpl( accountRepository, + accountAuditOutboxRepository, + accountConnectScopeRepository, + accountJoinOperationRepository, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository, @@ -750,12 +1554,11 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { mailProperties, tokenProperties, jwtAuthProperties, - loggingAdminClient, gameSessionClient, entityManagementClient, jwtUtil, sessionService, - sagaRunner); + transactionManager); IllegalStateException ex = assertThrows(IllegalStateException.class, () -> service.listBootstrapWorlds("boom-token")); @@ -772,13 +1575,17 @@ void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(gameSessionClient.listGameplayRealms("demo")) .thenReturn( - java.util.List.of( + java.util.Arrays.asList( + null, net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() .setWorldSlug("demo") .setRealmSlug("broken") .setDisplayName("Broken Realm") .setTenantId("bad") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -798,6 +1605,29 @@ void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); } + @Test + void listBootstrapRealmsMapsZeroPublicAuthorityFromGameSession() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenThrow( + new IllegalStateException( + "Gameplay realm discovery failed: invalid public realm cardinality")); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + } + @Test void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { Account account = new Account(); @@ -814,6 +1644,9 @@ void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -833,6 +1666,91 @@ void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); } + @Test + void listBootstrapRealmsRejectsMultipleVisiblePublicRealms() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + var firstPublicRealm = gameSessionClient.listGameplayRealms("demo").getFirst(); + var secondPublicRealm = + firstPublicRealm.toBuilder() + .setRealmSlug("production-alt") + .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") + .setGameInstanceId("45") + .build(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(java.util.List.of(firstPublicRealm, secondPublicRealm)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + } + + @Test + void listBootstrapRealmsAcceptsExactlyOneVisiblePublicRealm() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + + assertEquals(1, realms.size()); + assertEquals("production", realms.getFirst().realmSlug()); + } + + @ParameterizedTest + @ValueSource(strings = {"101", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) + void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(realmId) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + } + @Test void issueConnectTokenRejectsMalformedConnectScopeId() { Account account = new Account(); @@ -997,6 +1915,59 @@ void issueConnectTokenRejectsMalformedConnectScopeClaims() { assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); } + @ParameterizedTest + @ValueSource(strings = {"101", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) + void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String malformedConnectScopeId = + new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + "11", + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", "11"), + Map.entry("tenantId", "7"), + Map.entry("realmId", realmId), + Map.entry("worldSlug", "demo"), + Map.entry("realmSlug", "production"), + Map.entry("playableStateNamespaceId", "production-namespace-7"), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", "44"), + Map.entry("catalogRevision", "23"), + Map.entry("pointerVersion", "17"), + Map.entry("evaluatedAt", java.time.Instant.now().toString()), + Map.entry( + "connectScopeExpiresAt", + java.time.Instant.now().plusSeconds(3600).toString()), + Map.entry("jti", "invalid-realm-id"))); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(malformedConnectScopeId, "req-invalid-realm-id"))); + + assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + @Test void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { Account account = new Account(); @@ -1233,7 +2204,9 @@ void getTenantMembershipForRuntimeReturnsAdmissionAllowedForExistingAccount() { assertEquals(7L, dto.tenantId()); assertTrue(dto.membershipExists()); assertTrue(dto.gameplayAdmissionAllowed()); - assertEquals(711L, dto.membershipVersion()); + assertEquals(1L, dto.membershipVersion()); + assertEquals("ACTIVE", dto.membershipLifecycleState()); + assertEquals(1L, dto.membershipAuthorityGeneration()); assertNotNull(dto.evaluatedAt()); } @@ -1276,8 +2249,8 @@ void getTenantEntitlementsForRuntimeUsesCurrentSubscriptions() { assertEquals(7L, dto.tenantId()); assertTrue(dto.gameplayAvailable()); assertTrue(dto.allowPublicJoin()); - assertEquals(31L, dto.entitlementVersion()); - assertEquals(31L, dto.tenantBillingSequence()); + assertEquals(1L, dto.entitlementVersion()); + assertEquals(1L, dto.tenantBillingSequence()); assertNotNull(dto.evaluatedAt()); } @@ -1313,6 +2286,57 @@ void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); } + @Test + void issueDirectTextConnectScopeRejectsUnavailableEntitlementWithoutRetainingScope() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + + @Test + void issueDirectTextConnectScopeRejectsBillingBlockedEntitlementWithoutRetainingScope() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + Subscription canceled = new Subscription(); + canceled.setId(31L); + canceled.setTenantId(7L); + canceled.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(canceled)); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); + + assertEquals("TENANT_BILLING_BLOCKED", exception.getCode()); + assertEquals("Gameplay is not available for this tenant", exception.getMessage()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + + @Test + void issueDirectTextConnectScopeRetainsScopeForActiveEntitlement() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + + DirectTextJoinScope result = + service.issueDirectTextConnectScope(directTextCaller(), directTextTarget()); + + assertNotNull(result.connectScopeId()); + assertNotNull(result.connectScopeExpiresAt()); + org.mockito.Mockito.verify(accountConnectScopeRepository) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + @Test void issueConnectTokenReturnsShortLivedConnectToken() { Account account = new Account(); @@ -1445,6 +2469,9 @@ void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("99") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) @@ -1460,9 +2487,10 @@ void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { service.issueConnectToken( bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-4"))); - assertEquals("CONNECT_SCOPE_MISMATCH", ex.getCode()); + // The catalog and pointer disagree before Account has a valid current pair to compare. + assertEquals("ADMISSION_POINTER_UNAVAILABLE", ex.getCode()); assertEquals( - "Selected gameplay target is no longer admissible; rerun bootstrap discovery and request a fresh connect scope", + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", ex.getMessage()); } @@ -1495,6 +2523,9 @@ void issueConnectTokenRejectsWorldMismatchAfterBootstrapDiscovery() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -1550,6 +2581,9 @@ void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { .setDisplayName("Live Realm") .setTenantId("") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -1609,6 +2643,9 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("99") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) @@ -1801,6 +2838,9 @@ void issueConnectTokenRejectsPresentNonAdmittingMembership( .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(true) .setPublicProductionRealm(publicProductionRealm) @@ -1817,6 +2857,9 @@ void issueConnectTokenRejectsPresentNonAdmittingMembership( .setRealmDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(true) .setPublicProductionRealm(publicProductionRealm) @@ -1888,6 +2931,9 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("99") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) @@ -1903,13 +2949,14 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { service.issueConnectToken( bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-fail-1"))); - assertEquals("CONNECT_SCOPE_MISMATCH", firstFailure.getCode()); + // The catalog and pointer disagree before Account has a valid current pair to compare. + assertEquals("ADMISSION_POINTER_UNAVAILABLE", firstFailure.getCode()); when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, "req-replay-fail-1")) .thenReturn( Optional.of( new SessionService.ConnectTokenReplay( - false, null, "CONNECT_SCOPE_MISMATCH", firstFailure.getMessage()))); + false, null, "ADMISSION_POINTER_UNAVAILABLE", firstFailure.getMessage()))); when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() @@ -1919,6 +2966,9 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -1935,10 +2985,10 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-fail-1"))); - assertEquals("CONNECT_SCOPE_MISMATCH", replayedFailure.getCode()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", replayedFailure.getCode()); assertEquals(firstFailure.getMessage(), replayedFailure.getMessage()); assertEquals( - "Selected gameplay target is no longer admissible; rerun bootstrap discovery and request a fresh connect scope", + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", replayedFailure.getMessage()); } @@ -2117,6 +3167,9 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis .setDisplayName("Private Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(false) @@ -2134,6 +3187,9 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis .setRealmDisplayName("Private Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(false) @@ -2187,6 +3243,9 @@ void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2237,6 +3296,9 @@ void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2273,6 +3335,13 @@ void listBootstrapRealmsIncludesRealmStatePolicy() { var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); assertEquals(1, realms.size()); + assertEquals(REALM_ID, realms.getFirst().realmId()); + assertEquals( + REALM_ID, + new JwtUtil(JWT_SECRET, 300000L) + .parseToken(realms.getFirst().connectScopeId()) + .getPayload() + .get("realmId")); assertEquals("SHARED", realms.getFirst().stateScope()); assertEquals("ALLOW_NEW", realms.getFirst().characterCreationPolicy()); } @@ -2296,6 +3365,9 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { .setDisplayName("Broken Realm") .setTenantId("bad") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2309,6 +3381,9 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2347,6 +3422,9 @@ void listBootstrapRealmsRejectsRealmWithUnknownStateScope() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2386,6 +3464,9 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2402,6 +3483,9 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2447,6 +3531,8 @@ void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() .thenReturn(Optional.of(membership(account, 7L))); when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW"), net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() .setWorldSlug("demo") .setWorldDisplayName("Demo World") @@ -2454,6 +3540,9 @@ void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("bad") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2490,6 +3579,8 @@ void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { .thenReturn(Optional.of(membership(account, 7L))); when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW"), net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() .setWorldSlug("demo") .setWorldDisplayName("Demo World") @@ -2497,6 +3588,9 @@ void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2541,6 +3635,9 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2557,6 +3654,9 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2573,6 +3673,9 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setRealmDisplayName("Live Realm") .setTenantId("7") .setGameInstanceId("91") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2606,7 +3709,8 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat assertEquals("char-sandbox-1", characters.getFirst().characterId()); assertEquals("BuilderMara", characters.getFirst().characterName()); assertEquals("ISOLATED", characters.getFirst().stateScope()); - org.mockito.Mockito.verify(gameSessionClient).getAdmissionPointer(7L, "sandbox", "production"); + org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.times(2)) + .getAdmissionPointer(7L, "sandbox", "production"); } @Test @@ -2629,6 +3733,9 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { .setDisplayName("Tenant Seven") .setTenantId("7") .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) .setPublicProductionRealm(true) @@ -2641,12 +3748,23 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { .setDisplayName("Tenant Eight") .setTenantId("8") .setGameInstanceId("45") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-8") + .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW")); + when(gameSessionClient.getAdmissionPointer(8L, "demo", "production")) + .thenReturn( + admissionPointer( + 8L, "demo", "production", "45", 18L, true, true, "SHARED", "ALLOW_NEW")); when(entityManagementClient.listCharactersByAccount( 7L, 11L, 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(java.util.List.of()); @@ -2665,9 +3783,9 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { bootstrap.bootstrapToken(), "demo", "production", connectScopeId); assertTrue(characters.isEmpty()); - org.mockito.Mockito.verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); - org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.never()) - .getAdmissionPointer(8L, "demo", "production"); + org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.times(2)) + .getAdmissionPointer(7L, "demo", "production"); + org.mockito.Mockito.verify(gameSessionClient).getAdmissionPointer(8L, "demo", "production"); } @Test @@ -2697,6 +3815,44 @@ void listBootstrapCharactersRejectsPathThatDoesNotMatchSignedScope() { verifyNoInteractions(entityManagementClient); } + @Test + void listBootstrapCharactersRejectsChangedCanonicalRealmId() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + net.firedevops.firemud.gamesession.v1.GameplayRealm changedRealm = + gameSessionClient.listGameplayRealms("demo").getFirst().toBuilder() + .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") + .build(); + when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(changedRealm)); + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer changedAdmissionPointer = + gameSessionClient.getAdmissionPointer(7L, "demo", "production").toBuilder() + .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") + .build(); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn(changedAdmissionPointer); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + + assertEquals("CONNECT_SCOPE_MISMATCH", ex.getCode()); + verifyNoInteractions(entityManagementClient); + } + @Test void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { Account account = new Account(); @@ -2721,12 +3877,19 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(false) .setRequiresCharacterSelection(false) .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + admissionPointer( + 7L, "demo", "preview", "55", 19L, false, false, "SHARED", "ALLOW_NEW")); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); @@ -2762,6 +3925,9 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -2778,6 +3944,9 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( .setRealmDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -2819,6 +3988,9 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -2826,6 +3998,18 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + admissionPointer( + 7L, + "demo", + "preview", + "55", + 19L, + visible, + publicProductionRealm, + "SHARED", + "ALLOW_NEW")); when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( 11L, 7L, "demo", "preview")) .thenReturn(true); @@ -2866,6 +4050,9 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -2882,6 +4069,9 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( .setRealmDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-7") + .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) .setPublicProductionRealm(publicProductionRealm) @@ -3379,6 +4569,38 @@ void updateLoginAuthModesFailsClosedBeforeReadingOrPersistingAccount() { org.mockito.Mockito.verifyNoInteractions(accountRepository); } + private static Account directTextAccount() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + return account; + } + + private static DirectTextCallerContext directTextCaller() { + return new DirectTextCallerContext( + 11L, + 7L, + UUID.fromString(REALM_ID), + "production-namespace-7", + "SHARED", + 44L, + "session-1", + "direct-text-request-1"); + } + + private static DirectTextJoinTarget directTextTarget() { + return new DirectTextJoinTarget( + 7L, + UUID.fromString(REALM_ID), + "demo", + "production", + "production-namespace-7", + "SHARED", + 44L, + 23L, + 17L); + } + private static String hash(String password) { Argon2 argon2 = Argon2Factory.create(); char[] chars = password.toCharArray(); @@ -3389,12 +4611,45 @@ private static String hash(String password) { } } + private static net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer admissionPointer( + long tenantId, + String worldSlug, + String realmSlug, + String gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + String stateScope, + String characterCreationPolicy) { + return net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug(worldSlug) + .setWorldDisplayName("demo".equals(worldSlug) ? "Demo World" : "Builder Sandbox") + .setRealmSlug(realmSlug) + .setRealmDisplayName("production".equals(realmSlug) ? "Live Realm" : "Preview Realm") + .setTenantId(Long.toString(tenantId)) + .setGameInstanceId(gameInstanceId) + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId("production-namespace-" + tenantId) + .setCatalogRevision(23L) + .setPointerVersion(pointerVersion) + .setVisible(visible) + .setPublicProductionRealm(publicProductionRealm) + .setRequiresCharacterSelection(false) + .setStateScope(stateScope) + .setCharacterCreationPolicy(characterCreationPolicy) + .build(); + } + private static AccountTenantMembership membership(Account account, long tenantId) { AccountTenantMembership membership = new AccountTenantMembership(); membership.setId(tenantId * 100 + (account.getId() == null ? 0L : account.getId())); membership.setAccount(account); membership.setTenantId(tenantId); membership.setGameplayAdmissionAllowed(true); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(1L); + membership.setAuthorityProvenance("SEEDED_DEMO"); return membership; } diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index 30a088e01d..a9c826f671 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -37,5 +37,8 @@ void accountServiceMethodSetIsFullyCategorized() { AccountRuntimeStubServer.implementedRuntimeMethodNames().stream(), NON_RUNTIME_METHODS.stream()) .collect(java.util.stream.Collectors.toSet())); + + assertThat(AccountRuntimeStubServer.implementedRuntimeMethodNames()) + .contains("IssueDirectTextConnectScope", "JoinPublicProductionMembership"); } } diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 06a325ea23..5fdff55e61 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -4,6 +4,7 @@ import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.stub.StreamObserver; import java.io.IOException; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Set; @@ -22,12 +23,18 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.account.v1.PingRequest; import net.firedevops.firemud.account.v1.PingResponse; import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.account.AccountProfileJson; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; /** Shared fake Account runtime authority for cross-service gameplay tests. */ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountServiceImplBase @@ -39,7 +46,9 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe "Authenticate", "GetTenantMembershipForRuntime", "GetRealmAccessGrantForRuntime", - "GetTenantEntitlementsForRuntime"); + "GetTenantEntitlementsForRuntime", + "IssueDirectTextConnectScope", + "JoinPublicProductionMembership"); private final Server server; private final List authenticateRequests = new CopyOnWriteArrayList<>(); @@ -49,8 +58,10 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe private final AtomicBoolean allowPublicJoin = new AtomicBoolean(true); private final AtomicBoolean realmAccessGranted = new AtomicBoolean(true); private final AtomicLong defaultAccountId = new AtomicLong(1L); + private final AtomicLong nextConnectScopeId = new AtomicLong(1L); private final Map accountIdsByEmail = new ConcurrentHashMap<>(); private final Map profilesByAccountId = new ConcurrentHashMap<>(); + private final Map connectScopesById = new ConcurrentHashMap<>(); public AccountRuntimeStubServer(int port) throws IOException { this.server = NettyServerBuilder.forPort(port).addService(this).build().start(); @@ -198,6 +209,109 @@ public void getTenantEntitlementsForRuntime( responseObserver.onCompleted(); } + @Override + public void issueDirectTextConnectScope( + IssueDirectTextConnectScopeRequest request, + StreamObserver responseObserver) { + PlayerExecutionContext caller = request.getPlayerContext(); + if (caller.getAccountId().isBlank() + || caller.getTenantId().isBlank() + || caller.getRealmId().isBlank() + || caller.getGameInstanceId().isBlank() + || caller.getPlayableStateNamespaceId().isBlank() + || caller.getPlayableStateScope().isBlank() + || request.getTenantId().isBlank() + || request.getRealmId().isBlank() + || request.getGameInstanceId().isBlank() + || request.getWorldSlug().isBlank() + || request.getRealmSlug().isBlank() + || request.getPlayableStateNamespaceId().isBlank() + || request.getPlayableStateScope().isBlank() + || !caller.getTenantId().equals(request.getTenantId()) + || !caller.getRealmId().equals(request.getRealmId()) + || !caller.getGameInstanceId().equals(request.getGameInstanceId()) + || !caller.getPlayableStateNamespaceId().equals(request.getPlayableStateNamespaceId()) + || !caller.getPlayableStateScope().equals(request.getPlayableStateScope())) { + responseObserver.onNext( + IssueDirectTextConnectScopeResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("INVALID_ARGUMENT") + .setMessage("Direct-text connect scope request is incomplete")) + .build()); + } else { + String scopeId = "stub-connect-scope-" + nextConnectScopeId.getAndIncrement(); + Instant expiresAt = Instant.now().plusSeconds(300); + connectScopesById.put( + scopeId, + new StubConnectScope( + caller.getAccountId(), + request.getTenantId(), + request.getRealmId(), + request.getGameInstanceId(), + request.getPlayableStateNamespaceId(), + request.getPlayableStateScope(), + expiresAt)); + responseObserver.onNext( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId(scopeId) + .setConnectScopeExpiresAt(expiresAt.toString()) + .build()); + } + responseObserver.onCompleted(); + } + + @Override + public void joinPublicProductionMembership( + JoinPublicProductionMembershipRequest request, + StreamObserver responseObserver) { + PlayerExecutionContext caller = request.getPlayerContext(); + StubConnectScope scope = connectScopesById.get(request.getConnectScopeId()); + if (request.getConnectScopeId().isBlank() + || request.getRequestId().isBlank() + || !request.getRequestId().equals(caller.getRequestId()) + || caller.getAccountId().isBlank() + || caller.getTenantId().isBlank() + || scope == null + || !scope.expiresAt().isAfter(Instant.now()) + || !scope.accountId().equals(caller.getAccountId()) + || !scope.tenantId().equals(caller.getTenantId()) + || !scope.realmId().equals(caller.getRealmId()) + || !scope.gameInstanceId().equals(caller.getGameInstanceId()) + || !scope.playableStateNamespaceId().equals(caller.getPlayableStateNamespaceId()) + || !scope.playableStateScope().equals(caller.getPlayableStateScope())) { + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("INVALID_ARGUMENT") + .setMessage("Direct-text JOIN request is incomplete")) + .build()); + } else if (!allowPublicJoin.get()) { + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setOutcomeCode("PUBLIC_PRODUCTION_ADMISSION_DENIED") + .setAccountId(caller.getAccountId()) + .setTenantId(caller.getTenantId()) + .build()); + } else { + membershipExists.set(true); + gameplayAdmissionAllowed.set(true); + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("JOINED") + .setAccountId(caller.getAccountId()) + .setTenantId(caller.getTenantId()) + .setMembershipId( + "stub-membership-" + caller.getAccountId() + "-" + caller.getTenantId()) + .setMembershipVersion(1L) + .setMembershipAuthorityGeneration(1L) + .build()); + } + responseObserver.onCompleted(); + } + @Override public void getProfile( GetProfileRequest request, StreamObserver responseObserver) { @@ -262,4 +376,13 @@ private StubProfile withPresenceVisibilityPolicy(String visibilityPolicy) { visibilityPolicy == null ? DEFAULT_VISIBILITY_POLICY : visibilityPolicy); } } + + private record StubConnectScope( + String accountId, + String tenantId, + String realmId, + String gameInstanceId, + String playableStateNamespaceId, + String playableStateScope, + Instant expiresAt) {} } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java new file mode 100644 index 0000000000..5301aae34d --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/AccountAuditGrpcAuthConfiguration.java @@ -0,0 +1,37 @@ +package net.firedevops.firemud.loggingadmin.config; + +import java.util.HashSet; +import java.util.Set; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.common.security.JwtUtil; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.grpc.server.GlobalServerInterceptor; + +/** Allows mTLS-guarded Account audit methods to run without a JWT token. */ +@Configuration(proxyBeanMethods = false) +public class AccountAuditGrpcAuthConfiguration { + private static final Set ACCOUNT_AUDIT_METHODS = + Set.of( + "logging_admin.v1.LoggingAdminService/CreateLogEvent", + "logging_admin.v1.LoggingAdminService/ReadLogEventReceipt"); + + @Bean + @GlobalServerInterceptor + @ConditionalOnProperty( + prefix = "firemud.auth.grpc", + name = "interceptor-enabled", + havingValue = "true", + matchIfMissing = true) + @ConditionalOnMissingBean(AuthTokenInterceptor.class) + public AuthTokenInterceptor accountAuditAuthTokenInterceptor( + @Qualifier("jwtUtil") JwtUtil jwtUtil, GrpcAuthProperties properties) { + Set unauthenticatedMethods = new HashSet<>(properties.getPublicMethods()); + unauthenticatedMethods.addAll(ACCOUNT_AUDIT_METHODS); + return new AuthTokenInterceptor(jwtUtil, unauthenticatedMethods); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java new file mode 100644 index 0000000000..b80457862e --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java @@ -0,0 +1,13 @@ +package net.firedevops.firemud.loggingadmin.dto; + +public record AccountAuditReceiptDto( + AccountAuditScope scope, + Long tenantId, + String auditEventId, + String receiptId, + long logEventId, + int schemaVersion, + int payloadDigestVersion, + String payloadDigest, + AccountAuditReceiptStatus status, + AccountAuditReceiptOutcome outcome) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java new file mode 100644 index 0000000000..35bdf8d33a --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptOutcome.java @@ -0,0 +1,8 @@ +package net.firedevops.firemud.loggingadmin.dto; + +public enum AccountAuditReceiptOutcome { + ACCEPTED, + DUPLICATE, + NON_REPLAYABLE, + IDEMPOTENCY_CONFLICT +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java new file mode 100644 index 0000000000..9c9a8f5047 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptStatus.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.loggingadmin.dto; + +public enum AccountAuditReceiptStatus { + COMMITTED, + MINIMIZED, + CONFLICT +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java new file mode 100644 index 0000000000..e3f9b85a3d --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditScope.java @@ -0,0 +1,16 @@ +package net.firedevops.firemud.loggingadmin.dto; + +public enum AccountAuditScope { + PLATFORM("platform"), + TENANT("tenant"); + + private final String databaseValue; + + AccountAuditScope(String databaseValue) { + this.databaseValue = databaseValue; + } + + public String databaseValue() { + return databaseValue; + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java index bbded3dd0b..0e187d9160 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java @@ -1,10 +1,22 @@ package net.firedevops.firemud.loggingadmin.dto; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Size; +import com.google.protobuf.ByteString; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +/** The immutable Account audit envelope accepted by the existing CreateLogEvent RPC. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Protobuf ByteString is immutable, so retaining and exposing the payload is safe.") public record CreateLogEventRequest( - @NotNull Long tenantId, - Long accountId, - @NotNull @Size(max = 50) String type, - @NotNull @Size(max = 255) String message) {} + AccountAuditScope scope, + Long tenantId, + String auditEventId, + String producerService, + String eventType, + Instant occurredAt, + int schemaVersion, + ByteString payload, + int payloadDigestVersion, + String payloadDigest) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java new file mode 100644 index 0000000000..9e04277e29 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.loggingadmin.entity; + +import java.util.UUID; + +/** A durable receiver-side audit envelope and its readback receipt. */ +public record AccountAuditReceipt( + long id, + UUID receiptId, + String scope, + Long tenantId, + String auditEventId, + String producerService, + String eventType, + long occurredAtSeconds, + int occurredAtNanos, + int schemaVersion, + int payloadDigestVersion, + String payloadDigest, + byte[] payload, + String status, + String outcome) { + public AccountAuditReceipt { + payload = payload == null ? null : payload.clone(); + } + + @Override + public byte[] payload() { + return payload == null ? null : payload.clone(); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java new file mode 100644 index 0000000000..226e9d4046 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceiptInsertResult.java @@ -0,0 +1,3 @@ +package net.firedevops.firemud.loggingadmin.entity; + +public record AccountAuditReceiptInsertResult(AccountAuditReceipt receipt, boolean inserted) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java new file mode 100644 index 0000000000..bcaffd3767 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.loggingadmin.repository; + +import static net.firedevops.firemud.loggingadmin.jooq.tables.AccountAuditReceipts.ACCOUNT_AUDIT_RECEIPTS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceipt; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceiptInsertResult; +import net.firedevops.firemud.loggingadmin.jooq.tables.records.AccountAuditReceiptsRecord; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountAuditReceiptRepository { + private final DSLContext dsl; + + public AccountAuditReceiptRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public AccountAuditReceiptInsertResult insertIfAbsent( + CreateLogEventRequest request, UUID receiptId) { + long tenantKey = request.tenantId() == null ? 0L : request.tenantId(); + int inserted = + dsl.insertInto(ACCOUNT_AUDIT_RECEIPTS) + .set(ACCOUNT_AUDIT_RECEIPTS.RECEIPT_ID, receiptId) + .set(ACCOUNT_AUDIT_RECEIPTS.SCOPE, request.scope().databaseValue()) + .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_ID, request.tenantId()) + .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY, tenantKey) + .set(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID, request.auditEventId()) + .set(ACCOUNT_AUDIT_RECEIPTS.PRODUCER_SERVICE, request.producerService()) + .set(ACCOUNT_AUDIT_RECEIPTS.EVENT_TYPE, request.eventType()) + .set(ACCOUNT_AUDIT_RECEIPTS.OCCURRED_AT_SECONDS, request.occurredAt().getEpochSecond()) + .set(ACCOUNT_AUDIT_RECEIPTS.OCCURRED_AT_NANOS, request.occurredAt().getNano()) + .set(ACCOUNT_AUDIT_RECEIPTS.SCHEMA_VERSION, request.schemaVersion()) + .set(ACCOUNT_AUDIT_RECEIPTS.PAYLOAD_DIGEST_VERSION, request.payloadDigestVersion()) + .set(ACCOUNT_AUDIT_RECEIPTS.PAYLOAD_DIGEST, request.payloadDigest()) + .set(ACCOUNT_AUDIT_RECEIPTS.PAYLOAD, request.payload().toByteArray()) + .set(ACCOUNT_AUDIT_RECEIPTS.STATUS, "COMMITTED") + .set(ACCOUNT_AUDIT_RECEIPTS.OUTCOME, "ACCEPTED") + .onConflictDoNothing() + .execute(); + AccountAuditReceipt receipt = + findByIdentity(request, tenantKey) + .orElseThrow( + () -> + new IllegalStateException( + "Account audit receipt identity conflict did not resolve to a receipt")); + return new AccountAuditReceiptInsertResult(receipt, inserted == 1); + } + + public Optional findByIdentity( + CreateLogEventRequest request, long tenantKey) { + return dsl.selectFrom(ACCOUNT_AUDIT_RECEIPTS) + .where( + ACCOUNT_AUDIT_RECEIPTS + .SCOPE + .eq(request.scope().databaseValue()) + .and(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY.eq(tenantKey)) + .and(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(request.auditEventId()))) + .fetchOptional(this::toEntity); + } + + private AccountAuditReceipt toEntity(Record record) { + AccountAuditReceiptsRecord receiptRecord = (AccountAuditReceiptsRecord) record; + return new AccountAuditReceipt( + receiptRecord.getId(), + receiptRecord.getReceiptId(), + receiptRecord.getScope(), + receiptRecord.getTenantId(), + receiptRecord.getAuditEventId(), + receiptRecord.getProducerService(), + receiptRecord.getEventType(), + receiptRecord.getOccurredAtSeconds(), + receiptRecord.getOccurredAtNanos(), + receiptRecord.getSchemaVersion(), + receiptRecord.getPayloadDigestVersion(), + receiptRecord.getPayloadDigest(), + receiptRecord.getPayload(), + receiptRecord.getStatus(), + receiptRecord.getOutcome()); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java new file mode 100644 index 0000000000..52b49613b5 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditReceiptNotFoundException.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.loggingadmin.service; + +public class AuditReceiptNotFoundException extends RuntimeException { + public AuditReceiptNotFoundException() { + super("Account audit receipt not found"); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java new file mode 100644 index 0000000000..c8abf99170 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/AuditStorageUnavailableException.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.loggingadmin.service; + +public class AuditStorageUnavailableException extends RuntimeException { + public AuditStorageUnavailableException(Throwable cause) { + super("Account audit receipt storage is unavailable", cause); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java index 0617b3ad2e..e86cc22dc0 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/LogEventService.java @@ -1,8 +1,10 @@ package net.firedevops.firemud.loggingadmin.service; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; -import net.firedevops.firemud.loggingadmin.dto.LogEventDto; public interface LogEventService { - LogEventDto createLogEvent(CreateLogEventRequest request); + AccountAuditReceiptDto createLogEvent(CreateLogEventRequest request); + + AccountAuditReceiptDto readLogEventReceipt(CreateLogEventRequest request); } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java index fc3c54d6a0..6d87af4ef8 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java @@ -1,14 +1,28 @@ package net.firedevops.firemud.loggingadmin.service.impl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import io.micrometer.core.annotation.Timed; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; -import net.firedevops.firemud.loggingadmin.dto.LogEventDto; -import net.firedevops.firemud.loggingadmin.entity.LogEvent; -import net.firedevops.firemud.loggingadmin.repository.LogEventRepository; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceipt; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceiptInsertResult; +import net.firedevops.firemud.loggingadmin.repository.AccountAuditReceiptRepository; +import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; +import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; import net.firedevops.firemud.loggingadmin.service.LogEventService; +import org.jooq.exception.DataAccessException; import org.slf4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -19,31 +33,184 @@ justification = "Spring injects the shared repository singleton for this service seam.") public class LogEventServiceImpl implements LogEventService { private static final Logger logger = LoggingUtil.getLogger(LogEventServiceImpl.class); + private static final String ACCOUNT_SERVICE = "account-service"; + private static final String SHA_256_PREFIX = "sha256:"; - private final LogEventRepository repository; + private final AccountAuditReceiptRepository repository; - public LogEventServiceImpl(LogEventRepository repository) { + public LogEventServiceImpl(AccountAuditReceiptRepository repository) { this.repository = repository; } @Override @Transactional - @Timed(value = "logging.createLogEvent") - public LogEventDto createLogEvent(CreateLogEventRequest request) { - logger.info("Creating log event {} for tenant {}", request.type(), request.tenantId()); - LogEvent entity = new LogEvent(); - entity.setTenantId(request.tenantId()); - entity.setAccountId(request.accountId()); - entity.setType(request.type()); - entity.setMessage(request.message()); - entity.setTimestamp(Instant.now()); - entity = repository.save(entity); - return new LogEventDto( - entity.getId(), - entity.getTenantId(), - entity.getAccountId(), - entity.getType(), - entity.getMessage(), - entity.getTimestamp()); + public AccountAuditReceiptDto createLogEvent(CreateLogEventRequest request) { + validateEnvelope(request); + try { + AccountAuditReceiptInsertResult result = + repository.insertIfAbsent(request, UUID.randomUUID()); + return receiptOutcome(result.receipt(), request, result.inserted()); + } catch (DataAccessException ex) { + logger.warn("Account audit receipt write is unavailable: {}", ex.getClass().getSimpleName()); + throw new AuditStorageUnavailableException(ex); + } + } + + @Override + @Transactional(readOnly = true) + public AccountAuditReceiptDto readLogEventReceipt(CreateLogEventRequest request) { + validateEnvelope(request); + try { + long tenantKey = request.tenantId() == null ? 0L : request.tenantId(); + AccountAuditReceipt receipt = + repository + .findByIdentity(request, tenantKey) + .orElseThrow(AuditReceiptNotFoundException::new); + return receiptOutcome(receipt, request, false); + } catch (AuditReceiptNotFoundException ex) { + throw ex; + } catch (DataAccessException ex) { + logger.warn("Account audit receipt read is unavailable: {}", ex.getClass().getSimpleName()); + throw new AuditStorageUnavailableException(ex); + } + } + + private static AccountAuditReceiptDto receiptOutcome( + AccountAuditReceipt receipt, CreateLogEventRequest request, boolean inserted) { + if (inserted) { + return toDto( + receipt, AccountAuditReceiptStatus.COMMITTED, AccountAuditReceiptOutcome.ACCEPTED); + } + + boolean metadataMatches = metadataMatches(receipt, request); + if (!metadataMatches) { + return toDto( + receipt, + AccountAuditReceiptStatus.CONFLICT, + AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT); + } + + byte[] retainedPayload = receipt.payload(); + if (retainedPayload == null) { + return toDto( + receipt, AccountAuditReceiptStatus.MINIMIZED, AccountAuditReceiptOutcome.NON_REPLAYABLE); + } + if (!Arrays.equals(retainedPayload, request.payload().toByteArray())) { + return toDto( + receipt, + AccountAuditReceiptStatus.CONFLICT, + AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT); + } + + if ("MINIMIZED".equals(receipt.status()) || "NON_REPLAYABLE".equals(receipt.outcome())) { + return toDto( + receipt, AccountAuditReceiptStatus.MINIMIZED, AccountAuditReceiptOutcome.NON_REPLAYABLE); + } + if (!"COMMITTED".equals(receipt.status())) { + throw new IllegalStateException("Unknown persisted account audit receipt status"); + } + return toDto( + receipt, AccountAuditReceiptStatus.COMMITTED, AccountAuditReceiptOutcome.DUPLICATE); + } + + private static boolean metadataMatches( + AccountAuditReceipt receipt, CreateLogEventRequest request) { + Instant occurredAt = request.occurredAt(); + return receipt.scope().equals(request.scope().databaseValue()) + && Objects.equals(receipt.tenantId(), request.tenantId()) + && receipt.auditEventId().equals(request.auditEventId()) + && receipt.producerService().equals(request.producerService()) + && receipt.eventType().equals(request.eventType()) + && receipt.occurredAtSeconds() == occurredAt.getEpochSecond() + && receipt.occurredAtNanos() == occurredAt.getNano() + && receipt.schemaVersion() == request.schemaVersion() + && receipt.payloadDigestVersion() == request.payloadDigestVersion() + && receipt.payloadDigest().equals(request.payloadDigest()); + } + + private static AccountAuditReceiptDto toDto( + AccountAuditReceipt receipt, + AccountAuditReceiptStatus status, + AccountAuditReceiptOutcome outcome) { + return new AccountAuditReceiptDto( + "platform".equals(receipt.scope()) + ? net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.PLATFORM + : net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.TENANT, + receipt.tenantId(), + receipt.auditEventId(), + receipt.receiptId().toString(), + receipt.id(), + receipt.schemaVersion(), + receipt.payloadDigestVersion(), + receipt.payloadDigest(), + status, + outcome); + } + + private static void validateEnvelope(CreateLogEventRequest request) { + if (request == null + || request.scope() == null + || request.auditEventId() == null + || request.auditEventId().isBlank() + || request.producerService() == null + || !ACCOUNT_SERVICE.equals(request.producerService()) + || request.eventType() == null + || request.eventType().isBlank() + || request.occurredAt() == null + || request.schemaVersion() <= 0 + || request.payload() == null + || request.payloadDigest() == null) { + throw new IllegalArgumentException("Account audit envelope is incomplete"); + } + if (!isCanonicalUuid(request.auditEventId())) { + throw new IllegalArgumentException("auditEventId must be a canonical UUID"); + } + if (request.scope() == net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.PLATFORM) { + if (request.tenantId() != null) { + throw new IllegalArgumentException("tenantId must be absent for platform scope"); + } + } else if (request.tenantId() == null || request.tenantId() <= 0) { + throw new IllegalArgumentException("tenantId must be positive for tenant scope"); + } + if (request.payloadDigestVersion() != 1) { + throw new IllegalArgumentException("payloadDigestVersion must be 1"); + } + if (!request.payloadDigest().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("payloadDigest must be lowercase sha256 hex"); + } + byte[] payloadBytes = request.payload().toByteArray(); + validateUtf8(payloadBytes); + String computedDigest = SHA_256_PREFIX + sha256Hex(payloadBytes); + if (!computedDigest.equals(request.payloadDigest())) { + throw new IllegalArgumentException("payloadDigest does not match the exact payload bytes"); + } + } + + private static boolean isCanonicalUuid(String value) { + try { + return value.equals(UUID.fromString(value).toString()); + } catch (IllegalArgumentException ex) { + return false; + } + } + + private static void validateUtf8(byte[] payload) { + try { + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(payload)); + } catch (CharacterCodingException ex) { + throw new IllegalArgumentException("payload must contain exact UTF-8 bytes", ex); + } + } + + private static String sha256Hex(byte[] payload) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java index 928418f154..5f138cff0e 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java @@ -1,23 +1,39 @@ package net.firedevops.firemud.loggingadmin.service.impl; +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.time.Instant; import java.util.List; +import java.util.Map; import java.util.Set; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; +import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; import net.firedevops.firemud.loggingadmin.service.LogEventService; import net.firedevops.firemud.loggingadmin.service.LogQueryService; import net.firedevops.firemud.loggingadmin.service.ModerationService; import net.firedevops.firemud.loggingadmin.v1.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.TransactionException; @GrpcService public class LoggingAdminGrpcService extends LoggingAdminServiceGrpc.LoggingAdminServiceImplBase { @@ -28,10 +44,16 @@ public class LoggingAdminGrpcService extends LoggingAdminServiceGrpc.LoggingAdmi "Feature-flag toggles are unavailable until the shared mutation gate is implemented"; private static final Set MODERATION_POLICY_CALLERS = Set.of("game-session-service", "social-groups-service"); + private static final String ACCOUNT_SERVICE = "account-service"; + private static final Map> ACCOUNT_AUDIT_CALLER_ALLOWLIST = + Map.of( + "CreateLogEvent", Set.of(ACCOUNT_SERVICE), + "ReadLogEventReceipt", Set.of(ACCOUNT_SERVICE)); private final LogQueryService logQueryService; private final LogEventService logEventService; private final ModerationService moderationService; + private final String workloadNamespace; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -43,10 +65,21 @@ public LoggingAdminGrpcService( LogEventService logEventService, ModerationService moderationService, MeterRegistry meterRegistry) { + this(logQueryService, logEventService, moderationService, meterRegistry, null); + } + + @Autowired + public LoggingAdminGrpcService( + LogQueryService logQueryService, + LogEventService logEventService, + ModerationService moderationService, + MeterRegistry meterRegistry, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.logQueryService = logQueryService; this.logEventService = logEventService; this.moderationService = moderationService; this.meterRegistry = meterRegistry; + this.workloadNamespace = workloadNamespace; } @Override @@ -174,49 +207,225 @@ public void queryLogs( public void createLogEvent( CreateLogEventRequest request, StreamObserver responseObserver) { try { - AdminRoleGuard.requireAdminRole(); - var dto = - logEventService.createLogEvent( - new net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.parseOptionalPositiveLong( - request.getAccountId(), "accountId"), - request.getType(), - request.getMessage())); - CreateLogEventResponse response = - CreateLogEventResponse.newBuilder().setLogEventId(String.valueOf(dto.id())).build(); + requireAccountAuditCaller("CreateLogEvent"); + AccountAuditReceiptDto receipt = logEventService.createLogEvent(toAuditRequest(request)); + CreateLogEventResponse response = toCreateLogEventResponse(receipt); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { - CreateLogEventResponse response = - CreateLogEventResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "CreateLogEvent", - "PERMISSION_DENIED", - ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); + responseObserver.onError( + Status.PERMISSION_DENIED.withDescription(ex.getMessage()).asRuntimeException()); } catch (IllegalArgumentException ex) { - CreateLogEventResponse response = - CreateLogEventResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "CreateLogEvent", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); + responseObserver.onError( + Status.INVALID_ARGUMENT.withDescription(ex.getMessage()).asRuntimeException()); + } catch (AuditStorageUnavailableException ex) { + responseObserver.onError( + Status.UNAVAILABLE.withDescription(ex.getMessage()).asRuntimeException()); + } catch (DataAccessException | TransactionException ex) { + logger.warn("CreateLogEvent transaction is unavailable: {}", ex.getClass().getSimpleName()); + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Account audit ingress storage is unavailable") + .asRuntimeException()); } catch (Exception ex) { - CreateLogEventResponse response = - CreateLogEventResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "CreateLogEvent", ex)) - .build(); - responseObserver.onNext(response); + logger.error("CreateLogEvent failed before producing an audit receipt", ex); + responseObserver.onError( + Status.INTERNAL.withDescription("Account audit ingress failed").asRuntimeException()); + } + } + + @Override + @Timed(value = "loggingadminGrpc.readLogEventReceipt") + public void readLogEventReceipt( + ReadLogEventReceiptRequest request, + StreamObserver responseObserver) { + try { + requireAccountAuditCaller("ReadLogEventReceipt"); + AccountAuditReceiptDto receipt = logEventService.readLogEventReceipt(toAuditRequest(request)); + responseObserver.onNext(toReadLogEventReceiptResponse(receipt)); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onError( + Status.PERMISSION_DENIED.withDescription(ex.getMessage()).asRuntimeException()); + } catch (IllegalArgumentException ex) { + responseObserver.onError( + Status.INVALID_ARGUMENT.withDescription(ex.getMessage()).asRuntimeException()); + } catch (AuditReceiptNotFoundException ex) { + responseObserver.onError( + Status.NOT_FOUND.withDescription(ex.getMessage()).asRuntimeException()); + } catch (AuditStorageUnavailableException ex) { + responseObserver.onError( + Status.UNAVAILABLE.withDescription(ex.getMessage()).asRuntimeException()); + } catch (DataAccessException | TransactionException ex) { + logger.warn( + "ReadLogEventReceipt transaction is unavailable: {}", ex.getClass().getSimpleName()); + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Account audit receipt storage is unavailable") + .asRuntimeException()); + } catch (Exception ex) { + logger.error("ReadLogEventReceipt failed before producing a receipt", ex); + responseObserver.onError( + Status.INTERNAL + .withDescription("Account audit receipt read failed") + .asRuntimeException()); + } + } + + private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toAuditRequest( + CreateLogEventRequest request) { + return toAuditRequest( + request.getScope(), + request.getTenantId(), + request.getAuditEventId(), + request.getProducerService(), + request.getEventType(), + request.hasOccurredAt() ? request.getOccurredAt() : null, + request.getSchemaVersion(), + request.getPayload(), + request.getPayloadDigestVersion(), + request.getPayloadDigest()); + } + + private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toAuditRequest( + ReadLogEventReceiptRequest request) { + return toAuditRequest( + request.getScope(), + request.getTenantId(), + request.getAuditEventId(), + request.getProducerService(), + request.getEventType(), + request.hasOccurredAt() ? request.getOccurredAt() : null, + request.getSchemaVersion(), + request.getPayload(), + request.getPayloadDigestVersion(), + request.getPayloadDigest()); + } + + private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toAuditRequest( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope requestScope, + String tenantIdText, + String auditEventId, + String producerService, + String eventType, + Timestamp occurredAt, + int schemaVersion, + ByteString payload, + int payloadDigestVersion, + String payloadDigest) { + AccountAuditScope scope = + switch (requestScope) { + case ACCOUNT_AUDIT_SCOPE_PLATFORM -> AccountAuditScope.PLATFORM; + case ACCOUNT_AUDIT_SCOPE_TENANT -> AccountAuditScope.TENANT; + default -> throw new IllegalArgumentException("scope must be platform or tenant"); + }; + Long tenantId; + if (scope == AccountAuditScope.TENANT) { + tenantId = RequestIdValidation.requirePositiveLong(tenantIdText, "tenantId"); + } else { + if (!tenantIdText.isEmpty()) { + throw new IllegalArgumentException("tenantId must be absent for platform scope"); + } + tenantId = null; + } + if (!ACCOUNT_SERVICE.equals(producerService)) { + throw new IllegalArgumentException( + "producerService must match the authenticated account-service workload"); + } + if (occurredAt == null) { + throw new IllegalArgumentException("occurredAt is required"); + } + if (occurredAt.getSeconds() < -62135596800L + || occurredAt.getSeconds() > 253402300799L + || occurredAt.getNanos() < 0 + || occurredAt.getNanos() > 999999999) { + throw new IllegalArgumentException("occurredAt must be a valid protobuf timestamp"); } + return new net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest( + scope, + tenantId, + auditEventId, + ACCOUNT_SERVICE, + eventType, + Instant.ofEpochSecond(occurredAt.getSeconds(), occurredAt.getNanos()), + schemaVersion, + payload, + payloadDigestVersion, + payloadDigest); + } + + private static CreateLogEventResponse toCreateLogEventResponse(AccountAuditReceiptDto receipt) { + return CreateLogEventResponse.newBuilder() + .setScope(toProtoScope(receipt.scope())) + .setTenantId(receipt.tenantId() == null ? "" : receipt.tenantId().toString()) + .setAuditEventId(receipt.auditEventId()) + .setReceiptId(receipt.receiptId()) + .setLogEventId(Long.toString(receipt.logEventId())) + .setSchemaVersion(receipt.schemaVersion()) + .setPayloadDigestVersion(receipt.payloadDigestVersion()) + .setPayloadDigest(receipt.payloadDigest()) + .setStatus(toProtoStatus(receipt.status())) + .setOutcome(toProtoOutcome(receipt.outcome())) + .build(); + } + + private static ReadLogEventReceiptResponse toReadLogEventReceiptResponse( + AccountAuditReceiptDto receipt) { + return ReadLogEventReceiptResponse.newBuilder() + .setScope(toProtoScope(receipt.scope())) + .setTenantId(receipt.tenantId() == null ? "" : receipt.tenantId().toString()) + .setAuditEventId(receipt.auditEventId()) + .setReceiptId(receipt.receiptId()) + .setLogEventId(Long.toString(receipt.logEventId())) + .setSchemaVersion(receipt.schemaVersion()) + .setPayloadDigestVersion(receipt.payloadDigestVersion()) + .setPayloadDigest(receipt.payloadDigest()) + .setStatus(toProtoStatus(receipt.status())) + .setOutcome(toProtoOutcome(receipt.outcome())) + .build(); + } + + private static net.firedevops.firemud.loggingadmin.v1.AccountAuditScope toProtoScope( + AccountAuditScope scope) { + return switch (scope) { + case PLATFORM -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM; + case TENANT -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT; + }; + } + + private static net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus toProtoStatus( + AccountAuditReceiptStatus status) { + return switch (status) { + case COMMITTED -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED; + case MINIMIZED -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED; + case CONFLICT -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_CONFLICT; + }; + } + + private static net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome toProtoOutcome( + AccountAuditReceiptOutcome outcome) { + return switch (outcome) { + case ACCEPTED -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED; + case DUPLICATE -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE; + case NON_REPLAYABLE -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE; + case IDEMPOTENCY_CONFLICT -> + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_IDEMPOTENCY_CONFLICT; + }; } @Override @@ -353,4 +562,19 @@ private static void requireAllowlistedInternalService( methodName + " requires an allowlisted internal service caller"); } } + + private void requireAccountAuditCaller(String methodName) { + Set allowedServices = ACCOUNT_AUDIT_CALLER_ALLOWLIST.get(methodName); + GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); + if (allowedServices == null + || peerIdentity == null + || !allowedServices.contains(peerIdentity.service()) + || workloadNamespace == null + || workloadNamespace.isBlank() + || !("spiffe://firemud/ns/" + workloadNamespace + "/sa/" + ACCOUNT_SERVICE) + .equals(peerIdentity.uri())) { + throw new AdminAuthorizationException( + methodName + " requires an allowlisted account-service mTLS peer"); + } + } } diff --git a/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql b/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql new file mode 100644 index 0000000000..4e1a61f25a --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V2__account_audit_receipts.sql @@ -0,0 +1,47 @@ +CREATE TABLE account_audit_receipts ( + id BIGSERIAL PRIMARY KEY, + receipt_id UUID NOT NULL UNIQUE, + scope VARCHAR(16) NOT NULL, + tenant_id BIGINT, + tenant_key BIGINT NOT NULL, + audit_event_id VARCHAR(36) NOT NULL, + producer_service TEXT NOT NULL, + event_type TEXT NOT NULL, + occurred_at_seconds BIGINT NOT NULL, + occurred_at_nanos INTEGER NOT NULL, + schema_version INTEGER NOT NULL, + payload_digest_version INTEGER NOT NULL, + payload_digest TEXT NOT NULL, + payload BYTEA, + status VARCHAR(16) NOT NULL, + outcome VARCHAR(32) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT chk_account_audit_receipt_scope + CHECK ( + (scope = 'platform' AND tenant_id IS NULL AND tenant_key = 0) + OR ( + scope = 'tenant' + AND tenant_id IS NOT NULL + AND tenant_id > 0 + AND tenant_key = tenant_id + ) + ), + CONSTRAINT chk_account_audit_receipt_occurred_at_nanos + CHECK (occurred_at_nanos BETWEEN 0 AND 999999999), + CONSTRAINT chk_account_audit_receipt_versions + CHECK (schema_version > 0 AND payload_digest_version = 1), + CONSTRAINT chk_account_audit_receipt_digest + CHECK (payload_digest LIKE 'sha256:%' AND length(payload_digest) = 71), + CONSTRAINT chk_account_audit_receipt_terminal_state + CHECK ( + (status = 'COMMITTED' AND outcome IN ('ACCEPTED', 'DUPLICATE') AND payload IS NOT NULL) + OR (status = 'MINIMIZED' AND outcome = 'NON_REPLAYABLE' AND payload IS NULL) + ) +); + +CREATE UNIQUE INDEX uq_account_audit_receipt_identity + ON account_audit_receipts (scope, tenant_key, audit_event_id); + +CREATE INDEX idx_account_audit_receipts_tenant_event + ON account_audit_receipts (tenant_id, audit_event_id) + WHERE scope = 'tenant'; diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java new file mode 100644 index 0000000000..130443b4b4 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java @@ -0,0 +1,212 @@ +package net.firedevops.firemud.loggingadmin.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceipt; +import net.firedevops.firemud.loggingadmin.entity.AccountAuditReceiptInsertResult; +import net.firedevops.firemud.loggingadmin.repository.AccountAuditReceiptRepository; +import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class LogEventServiceImplTest { + private static final String AUDIT_EVENT_ID = "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3"; + private static final UUID RECEIPT_ID = UUID.fromString("c0c1f03b-31b7-4281-aaf8-2d66f29e8770"); + + private final AccountAuditReceiptRepository repository = + Mockito.mock(AccountAuditReceiptRepository.class); + private final LogEventServiceImpl service = new LogEventServiceImpl(repository); + + @Test + void firstWriteReturnsCommittedAcceptedReceipt() { + CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + AccountAuditReceipt receipt = + receipt(request, request.payload().toByteArray(), "COMMITTED", "ACCEPTED"); + when(repository.insertIfAbsent(eq(request), any(UUID.class))) + .thenReturn(new AccountAuditReceiptInsertResult(receipt, true)); + + var result = service.createLogEvent(request); + + assertEquals(AccountAuditReceiptStatus.COMMITTED, result.status()); + assertEquals(AccountAuditReceiptOutcome.ACCEPTED, result.outcome()); + assertEquals(91L, result.logEventId()); + verify(repository).insertIfAbsent(eq(request), any(UUID.class)); + } + + @Test + void exactRetryReturnsOriginalReceiptAsDuplicate() { + CreateLogEventRequest request = request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{}"); + AccountAuditReceipt receipt = + receipt(request, request.payload().toByteArray(), "COMMITTED", "ACCEPTED"); + when(repository.insertIfAbsent(eq(request), any(UUID.class))) + .thenReturn(new AccountAuditReceiptInsertResult(receipt, false)); + + var result = service.createLogEvent(request); + + assertEquals(AccountAuditReceiptStatus.COMMITTED, result.status()); + assertEquals(AccountAuditReceiptOutcome.DUPLICATE, result.outcome()); + assertEquals(42L, result.tenantId()); + } + + @Test + void changedImmutableMetadataReturnsIdempotencyConflict() { + CreateLogEventRequest original = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + CreateLogEventRequest changed = + request(AccountAuditScope.PLATFORM, null, Instant.EPOCH.plusSeconds(1), "{}"); + when(repository.insertIfAbsent(eq(changed), any(UUID.class))) + .thenReturn( + new AccountAuditReceiptInsertResult( + receipt(original, original.payload().toByteArray(), "COMMITTED", "ACCEPTED"), + false)); + + var result = service.createLogEvent(changed); + + assertEquals(AccountAuditReceiptStatus.CONFLICT, result.status()); + assertEquals(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT, result.outcome()); + } + + @Test + void minimizedRetryIsSuccessfulButNonReplayable() { + CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + when(repository.insertIfAbsent(eq(request), any(UUID.class))) + .thenReturn( + new AccountAuditReceiptInsertResult( + receipt(request, null, "MINIMIZED", "NON_REPLAYABLE"), false)); + + var result = service.createLogEvent(request); + + assertEquals(AccountAuditReceiptStatus.MINIMIZED, result.status()); + assertEquals(AccountAuditReceiptOutcome.NON_REPLAYABLE, result.outcome()); + } + + @Test + void missingReadbackThrowsForCanonicalNotFoundMapping() { + CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + when(repository.findByIdentity(request, 0L)).thenReturn(Optional.empty()); + + assertThrows(AuditReceiptNotFoundException.class, () -> service.readLogEventReceipt(request)); + } + + @Test + void unsupportedDigestVersionFailsBeforeRepositoryAccess() { + CreateLogEventRequest valid = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + CreateLogEventRequest unsupported = + new CreateLogEventRequest( + valid.scope(), + valid.tenantId(), + valid.auditEventId(), + valid.producerService(), + valid.eventType(), + valid.occurredAt(), + valid.schemaVersion(), + valid.payload(), + 2, + valid.payloadDigest()); + + assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(unsupported)); + verifyNoInteractions(repository); + } + + @Test + void payloadDigestMismatchFailsBeforeRepositoryAccess() { + CreateLogEventRequest valid = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + CreateLogEventRequest mismatched = + new CreateLogEventRequest( + valid.scope(), + valid.tenantId(), + valid.auditEventId(), + valid.producerService(), + valid.eventType(), + valid.occurredAt(), + valid.schemaVersion(), + valid.payload(), + valid.payloadDigestVersion(), + "sha256:" + "0".repeat(64)); + + assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(mismatched)); + verifyNoInteractions(repository); + } + + @Test + void invalidUtf8PayloadFailsBeforeRepositoryAccess() { + ByteString payload = ByteString.copyFrom(new byte[] {(byte) 0xff}); + CreateLogEventRequest request = + new CreateLogEventRequest( + AccountAuditScope.PLATFORM, + null, + AUDIT_EVENT_ID, + "account-service", + "ACCOUNT_REGISTERED", + Instant.EPOCH, + 1, + payload, + 1, + digest(payload.toByteArray())); + + assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(request)); + verifyNoInteractions(repository); + } + + private static CreateLogEventRequest request( + AccountAuditScope scope, Long tenantId, Instant occurredAt, String payloadText) { + ByteString payload = ByteString.copyFrom(payloadText, StandardCharsets.UTF_8); + return new CreateLogEventRequest( + scope, + tenantId, + AUDIT_EVENT_ID, + "account-service", + "ACCOUNT_REGISTERED", + occurredAt, + 1, + payload, + 1, + digest(payload.toByteArray())); + } + + private static AccountAuditReceipt receipt( + CreateLogEventRequest request, byte[] payload, String status, String outcome) { + return new AccountAuditReceipt( + 91L, + RECEIPT_ID, + request.scope().databaseValue(), + request.tenantId(), + request.auditEventId(), + request.producerService(), + request.eventType(), + request.occurredAt().getEpochSecond(), + request.occurredAt().getNano(), + request.schemaVersion(), + request.payloadDigestVersion(), + request.payloadDigest(), + payload, + status, + outcome); + } + + private static String digest(byte[] payload) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException(ex); + } + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index 8a3df2b5fd..2a5c7658ee 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -1,23 +1,49 @@ package net.firedevops.firemud.loggingadmin.service.impl; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.protobuf.ProtoUtils; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.time.Instant; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; import net.firedevops.firemud.common.security.SessionContext; -import net.firedevops.firemud.loggingadmin.dto.LogEventDto; +import net.firedevops.firemud.loggingadmin.config.AccountAuditGrpcAuthConfiguration; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditScope; import net.firedevops.firemud.loggingadmin.dto.ModerationPolicyDecisionDto; +import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; +import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; import net.firedevops.firemud.loggingadmin.service.LogEventService; import net.firedevops.firemud.loggingadmin.service.LogQueryService; import net.firedevops.firemud.loggingadmin.service.ModerationService; @@ -29,11 +55,16 @@ import net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse; import net.firedevops.firemud.loggingadmin.v1.QueryLogsRequest; import net.firedevops.firemud.loggingadmin.v1.QueryLogsResponse; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptResponse; import net.firedevops.firemud.loggingadmin.v1.ToggleFeatureFlagRequest; import net.firedevops.firemud.loggingadmin.v1.ToggleFeatureFlagResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; class LoggingAdminGrpcServiceAuthTest { @AfterEach @@ -41,6 +72,38 @@ void tearDown() { SessionContext.clear(); } + @Test + void auditMethodsBypassJwtRequirementButOtherMethodsRemainProtected() { + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class)) + .withUserConfiguration(AccountAuditGrpcAuthConfiguration.class) + .withPropertyValues( + "firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234", + "firemud.auth.grpc.public-methods[0]=logging_admin.v1.LoggingAdminService/Ping") + .run( + context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + GrpcAuthProperties properties = context.getBean(GrpcAuthProperties.class); + assertThat(properties.getPublicMethods()) + .containsExactly("logging_admin.v1.LoggingAdminService/Ping"); + AuthTokenInterceptor interceptor = context.getBean(AuthTokenInterceptor.class); + assertTrue( + passesWithoutBearer( + interceptor, "logging_admin.v1.LoggingAdminService/CreateLogEvent")); + assertTrue( + passesWithoutBearer( + interceptor, "logging_admin.v1.LoggingAdminService/ReadLogEventReceipt")); + assertTrue( + passesWithoutBearer(interceptor, "logging_admin.v1.LoggingAdminService/Ping")); + assertFalse( + passesWithoutBearer( + interceptor, "logging_admin.v1.LoggingAdminService/QueryLogs")); + }); + } + @Test void adminMethodsReturnPermissionDeniedErrorDetail() { SessionContext.setContext("1", List.of("player"), Map.of()); @@ -73,53 +136,167 @@ public void onCompleted() {} } @Test - void createLogEventUsesLogEventServiceWithoutCallingModeration() { - SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + void accountMtlSPeerCreatesReceiptWithoutJwtOrAdminRole() { LogEventService logEventService = Mockito.mock(LogEventService.class); ModerationService moderationService = Mockito.mock(ModerationService.class); + String digest = digest("{\"accountId\":42}".getBytes(StandardCharsets.UTF_8)); when(logEventService.createLogEvent(any())) .thenReturn( - new LogEventDto( + new AccountAuditReceiptDto( + AccountAuditScope.PLATFORM, + null, + "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3", + "receipt-1", 77L, - 1L, - 42L, - "ACCOUNT_CREATED", - "account created", - Instant.parse("2026-01-01T00:00:00Z"))); + 1, + 1, + digest, + AccountAuditReceiptStatus.COMMITTED, + AccountAuditReceiptOutcome.ACCEPTED)); LoggingAdminGrpcService service = new LoggingAdminGrpcService( Mockito.mock(LogQueryService.class), logEventService, moderationService, - new SimpleMeterRegistry()); + new SimpleMeterRegistry(), + "firemud"); AtomicReference ref = new AtomicReference<>(); - service.createLogEvent( - CreateLogEventRequest.newBuilder() - .setTenantId("1") - .setAccountId("42") - .setType("ACCOUNT_CREATED") - .setMessage("account created") - .build(), - new StreamObserver<>() { - @Override - public void onNext(CreateLogEventResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + AtomicReference error = new AtomicReference<>(); + invokeWithPeer( + "account-service", + () -> service.createLogEvent(validCreateRequest(), responseObserver(ref, error))); assertNotNull(ref.get()); assertEquals("77", ref.get().getLogEventId()); + assertEquals( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM, + ref.get().getScope()); + assertEquals( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED, + ref.get().getStatus()); + assertEquals( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED, + ref.get().getOutcome()); + assertNull(error.get()); verify(logEventService).createLogEvent(any()); verify(moderationService, never()).applyAction(any()); } + @Test + void adminJwtClaimsDoNotAuthorizeAuditIngressWithoutAccountPeer() { + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + LogEventService logEventService = Mockito.mock(LogEventService.class); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + service.createLogEvent(validCreateRequest(), responseObserver(response, error)); + + assertEquals(Status.Code.PERMISSION_DENIED, Status.fromThrowable(error.get()).getCode()); + verifyNoInteractions(logEventService); + } + + @Test + void jwtClaimNamingAccountServiceCannotOverrideWrongMtlsPeer() { + SessionContext.setContext(null, List.of(), Map.of(), true, "account-service", "instance-1"); + LogEventService logEventService = Mockito.mock(LogEventService.class); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "game-session-service", + () -> service.createLogEvent(validCreateRequest(), responseObserver(response, error))); + + assertEquals(Status.Code.PERMISSION_DENIED, Status.fromThrowable(error.get()).getCode()); + verifyNoInteractions(logEventService); + } + + @Test + void accountAuditRejectsAccountServicePeerFromOtherNamespace() { + LogEventService logEventService = Mockito.mock(LogEventService.class); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "other", + "account-service", + () -> service.createLogEvent(validCreateRequest(), responseObserver(response, error))); + + assertEquals(Status.Code.PERMISSION_DENIED, Status.fromThrowable(error.get()).getCode()); + verifyNoInteractions(logEventService); + } + + @Test + void receiptReadReturnsCanonicalNotFoundStatus() { + LogEventService logEventService = Mockito.mock(LogEventService.class); + when(logEventService.readLogEventReceipt(any())).thenThrow(new AuditReceiptNotFoundException()); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "account-service", + () -> service.readLogEventReceipt(validReadRequest(), responseObserver(response, error))); + + assertEquals(Status.Code.NOT_FOUND, Status.fromThrowable(error.get()).getCode()); + assertNull(response.get()); + } + + @Test + void accountMtlSPeerCanReadTypedReceiptWithoutJwt() { + LogEventService logEventService = Mockito.mock(LogEventService.class); + String digest = digest("{\"accountId\":42}".getBytes(StandardCharsets.UTF_8)); + when(logEventService.readLogEventReceipt(any())) + .thenReturn( + new AccountAuditReceiptDto( + AccountAuditScope.PLATFORM, + null, + "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3", + "receipt-1", + 77L, + 1, + 1, + digest, + AccountAuditReceiptStatus.COMMITTED, + AccountAuditReceiptOutcome.DUPLICATE)); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "account-service", + () -> service.readLogEventReceipt(validReadRequest(), responseObserver(response, error))); + + assertEquals( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE, + response.get().getOutcome()); + assertNull(error.get()); + verify(logEventService).readLogEventReceipt(any()); + } + + @Test + void auditStorageFailureReturnsCanonicalUnavailableStatus() { + LogEventService logEventService = Mockito.mock(LogEventService.class); + when(logEventService.createLogEvent(any())) + .thenThrow(new AuditStorageUnavailableException(new IllegalStateException("database"))); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "account-service", + () -> service.createLogEvent(validCreateRequest(), responseObserver(response, error))); + + assertEquals(Status.Code.UNAVAILABLE, Status.fromThrowable(error.get()).getCode()); + assertNull(response.get()); + } + @Test void toggleFeatureFlagRejectsZeroTenantIdBeforeDispatch() { SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); @@ -259,41 +436,22 @@ public void onCompleted() {} } @Test - void createLogEventRejectsZeroAccountIdBeforeDispatch() { - SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + void createLogEventMapsUnsupportedDigestVersionRejectionToInvalidArgument() { LogEventService logEventService = Mockito.mock(LogEventService.class); - LoggingAdminGrpcService service = - new LoggingAdminGrpcService( - Mockito.mock(LogQueryService.class), - logEventService, - Mockito.mock(ModerationService.class), - new SimpleMeterRegistry()); + when(logEventService.createLogEvent(any())) + .thenThrow(new IllegalArgumentException("payloadDigestVersion must be 1")); + LoggingAdminGrpcService service = newService(logEventService); AtomicReference ref = new AtomicReference<>(); - service.createLogEvent( - CreateLogEventRequest.newBuilder() - .setTenantId("1") - .setAccountId("0") - .setType("ACCOUNT_CREATED") - .setMessage("account created") - .build(), - new StreamObserver<>() { - @Override - public void onNext(CreateLogEventResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); - verifyNoInteractions(logEventService); + AtomicReference error = new AtomicReference<>(); + CreateLogEventRequest request = + validCreateRequest().toBuilder().setPayloadDigestVersion(2).build(); + invokeWithPeer( + "account-service", () -> service.createLogEvent(request, responseObserver(ref, error))); + + assertEquals(Status.Code.INVALID_ARGUMENT, Status.fromThrowable(error.get()).getCode()); + assertNull(ref.get()); + verify(logEventService).createLogEvent(argThat(dto -> dto.payloadDigestVersion() == 2)); } @Test @@ -640,4 +798,114 @@ public void onCompleted() {} assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); verifyNoInteractions(moderationService); } + + private static LoggingAdminGrpcService newService(LogEventService logEventService) { + return new LoggingAdminGrpcService( + Mockito.mock(LogQueryService.class), + logEventService, + Mockito.mock(ModerationService.class), + new SimpleMeterRegistry(), + "firemud"); + } + + private static boolean passesWithoutBearer( + AuthTokenInterceptor interceptor, String fullMethodName) { + MethodDescriptor descriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(fullMethodName) + .setRequestMarshaller(ProtoUtils.marshaller(CreateLogEventRequest.getDefaultInstance())) + .setResponseMarshaller( + ProtoUtils.marshaller(CreateLogEventResponse.getDefaultInstance())) + .build(); + @SuppressWarnings("unchecked") + ServerCall serverCall = + (ServerCall) Mockito.mock(ServerCall.class); + when(serverCall.getMethodDescriptor()).thenReturn(descriptor); + AtomicReference callStarted = new AtomicReference<>(false); + ServerCallHandler next = + (call, headers) -> { + callStarted.set(true); + return new ServerCall.Listener<>() {}; + }; + + interceptor.interceptCall(serverCall, new Metadata(), next); + return callStarted.get(); + } + + private static StreamObserver responseObserver( + AtomicReference response, AtomicReference error) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + response.set(value); + } + + @Override + public void onError(Throwable value) { + error.set(value); + } + + @Override + public void onCompleted() {} + }; + } + + private static void invokeWithPeer(String serviceName, Runnable invocation) { + invokeWithPeer("firemud", serviceName, invocation); + } + + private static void invokeWithPeer(String namespace, String serviceName, Runnable invocation) { + String uri = "spiffe://firemud/ns/" + namespace + "/sa/" + serviceName; + Context context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, namespace, serviceName)); + Context previous = context.attach(); + try { + invocation.run(); + } finally { + context.detach(previous); + } + } + + private static CreateLogEventRequest validCreateRequest() { + ByteString payload = ByteString.copyFrom("{\"accountId\":42}".getBytes(StandardCharsets.UTF_8)); + return CreateLogEventRequest.newBuilder() + .setScope( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM) + .setAuditEventId("d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3") + .setProducerService("account-service") + .setEventType("ACCOUNT_REGISTERED") + .setOccurredAt(Timestamp.newBuilder().setSeconds(1).setNanos(234567890)) + .setSchemaVersion(1) + .setPayload(payload) + .setPayloadDigestVersion(1) + .setPayloadDigest(digest(payload.toByteArray())) + .build(); + } + + private static ReadLogEventReceiptRequest validReadRequest() { + CreateLogEventRequest create = validCreateRequest(); + return ReadLogEventReceiptRequest.newBuilder() + .setScope(create.getScope()) + .setAuditEventId(create.getAuditEventId()) + .setProducerService(create.getProducerService()) + .setEventType(create.getEventType()) + .setOccurredAt(create.getOccurredAt()) + .setSchemaVersion(create.getSchemaVersion()) + .setPayload(create.getPayload()) + .setPayloadDigestVersion(create.getPayloadDigestVersion()) + .setPayloadDigest(create.getPayloadDigest()) + .build(); + } + + private static String digest(byte[] payload) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException(ex); + } + } } From c5d4cc718f3074229b54ffc07d7890c0dab70936 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 06:14:31 +1300 Subject: [PATCH 09/75] Produce exact gameplay realm identity before Account reader --- .../command/text/GameplayWorldCatalog.java | 71 +++- .../entity/GameplayAdmissionPointer.java | 4 + .../GameplayAdmissionPointerRepository.java | 52 +++ .../GameplayAdmissionPointerSnapshot.java | 70 +++- ...eplayAdmissionPointerAuthorityService.java | 40 ++- .../service/impl/GameSessionGrpcService.java | 56 ++- ...V5__separate_gameplay_catalog_revision.sql | 4 + .../V6__persist_gameplay_realm_identity.sql | 74 ++++ .../text/GameplayWorldCatalogTest.java | 35 ++ ...ameplayAdmissionPointerRepositoryTest.java | 137 ++++++++ ...yAdmissionPointerAuthorityServiceTest.java | 1 + .../impl/GameSessionGrpcServiceTest.java | 322 ++++++++++++++++-- 12 files changed, 827 insertions(+), 39 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V5__separate_gameplay_catalog_revision.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index b24f5862c0..861fff6a18 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -7,6 +7,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.UUID; import java.util.function.Supplier; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; @@ -285,7 +286,10 @@ private static RealmView toRealmView(GameplayAdmissionPointerSnapshot pointer) { pointer.publicProductionRealm(), pointer.requiresCharacterSelection(), pointer.stateScope(), - pointer.characterCreationPolicy()); + pointer.characterCreationPolicy(), + pointer.catalogRevision(), + pointer.realmId(), + pointer.playableStateNamespaceId()); } private static WorldView copyWorldView(WorldView input) { @@ -312,7 +316,10 @@ private static RealmView copyRealmView(RealmView input) { input.publicProductionRealm(), input.requiresCharacterSelection(), input.stateScope(), - input.characterCreationPolicy()); + input.characterCreationPolicy(), + input.catalogRevision(), + input.realmId(), + input.playableStateNamespaceId()); } public record WorldView(String slug, String displayName, List realms) { @@ -331,7 +338,65 @@ public record RealmView( boolean publicProductionRealm, boolean requiresCharacterSelection, String stateScope, - String characterCreationPolicy) {} + String characterCreationPolicy, + long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId) { + /** Creates a synthetic realm view without authoritative identity evidence. */ + public RealmView( + String slug, + String displayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy, + long catalogRevision) { + this( + slug, + displayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + catalogRevision, + null, + null); + } + + /** Creates a synthetic realm view without authoritative catalog revision evidence. */ + public RealmView( + String slug, + String displayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy) { + this( + slug, + displayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + 0L); + } + } public record RuntimeRealmTarget( String worldSlug, String worldDisplayName, String realmSlug, String realmDisplayName) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java index 235349c833..27163a0068 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.entity; import java.time.Instant; +import java.util.UUID; import lombok.Data; @Data @@ -13,6 +14,9 @@ public class GameplayAdmissionPointer { private Long tenantId; private Long gameInstanceId; private Long pointerVersion; + private Long catalogRevision; + private UUID realmId; + private UUID playableStateNamespaceId; private boolean visible; private boolean publicProductionRealm; private boolean requiresCharacterSelection; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index a01611bf45..e67eefd155 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -3,10 +3,13 @@ import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; import static net.firedevops.firemud.gamesession.jooq.tables.GameplayAdmissionPointer.GAMEPLAY_ADMISSION_POINTER; +import static net.firedevops.firemud.gamesession.jooq.tables.GameplayTenantSharedPlayableStateNamespace.GAMEPLAY_TENANT_SHARED_PLAYABLE_STATE_NAMESPACE; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; import java.util.stream.Stream; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayAdmissionPointerRecord; @@ -73,11 +76,19 @@ public List findAllByOrderByWorldSlugAscRealmSlugAsc() public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { if (entity.getId() == null) { + if (!"SHARED".equals(entity.getStateScope()) && !"ISOLATED".equals(entity.getStateScope())) { + throw new IllegalArgumentException("state_scope must be SHARED or ISOLATED"); + } lockRuntimeTargetForCreation(entity); if (countByRuntimeTarget(entity.getTenantId(), entity.getGameInstanceId()) != 0) { throw new IllegalStateException( "Admission pointer creation conflicted with another route for the runtime target"); } + entity.setRealmId(UUID.randomUUID()); + entity.setPlayableStateNamespaceId( + "SHARED".equals(entity.getStateScope()) + ? getOrCreateTenantSharedNamespace(entity.getTenantId()) + : UUID.randomUUID()); GameplayAdmissionPointerRecord record = dsl.newRecord(GAMEPLAY_ADMISSION_POINTER); populate(record, entity); try { @@ -109,6 +120,12 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { "Admission pointer changed before the requested version could be committed: id=" + entity.getId()); } + if (!Objects.equals(entity.getRealmId(), current.getRealmId()) + || !Objects.equals( + entity.getPlayableStateNamespaceId(), current.getPlayableStateNamespaceId())) { + throw new IllegalStateException( + "Admission pointer update cannot replace durable realm or playable-state identity"); + } long destinationCount = countByRuntimeTargetExcludingId( entity.getTenantId(), entity.getGameInstanceId(), entity.getId()); @@ -127,6 +144,7 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { .set(GAMEPLAY_ADMISSION_POINTER.TENANT_ID, entity.getTenantId()) .set(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID, entity.getGameInstanceId()) .set(GAMEPLAY_ADMISSION_POINTER.POINTER_VERSION, entity.getPointerVersion()) + .set(GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION, entity.getCatalogRevision()) .set(GAMEPLAY_ADMISSION_POINTER.VISIBLE, entity.isVisible()) .set( GAMEPLAY_ADMISSION_POINTER.PUBLIC_PRODUCTION_REALM, @@ -228,6 +246,33 @@ private void lockRuntimeTargetForCreation(GameplayAdmissionPointer entity) { lockRuntimeTarget(runtimeTargetLockKey(entity.getTenantId(), entity.getGameInstanceId())); } + private UUID getOrCreateTenantSharedNamespace(Long tenantId) { + lockRuntimeTarget("tenant-shared-playable-state:" + tenantId); + var table = GAMEPLAY_TENANT_SHARED_PLAYABLE_STATE_NAMESPACE; + UUID namespace = + dsl.select(table.PLAYABLE_STATE_NAMESPACE_ID) + .from(table) + .where(table.TENANT_ID.eq(tenantId)) + .fetchOne(table.PLAYABLE_STATE_NAMESPACE_ID); + if (namespace != null) { + return namespace; + } + dsl.insertInto(table) + .set(table.TENANT_ID, tenantId) + .set(table.PLAYABLE_STATE_NAMESPACE_ID, UUID.randomUUID()) + .onDuplicateKeyIgnore() + .execute(); + UUID allocated = + dsl.select(table.PLAYABLE_STATE_NAMESPACE_ID) + .from(table) + .where(table.TENANT_ID.eq(tenantId)) + .fetchOne(table.PLAYABLE_STATE_NAMESPACE_ID); + if (allocated == null) { + throw new IllegalStateException("Tenant shared playable-state namespace allocation failed"); + } + return allocated; + } + private void populate(GameplayAdmissionPointerRecord record, GameplayAdmissionPointer entity) { record.setWorldSlug(entity.getWorldSlug()); record.setWorldDisplayName(entity.getWorldDisplayName()); @@ -236,6 +281,9 @@ private void populate(GameplayAdmissionPointerRecord record, GameplayAdmissionPo record.setTenantId(entity.getTenantId()); record.setGameInstanceId(entity.getGameInstanceId()); record.setPointerVersion(entity.getPointerVersion()); + record.setCatalogRevision(entity.getCatalogRevision()); + record.setRealmId(entity.getRealmId()); + record.setPlayableStateNamespaceId(entity.getPlayableStateNamespaceId()); record.setVisible(entity.isVisible()); record.setPublicProductionRealm(entity.isPublicProductionRealm()); record.setRequiresCharacterSelection(entity.isRequiresCharacterSelection()); @@ -257,6 +305,10 @@ private GameplayAdmissionPointer toEntity(Record record) { entity.setTenantId(record.get(GAMEPLAY_ADMISSION_POINTER.TENANT_ID)); entity.setGameInstanceId(record.get(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID)); entity.setPointerVersion(record.get(GAMEPLAY_ADMISSION_POINTER.POINTER_VERSION)); + entity.setCatalogRevision(record.get(GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION)); + entity.setRealmId(record.get(GAMEPLAY_ADMISSION_POINTER.REALM_ID)); + entity.setPlayableStateNamespaceId( + record.get(GAMEPLAY_ADMISSION_POINTER.PLAYABLE_STATE_NAMESPACE_ID)); entity.setVisible(Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER.VISIBLE))); entity.setPublicProductionRealm( Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER.PUBLIC_PRODUCTION_REALM))); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java index 91fa8e464f..5b0a879615 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.gamesession.service; +import java.util.UUID; + public record GameplayAdmissionPointerSnapshot( String worldSlug, String worldDisplayName, @@ -12,4 +14,70 @@ public record GameplayAdmissionPointerSnapshot( boolean publicProductionRealm, boolean requiresCharacterSelection, String stateScope, - String characterCreationPolicy) {} + String characterCreationPolicy, + long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId) { + /** Creates a synthetic snapshot without catalog identity/revision authority. */ + public GameplayAdmissionPointerSnapshot( + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy, + long catalogRevision) { + this( + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + catalogRevision, + null, + null); + } + + /** Creates a synthetic snapshot without catalog authority for legacy test fixtures. */ + public GameplayAdmissionPointerSnapshot( + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy) { + this( + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + 0L); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index baa71c65e1..c1c216b5cd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -78,9 +78,15 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu && pointer.getTenantId() != mutation.tenantId()) { throw new IllegalArgumentException("tenant_id does not own admission pointer"); } + if (pointer.getId() != null + && !Objects.equals(pointer.getStateScope(), mutation.stateScope())) { + throw new IllegalArgumentException( + "state_scope changes require a new playable-state lifecycle"); + } enforceExpectedPointerVersion(pointer, mutation.expectedPointerVersion()); long nextPointerVersion = pointer.getId() == null ? 1L : Math.max(pointer.getPointerVersion() + 1L, 1L); + long nextCatalogRevision = nextCatalogRevision(pointer, mutation); pointer.setWorldSlug(mutation.worldSlug()); pointer.setWorldDisplayName(mutation.worldDisplayName()); pointer.setRealmSlug(mutation.realmSlug()); @@ -88,6 +94,7 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu pointer.setTenantId(mutation.tenantId()); pointer.setGameInstanceId(mutation.gameInstanceId()); pointer.setPointerVersion(nextPointerVersion); + pointer.setCatalogRevision(nextCatalogRevision); pointer.setVisible(mutation.visible()); pointer.setPublicProductionRealm(mutation.publicProductionRealm()); pointer.setRequiresCharacterSelection(mutation.requiresCharacterSelection()); @@ -167,7 +174,38 @@ private GameplayAdmissionPointerSnapshot toSnapshot(GameplayAdmissionPointer poi pointer.isPublicProductionRealm(), pointer.isRequiresCharacterSelection(), pointer.getStateScope(), - pointer.getCharacterCreationPolicy()); + pointer.getCharacterCreationPolicy(), + pointer.getCatalogRevision() == null ? 0L : pointer.getCatalogRevision(), + pointer.getRealmId(), + pointer.getPlayableStateNamespaceId()); + } + + private long nextCatalogRevision( + GameplayAdmissionPointer pointer, GameplayAdmissionPointerMutation mutation) { + if (pointer.getId() == null) { + return 1L; + } + Long currentRevision = pointer.getCatalogRevision(); + if (currentRevision == null || currentRevision <= 0L) { + throw new IllegalStateException("Admission pointer catalog revision is missing or invalid"); + } + if (!catalogPolicyMatches(pointer, mutation)) { + return Math.addExact(currentRevision, 1L); + } + return currentRevision; + } + + private boolean catalogPolicyMatches( + GameplayAdmissionPointer pointer, GameplayAdmissionPointerMutation mutation) { + return Objects.equals(pointer.getWorldSlug(), mutation.worldSlug()) + && Objects.equals(pointer.getWorldDisplayName(), mutation.worldDisplayName()) + && Objects.equals(pointer.getRealmSlug(), mutation.realmSlug()) + && Objects.equals(pointer.getRealmDisplayName(), mutation.realmDisplayName()) + && pointer.isVisible() == mutation.visible() + && pointer.isPublicProductionRealm() == mutation.publicProductionRealm() + && pointer.isRequiresCharacterSelection() == mutation.requiresCharacterSelection() + && Objects.equals(pointer.getStateScope(), mutation.stateScope()) + && Objects.equals(pointer.getCharacterCreationPolicy(), mutation.characterCreationPolicy()); } private void validateMutation(GameplayAdmissionPointerMutation mutation) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index f39849a79b..896ca96837 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -545,12 +545,20 @@ public void listGameplayRealms( gameplayWorldCatalog .resolveWorld(request.getWorldSlug()) .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay world selection")); + List realms = + gameplayWorldCatalog.visibleRealms(world).stream() + .map(realm -> toGameplayRealm(world.slug(), realm)) + .toList(); + ListGameplayRealmsResponse response = + ListGameplayRealmsResponse.newBuilder().addAllRealms(realms).build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (CatalogRevisionUnavailableException ex) { ListGameplayRealmsResponse response = ListGameplayRealmsResponse.newBuilder() - .addAllRealms( - gameplayWorldCatalog.visibleRealms(world).stream() - .map(realm -> toGameplayRealm(world.slug(), realm)) - .toList()) + .setError( + GrpcAppErrors.error( + meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); @@ -592,10 +600,24 @@ public void getAdmissionPointer( .setPublicProductionRealm(realm.publicProductionRealm()) .setStateScope(realm.stateScope()) .setCharacterCreationPolicy(realm.characterCreationPolicy()) + .setCatalogRevision(requireCatalogRevision(realm.catalogRevision())) + .setRealmId(requireIdentity(realm.realmId(), "realmId")) + .setPlayableStateNamespaceId( + requireIdentity( + realm.playableStateNamespaceId(), "playableStateNamespaceId")) .build()) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (CatalogRevisionUnavailableException ex) { + GetAdmissionPointerResponse response = + GetAdmissionPointerResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (IllegalArgumentException ex) { GetAdmissionPointerResponse response = GetAdmissionPointerResponse.newBuilder() @@ -778,9 +800,35 @@ private net.firedevops.firemud.gamesession.v1.GameplayRealm toGameplayRealm( .setPublicProductionRealm(realm.publicProductionRealm()) .setStateScope(realm.stateScope()) .setCharacterCreationPolicy(realm.characterCreationPolicy()) + .setCatalogRevision(requireCatalogRevision(realm.catalogRevision())) + .setRealmId(requireIdentity(realm.realmId(), "realmId")) + .setPlayableStateNamespaceId( + requireIdentity(realm.playableStateNamespaceId(), "playableStateNamespaceId")) .build(); } + private static String requireIdentity(java.util.UUID identity, String fieldName) { + if (identity == null) { + throw new CatalogRevisionUnavailableException( + "Authoritative gameplay " + fieldName + " is missing"); + } + return identity.toString(); + } + + private static long requireCatalogRevision(long catalogRevision) { + if (catalogRevision <= 0L) { + throw new CatalogRevisionUnavailableException( + "Authoritative gameplay catalog revision is missing or invalid"); + } + return catalogRevision; + } + + private static final class CatalogRevisionUnavailableException extends RuntimeException { + private CatalogRevisionUnavailableException(String message) { + super(message); + } + } + private static final class AuthorizationException extends RuntimeException { private AuthorizationException(String message) { super(message); diff --git a/services/game-session-service/src/main/resources/db/migration/V5__separate_gameplay_catalog_revision.sql b/services/game-session-service/src/main/resources/db/migration/V5__separate_gameplay_catalog_revision.sql new file mode 100644 index 0000000000..63e5cd1ce1 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V5__separate_gameplay_catalog_revision.sql @@ -0,0 +1,4 @@ +ALTER TABLE gameplay_admission_pointer + ADD COLUMN catalog_revision bigint NOT NULL DEFAULT 1, + ADD CONSTRAINT gameplay_admission_pointer_catalog_revision_positive + CHECK (catalog_revision > 0); diff --git a/services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql b/services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql new file mode 100644 index 0000000000..41effca0d0 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql @@ -0,0 +1,74 @@ +-- A tenant's shared playable-state namespace is allocated once and reused by every +-- SHARED realm. Isolated realms receive independent namespace UUIDs. +CREATE TABLE gameplay_tenant_shared_playable_state_namespace ( + tenant_id bigint PRIMARY KEY, + playable_state_namespace_id uuid NOT NULL UNIQUE, + allocated_at timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +INSERT INTO gameplay_tenant_shared_playable_state_namespace ( + tenant_id, + playable_state_namespace_id +) +SELECT shared_tenants.tenant_id, gen_random_uuid() +FROM ( + SELECT DISTINCT pointer.tenant_id + FROM gameplay_admission_pointer pointer + WHERE pointer.state_scope = 'SHARED' +) shared_tenants; + +ALTER TABLE gameplay_admission_pointer + ADD COLUMN realm_id uuid, + ADD COLUMN playable_state_namespace_id uuid; + +-- Retained rows with an exact known state scope can be classified without using +-- the replaceable game_instance_id as identity. Unknown legacy values remain +-- explicitly unresolved below. +UPDATE gameplay_admission_pointer +SET realm_id = gen_random_uuid(), + playable_state_namespace_id = ( + SELECT shared_namespace.playable_state_namespace_id + FROM gameplay_tenant_shared_playable_state_namespace shared_namespace + WHERE shared_namespace.tenant_id = gameplay_admission_pointer.tenant_id + ) +WHERE state_scope = 'SHARED'; + +UPDATE gameplay_admission_pointer +SET realm_id = gen_random_uuid(), + playable_state_namespace_id = gen_random_uuid() +WHERE state_scope = 'ISOLATED'; + +CREATE TABLE gameplay_admission_pointer_identity_backfill_issue ( + pointer_id bigint PRIMARY KEY, + tenant_id bigint NOT NULL, + world_slug character varying(120) NOT NULL, + realm_slug character varying(120) NOT NULL, + prior_state_scope character varying(32), + issue_code character varying(64) NOT NULL, + recorded_at timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +INSERT INTO gameplay_admission_pointer_identity_backfill_issue ( + pointer_id, + tenant_id, + world_slug, + realm_slug, + prior_state_scope, + issue_code +) +SELECT id, + tenant_id, + world_slug, + realm_slug, + state_scope, + 'UNKNOWN_PLAYABLE_STATE_SCOPE' +FROM gameplay_admission_pointer +WHERE state_scope IS NULL OR state_scope NOT IN ('SHARED', 'ISOLATED'); + +ALTER TABLE gameplay_admission_pointer + ADD CONSTRAINT gameplay_admission_pointer_identity_pair_complete + CHECK ((realm_id IS NULL) = (playable_state_namespace_id IS NULL)); + +CREATE UNIQUE INDEX uq_gameplay_admission_pointer_realm_id + ON gameplay_admission_pointer (realm_id) + WHERE realm_id IS NOT NULL; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index f14c14301c..60dbe07f7a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -167,6 +167,41 @@ void normalizeWorldsDropsRealmViewsWithoutSlugsBeforeAdmissionLookup() { assertThat(catalog.resolveRealmForAdmission(normalizedWorld, "invalid")).isEmpty(); } + @Test + void authoritativePointerIdentityAndCatalogRevisionReachRealmView() { + java.util.UUID realmId = + java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"); + java.util.UUID playableStateNamespaceId = + java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412"); + when(authorityService.listPointers()) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 11L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 29L, + realmId, + playableStateNamespaceId))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + GameplayWorldCatalog.RealmView realm = + catalog.resolveRealm(catalog.resolveWorld("demo").orElseThrow(), "production").orElseThrow(); + + assertThat(realm.catalogRevision()).isEqualTo(29L); + assertThat(realm.realmId()).isEqualTo(realmId); + assertThat(realm.playableStateNamespaceId()).isEqualTo(playableStateNamespaceId); + } + private static GameplayWorldCatalog.WorldView worldWithTargetRealm( String realmSlug, boolean visible) { return new GameplayWorldCatalog.WorldView( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java new file mode 100644 index 0000000000..cce6340463 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -0,0 +1,137 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class GameplayAdmissionPointerRepositoryTest { + @Test + void stableRealmAndNamespaceIdentitySurviveRuntimeReplacement() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-identity;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + + GameplayAdmissionPointer shared = pointer(7L, 44L, "SHARED", "production"); + GameplayAdmissionPointer createdShared = repository.save(shared); + UUID sharedRealmId = createdShared.getRealmId(); + UUID sharedNamespaceId = createdShared.getPlayableStateNamespaceId(); + GameplayAdmissionPointer sharedReadback = + repository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production").orElseThrow(); + + GameplayAdmissionPointer secondShared = + repository.save(pointer(7L, 45L, "SHARED", "seasonal")); + GameplayAdmissionPointer isolated = repository.save(pointer(7L, 46L, "ISOLATED", "playtest")); + + assertNotNull(sharedRealmId); + assertNotNull(sharedNamespaceId); + assertEquals(sharedRealmId, sharedReadback.getRealmId()); + assertEquals(sharedNamespaceId, sharedReadback.getPlayableStateNamespaceId()); + assertNotNull(secondShared.getRealmId()); + assertNotNull(isolated.getRealmId()); + assertEquals(sharedNamespaceId, secondShared.getPlayableStateNamespaceId()); + assertNotEquals(sharedRealmId, secondShared.getRealmId()); + assertNotEquals(sharedNamespaceId, isolated.getPlayableStateNamespaceId()); + + createdShared.setGameInstanceId(99L); + createdShared.setPointerVersion(2L); + createdShared.setCatalogRevision(1L); + GameplayAdmissionPointer replaced = repository.save(createdShared); + + assertEquals(99L, replaced.getGameInstanceId()); + assertEquals(sharedRealmId, replaced.getRealmId()); + assertEquals(sharedNamespaceId, replaced.getPlayableStateNamespaceId()); + } + } + + @Test + void repositoryRejectsAttemptToReplaceStableRealmIdentity() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-identity-immutable;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + GameplayAdmissionPointer created = repository.save(pointer(7L, 44L, "ISOLATED", "fork")); + + created.setPointerVersion(2L); + created.setRealmId(UUID.randomUUID()); + + org.junit.jupiter.api.Assertions.assertThrows( + IllegalStateException.class, () -> repository.save(created)); + } + } + + private static GameplayAdmissionPointer pointer( + long tenantId, long gameInstanceId, String stateScope, String realmSlug) { + GameplayAdmissionPointer pointer = new GameplayAdmissionPointer(); + pointer.setWorldSlug("demo"); + pointer.setWorldDisplayName("Demo World"); + pointer.setRealmSlug(realmSlug); + pointer.setRealmDisplayName(realmSlug); + pointer.setTenantId(tenantId); + pointer.setGameInstanceId(gameInstanceId); + pointer.setPointerVersion(1L); + pointer.setCatalogRevision(1L); + pointer.setVisible(true); + pointer.setPublicProductionRealm("production".equals(realmSlug)); + pointer.setRequiresCharacterSelection(false); + pointer.setStateScope(stateScope); + pointer.setCharacterCreationPolicy("ALLOW_NEW"); + pointer.setLastUpdatedBy("test"); + pointer.setLastUpdateReason("test"); + pointer.setCreatedAt(Instant.parse("2026-09-24T00:00:00Z")); + pointer.setUpdatedAt(Instant.parse("2026-09-24T00:00:00Z")); + return pointer; + } + + private static void createSchema(DSLContext dsl) { + dsl.execute( + """ + CREATE TABLE gameplay_tenant_shared_playable_state_namespace ( + tenant_id BIGINT PRIMARY KEY, + playable_state_namespace_id UUID NOT NULL UNIQUE, + allocated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + ) + """); + dsl.execute( + """ + CREATE TABLE gameplay_admission_pointer ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(200) NOT NULL, + realm_slug VARCHAR(120) NOT NULL, + realm_display_name VARCHAR(200) NOT NULL, + tenant_id BIGINT NOT NULL, + game_instance_id BIGINT NOT NULL, + pointer_version BIGINT NOT NULL, + catalog_revision BIGINT NOT NULL, + realm_id UUID, + playable_state_namespace_id UUID, + visible BOOLEAN NOT NULL, + public_production_realm BOOLEAN NOT NULL, + requires_character_selection BOOLEAN NOT NULL, + state_scope VARCHAR(32) NOT NULL, + character_creation_policy VARCHAR(32) NOT NULL, + last_updated_by VARCHAR(200) NOT NULL, + last_update_reason VARCHAR(500) NOT NULL, + created_at TIMESTAMP NOT NULL, + updated_at TIMESTAMP NOT NULL, + CONSTRAINT uq_pointer_tenant_world_realm UNIQUE (tenant_id, world_slug, realm_slug), + CONSTRAINT uq_pointer_tenant_runtime UNIQUE (tenant_id, game_instance_id) + ) + """); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index ae5d5933b0..f84933a724 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -38,6 +38,7 @@ void upsertPointerRejectsMismatchedExpectedVersion() { GameplayAdmissionPointer existing = new GameplayAdmissionPointer(); existing.setId(11L); existing.setPointerVersion(3L); + existing.setStateScope("SHARED"); when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) .thenReturn(Optional.of(existing)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 27318cf7ba..8d1e514af6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -18,13 +18,18 @@ import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.AccountPresenceSnapshot; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.FeatureFlagService; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; import net.firedevops.firemud.gamesession.service.PingService; @@ -440,36 +445,26 @@ void gameplayCatalogRpcReturnsCanonicalRealmData() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); - world.setSlug("demo"); - world.setDisplayName("Demo World"); - GameplayCatalogProperties.Realm realm = new GameplayCatalogProperties.Realm(); - realm.setSlug("production"); - realm.setDisplayName("Live Realm"); - realm.setTenantId(7L); - realm.setGameInstanceId(999L); - realm.setPointerVersion(999L); - realm.setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); - realm.setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); - world.setRealms(List.of(realm)); - properties.setWorlds(List.of(world)); + GameplayAdmissionPointerSnapshot authoritativeSnapshot = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "ISOLATED", + "COPIED_ONLY", + 29L, + java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"), + java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412")); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(authoritativeSnapshot)); Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) - .thenReturn( - java.util.Optional.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo World", - "production", - "Live Realm", - 7L, - 44L, - 17L, - true, - false, - false, - "ISOLATED", - "COPIED_ONLY"))); + .thenReturn(java.util.Optional.of(authoritativeSnapshot)); GameSessionGrpcService service = newService( pingService, @@ -478,7 +473,7 @@ void gameplayCatalogRpcReturnsCanonicalRealmData() { textCommandInterpreter, gameInstanceRepository, pointerAuthorityService, - TestGameplayWorldCatalogs.fromProperties(properties), + new GameplayWorldCatalog(pointerAuthorityService), tickService, meterRegistry, ipLimiter); @@ -504,6 +499,12 @@ public void onCompleted() {} assertEquals(1, realmsRef.get().getRealmsCount()); assertEquals("production", realmsRef.get().getRealms(0).getRealmSlug()); assertEquals("ISOLATED", realmsRef.get().getRealms(0).getStateScope()); + assertEquals(17L, realmsRef.get().getRealms(0).getPointerVersion()); + assertEquals(29L, realmsRef.get().getRealms(0).getCatalogRevision()); + assertEquals("8a1df0f1-1b57-465e-9c4b-bb34f8153d31", realmsRef.get().getRealms(0).getRealmId()); + assertEquals( + "2ea958e0-13a2-41d0-9c39-59a96cf31412", + realmsRef.get().getRealms(0).getPlayableStateNamespaceId()); AtomicReference pointerRef = new AtomicReference<>(); service.getAdmissionPointer( @@ -529,9 +530,270 @@ public void onCompleted() {} assertEquals("44", pointerRef.get().getAdmissionPointer().getGameInstanceId()); assertEquals(17L, pointerRef.get().getAdmissionPointer().getPointerVersion()); + assertEquals(29L, pointerRef.get().getAdmissionPointer().getCatalogRevision()); + assertEquals( + "8a1df0f1-1b57-465e-9c4b-bb34f8153d31", + pointerRef.get().getAdmissionPointer().getRealmId()); + assertEquals( + "2ea958e0-13a2-41d0-9c39-59a96cf31412", + pointerRef.get().getAdmissionPointer().getPlayableStateNamespaceId()); Mockito.verify(pointerAuthorityService).findPointer(7L, "demo", "production"); } + @Test + void missingCatalogRevisionFailsClosedForCatalogAndAdmissionPointerReads() { + PingService pingService = Mockito.mock(PingService.class); + GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); + FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); + TextCommandInterpreter textCommandInterpreter = Mockito.mock(TextCommandInterpreter.class); + GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); + TickService tickService = Mockito.mock(TickService.class); + IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + GameplayAdmissionPointerSnapshot missingRevision = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 0L); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingRevision)); + Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) + .thenReturn(java.util.Optional.of(missingRevision)); + GameSessionGrpcService service = + newService( + pingService, + gameInstanceService, + featureFlagService, + textCommandInterpreter, + gameInstanceRepository, + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + tickService, + meterRegistry, + ipLimiter); + + AtomicReference realmsRef = new AtomicReference<>(); + service.listGameplayRealms( + ListGameplayRealmsRequest.newBuilder().setWorldSlug("demo").build(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayRealmsResponse value) { + realmsRef.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", realmsRef.get().getError().getCode()); + assertEquals(0, realmsRef.get().getRealmsCount()); + + AtomicReference pointerRef = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + pointerRef.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", pointerRef.get().getError().getCode()); + assertFalse(pointerRef.get().hasAdmissionPointer()); + } + + private static ListGameplayRealmsResponse listGameplayRealms( + GameSessionGrpcService service, String worldSlug) { + AtomicReference response = new AtomicReference<>(); + service.listGameplayRealms( + ListGameplayRealmsRequest.newBuilder().setWorldSlug(worldSlug).build(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayRealmsResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + return response.get(); + } + + @Test + void missingStableRealmIdentityFailsClosedForCatalogReads() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot missingIdentity = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 29L); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingIdentity)); + Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) + .thenReturn(java.util.Optional.of(missingIdentity)); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + AtomicReference response = new AtomicReference<>(); + service.listGameplayRealms( + ListGameplayRealmsRequest.newBuilder().setWorldSlug("demo").build(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayRealmsResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); + assertEquals(0, response.get().getRealmsCount()); + + AtomicReference pointerResponse = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + pointerResponse.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", pointerResponse.get().getError().getCode()); + assertFalse(pointerResponse.get().hasAdmissionPointer()); + } + + @Test + void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { + GameplayAdmissionPointerRepository pointerRepository = + Mockito.mock(GameplayAdmissionPointerRepository.class); + GameplayAdmissionPointerEventRepository eventRepository = + Mockito.mock(GameplayAdmissionPointerEventRepository.class); + AtomicReference currentPointer = new AtomicReference<>(); + Mockito.when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production")) + .thenAnswer(invocation -> java.util.Optional.ofNullable(currentPointer.get())); + Mockito.when(pointerRepository.save(Mockito.any(GameplayAdmissionPointer.class))) + .thenAnswer( + invocation -> { + GameplayAdmissionPointer pointer = invocation.getArgument(0); + if (pointer.getId() == null) { + pointer.setId(11L); + } + currentPointer.set(pointer); + return pointer; + }); + Mockito.when(eventRepository.save(Mockito.any(GameplayAdmissionPointerEvent.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + DatabaseGameplayAdmissionPointerAuthorityService authorityService = + new DatabaseGameplayAdmissionPointerAuthorityService(pointerRepository, eventRepository); + + GameplayAdmissionPointerSnapshot created = + authorityService.upsertPointer(pointerMutation(44L, true, 0L)); + GameplayAdmissionPointerSnapshot policyChanged = + authorityService.upsertPointer(pointerMutation(44L, false, 1L)); + GameplayAdmissionPointerSnapshot routeChanged = + authorityService.upsertPointer(pointerMutation(45L, false, 2L)); + + assertEquals(1L, created.catalogRevision()); + assertEquals(1L, created.pointerVersion()); + assertEquals(2L, policyChanged.catalogRevision()); + assertEquals(2L, policyChanged.pointerVersion()); + assertEquals(2L, routeChanged.catalogRevision()); + assertEquals(3L, routeChanged.pointerVersion()); + } + + private static GameplayAdmissionPointerMutation pointerMutation( + long gameInstanceId, boolean publicProductionRealm, Long expectedPointerVersion) { + return new GameplayAdmissionPointerMutation( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + gameInstanceId, + true, + publicProductionRealm, + false, + "SHARED", + "ALLOW_NEW", + "test", + "catalog revision test", + "catalog-revision-test-" + expectedPointerVersion, + expectedPointerVersion, + null); + } + @Test void getAdmissionPointerRuntimeFailureReturnsInternalErrorDetail() { PingService pingService = Mockito.mock(PingService.class); From 3f557fd26de6121906da4686bb92a3e365529341 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 06:55:54 +1300 Subject: [PATCH 10/75] Apply Account formatting in split writer stage --- .../accountservice/service/impl/AccountServiceImpl.java | 4 +--- .../accountservice/service/impl/AccountServiceImplTest.java | 4 +++- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index c6edd91b3e..457eb2e5e7 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -1357,9 +1357,7 @@ private List listAdmissibleRuntimeRealmTargets( .flatMap(Optional::stream) .toList(); validatePublicRealmCardinality(targets); - return targets.stream() - .filter(realm -> isRealmAdmissible(bootstrapContext, realm)) - .toList(); + return targets.stream().filter(realm -> isRealmAdmissible(bootstrapContext, realm)).toList(); } catch (AuthenticationException ex) { throw ex; } catch (RuntimeException ex) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index b50ed9d3c2..a45c4f9231 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -398,7 +398,9 @@ void joinPublicProductionRejectsStillActiveBootstrapForIneligibleLifecycleState( assertEquals(expectedCode, exception.getCode()); verifyNoInteractions( - accountJoinOperationRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + accountJoinOperationRepository, + accountTenantMembershipRepository, + accountAuditOutboxRepository); } @Test From b6ad79d0a0891ee984b9be65ba5cf91701e294ad Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 07:04:40 +1300 Subject: [PATCH 11/75] Keep catalog revisions separate from runtime pointer versions --- .../service/impl/AccountGrpcService.java | 2 +- .../service/impl/AccountServiceImpl.java | 1 + .../service/impl/AccountGrpcServiceTest.java | 23 +++++ .../service/impl/AccountServiceImplTest.java | 24 +++++ .../GameplayAdmissionPointerRepository.java | 51 +++++++++-- ...eplayAdmissionPointerAuthorityService.java | 16 +++- ...ameplayAdmissionPointerRepositoryTest.java | 37 ++++++++ ...yAdmissionPointerAuthorityServiceTest.java | 87 +++++++++++++++++++ .../impl/GameSessionGrpcServiceTest.java | 6 +- 9 files changed, 235 insertions(+), 12 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index a7a2e57849..116d3c74c4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -205,7 +205,7 @@ private DirectTextCallerContext directTextCaller( requireText(context.getPlayableStateScope(), "playableStateScope"), requirePositiveRequestId(context.getGameInstanceId(), "gameInstanceId"), requireText(context.getSessionId(), "sessionId"), - context.getRequestId()); + requireText(context.getRequestId(), "requestId")); } private UUID requireCanonicalRealmId(String value) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 457eb2e5e7..1228b3e583 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -469,6 +469,7 @@ public DirectTextJoinScope issueDirectTextConnectScope( if (caller == null || target == null || caller.accountId() <= 0L + || !StringUtils.hasText(caller.requestId()) || caller.tenantId() != target.tenantId() || !caller.realmId().equals(target.realmId()) || caller.gameInstanceId() != target.gameInstanceId() diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 92d64949bd..001edbf111 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -312,6 +312,29 @@ void directTextMethodsRejectMalformedOrMismatchedTypedContextBeforeServiceCall() Mockito.verifyNoInteractions(accountService); } + @ParameterizedTest + @ValueSource(strings = {"", " "}) + void issueDirectTextConnectScopeRejectsBlankRequestIdBeforeServiceCall(String requestId) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.issueDirectTextConnectScope( + validScopeRequest() + .toBuilder() + .setPlayerContext(validPlayerContext().toBuilder().setRequestId(requestId)) + .build(), + observer)); + + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + @ParameterizedTest @ValueSource(strings = {"30", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) void directTextScopeRejectsNoncanonicalRealmIdsAtBothIngressFields(String realmId) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index a45c4f9231..5a92fe42b9 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -2304,6 +2304,30 @@ void issueDirectTextConnectScopeRejectsUnavailableEntitlementWithoutRetainingSco .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); } + @ParameterizedTest + @ValueSource(strings = {"", " "}) + void issueDirectTextConnectScopeRejectsBlankRequestIdBeforeAuthorityOrScopeWork( + String requestId) { + DirectTextCallerContext caller = + new DirectTextCallerContext( + 11L, + 7L, + UUID.fromString(REALM_ID), + "production-namespace-7", + "SHARED", + 44L, + "session-1", + requestId); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.issueDirectTextConnectScope(caller, directTextTarget())); + + assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); + verifyNoInteractions(accountRepository, subscriptionRepository, accountConnectScopeRepository); + } + @Test void issueDirectTextConnectScopeRejectsBillingBlockedEntitlementWithoutRetainingScope() { Account account = directTextAccount(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index e67eefd155..60748667ed 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -99,8 +99,8 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { } return findById(record.getId()).orElseThrow(); } - if (entity.getPointerVersion() == null || entity.getPointerVersion() <= 1L) { - throw new IllegalArgumentException("Existing admission pointer must advance its version"); + if (entity.getPointerVersion() == null || entity.getPointerVersion() <= 0L) { + throw new IllegalArgumentException("Existing admission pointer must have a positive version"); } GameplayAdmissionPointer current = findByIdForUpdate(entity.getId()) @@ -115,10 +115,12 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { () -> new AdmissionPointerVersionMismatchException( "Admission pointer no longer exists: id=" + entity.getId())); - if (!Long.valueOf(entity.getPointerVersion() - 1L).equals(current.getPointerVersion())) { - throw new AdmissionPointerVersionMismatchException( - "Admission pointer changed before the requested version could be committed: id=" - + entity.getId()); + if (current.getPointerVersion() == null + || current.getCatalogRevision() == null + || entity.getCatalogRevision() == null + || entity.getCatalogRevision() <= 0L) { + throw new IllegalStateException( + "Admission pointer version and catalog revision must be present and positive"); } if (!Objects.equals(entity.getRealmId(), current.getRealmId()) || !Objects.equals( @@ -126,6 +128,24 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { throw new IllegalStateException( "Admission pointer update cannot replace durable realm or playable-state identity"); } + boolean runtimeTargetChanged = + !Objects.equals(entity.getGameInstanceId(), current.getGameInstanceId()); + boolean catalogChanged = !catalogPolicyMatches(current, entity); + long expectedPointerVersion = + runtimeTargetChanged + ? Math.addExact(current.getPointerVersion(), 1L) + : current.getPointerVersion(); + long expectedCatalogRevision = + catalogChanged + ? Math.addExact(current.getCatalogRevision(), 1L) + : current.getCatalogRevision(); + if (entity.getPointerVersion() != expectedPointerVersion + || entity.getCatalogRevision() != expectedCatalogRevision) { + throw new AdmissionPointerVersionMismatchException( + "Admission pointer version or catalog revision changed before the requested update could" + + " be committed: id=" + + entity.getId()); + } long destinationCount = countByRuntimeTargetExcludingId( entity.getTenantId(), entity.getGameInstanceId(), entity.getId()); @@ -166,7 +186,10 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { .eq(entity.getId()) .and( GAMEPLAY_ADMISSION_POINTER.POINTER_VERSION.eq( - entity.getPointerVersion() - 1L))) + current.getPointerVersion())) + .and( + GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION.eq( + current.getCatalogRevision()))) .execute(); } catch (IntegrityConstraintViolationException ex) { throw new IllegalStateException( @@ -295,6 +318,20 @@ private void populate(GameplayAdmissionPointerRecord record, GameplayAdmissionPo record.setUpdatedAt(toLocalDateTime(entity.getUpdatedAt())); } + private boolean catalogPolicyMatches( + GameplayAdmissionPointer current, GameplayAdmissionPointer requested) { + return Objects.equals(current.getWorldSlug(), requested.getWorldSlug()) + && Objects.equals(current.getWorldDisplayName(), requested.getWorldDisplayName()) + && Objects.equals(current.getRealmSlug(), requested.getRealmSlug()) + && Objects.equals(current.getRealmDisplayName(), requested.getRealmDisplayName()) + && current.isVisible() == requested.isVisible() + && current.isPublicProductionRealm() == requested.isPublicProductionRealm() + && current.isRequiresCharacterSelection() == requested.isRequiresCharacterSelection() + && Objects.equals(current.getStateScope(), requested.getStateScope()) + && Objects.equals( + current.getCharacterCreationPolicy(), requested.getCharacterCreationPolicy()); + } + private GameplayAdmissionPointer toEntity(Record record) { GameplayAdmissionPointer entity = new GameplayAdmissionPointer(); entity.setId(record.get(GAMEPLAY_ADMISSION_POINTER.ID)); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index c1c216b5cd..f2e4ec779e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -84,8 +84,17 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu "state_scope changes require a new playable-state lifecycle"); } enforceExpectedPointerVersion(pointer, mutation.expectedPointerVersion()); + if (pointer.getId() != null + && runtimeTargetMatches(pointer, mutation) + && catalogPolicyMatches(pointer, mutation)) { + return toSnapshot(pointer); + } + boolean runtimeTargetChanged = + pointer.getId() == null || !runtimeTargetMatches(pointer, mutation); long nextPointerVersion = - pointer.getId() == null ? 1L : Math.max(pointer.getPointerVersion() + 1L, 1L); + pointer.getId() == null || runtimeTargetChanged + ? pointer.getId() == null ? 1L : Math.addExact(pointer.getPointerVersion(), 1L) + : pointer.getPointerVersion(); long nextCatalogRevision = nextCatalogRevision(pointer, mutation); pointer.setWorldSlug(mutation.worldSlug()); pointer.setWorldDisplayName(mutation.worldDisplayName()); @@ -208,6 +217,11 @@ private boolean catalogPolicyMatches( && Objects.equals(pointer.getCharacterCreationPolicy(), mutation.characterCreationPolicy()); } + private boolean runtimeTargetMatches( + GameplayAdmissionPointer pointer, GameplayAdmissionPointerMutation mutation) { + return Objects.equals(pointer.getGameInstanceId(), mutation.gameInstanceId()); + } + private void validateMutation(GameplayAdmissionPointerMutation mutation) { requireText(mutation.worldSlug(), "world_slug is required"); requireText(mutation.worldDisplayName(), "world_display_name is required"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index cce6340463..113067382e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -3,12 +3,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.sql.Connection; import java.sql.DriverManager; import java.time.Instant; import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -74,6 +76,41 @@ void repositoryRejectsAttemptToReplaceStableRealmIdentity() throws Exception { } } + @Test + void catalogOnlyUpdatePreservesPointerVersionAndFencesStaleCatalogRevision() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-catalog-cas;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = + new GameplayAdmissionPointerRepository(dsl); + repository.save(pointer(7L, 44L, "SHARED", "production")); + + GameplayAdmissionPointer stale = + repository + .findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production") + .orElseThrow(); + GameplayAdmissionPointer catalogUpdate = + repository + .findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production") + .orElseThrow(); + catalogUpdate.setWorldDisplayName("Renamed Demo World"); + catalogUpdate.setPointerVersion(1L); + catalogUpdate.setCatalogRevision(2L); + + GameplayAdmissionPointer updated = repository.save(catalogUpdate); + + assertEquals(1L, updated.getPointerVersion()); + assertEquals(2L, updated.getCatalogRevision()); + + stale.setRealmDisplayName("Stale Realm Display"); + stale.setPointerVersion(1L); + stale.setCatalogRevision(2L); + assertThrows(AdmissionPointerVersionMismatchException.class, () -> repository.save(stale)); + } + } + private static GameplayAdmissionPointer pointer( long tenantId, long gameInstanceId, String stateScope, String realmSlug) { GameplayAdmissionPointer pointer = new GameplayAdmissionPointer(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index f84933a724..cc13f21eb4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -3,7 +3,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; 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.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.Optional; @@ -132,6 +134,72 @@ void upsertPointerAllowsCreateWhenExpectedVersionIsZero() { verify(eventRepository).save(any(GameplayAdmissionPointerEvent.class)); } + @Test + void upsertPointerAdvancesCatalogRevisionWithoutAdvancingPointerVersion() { + GameplayAdmissionPointer existing = existingPointer(); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + .thenReturn(Optional.of(existing)); + when(pointerRepository.save(any(GameplayAdmissionPointer.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + + GameplayAdmissionPointerSnapshot snapshot = + service.upsertPointer( + new GameplayAdmissionPointerMutation( + "demo", + "Renamed Demo World", + "production", + "Live Realm", + 1L, + 7L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "display update", + "req-catalog-only", + 1L, + null)); + + assertEquals(1L, snapshot.pointerVersion()); + assertEquals(2L, snapshot.catalogRevision()); + verify(pointerRepository).save(any(GameplayAdmissionPointer.class)); + verify(eventRepository).save(any(GameplayAdmissionPointerEvent.class)); + } + + @Test + void upsertPointerExactNoOpDoesNotAdvanceOrPersistVersions() { + GameplayAdmissionPointer existing = existingPointer(); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + .thenReturn(Optional.of(existing)); + + GameplayAdmissionPointerSnapshot snapshot = + service.upsertPointer( + new GameplayAdmissionPointerMutation( + "demo", + "Demo World", + "production", + "Live Realm", + 1L, + 7L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "repeat", + "req-no-op", + 1L, + null)); + + assertEquals(1L, snapshot.pointerVersion()); + assertEquals(1L, snapshot.catalogRevision()); + verify(pointerRepository, never()).save(any(GameplayAdmissionPointer.class)); + verifyNoInteractions(eventRepository); + } + @Test void findPointerByTenantAndRealmSlugDelegatesToRepository() { GameplayAdmissionPointer existing = new GameplayAdmissionPointer(); @@ -152,4 +220,23 @@ void findPointerByTenantAndRealmSlugDelegatesToRepository() { assertEquals(44L, snapshot.gameInstanceId()); verify(pointerRepository).findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production"); } + + private static GameplayAdmissionPointer existingPointer() { + GameplayAdmissionPointer pointer = new GameplayAdmissionPointer(); + pointer.setId(11L); + pointer.setWorldSlug("demo"); + pointer.setWorldDisplayName("Demo World"); + pointer.setRealmSlug("production"); + pointer.setRealmDisplayName("Live Realm"); + pointer.setTenantId(1L); + pointer.setGameInstanceId(7L); + pointer.setPointerVersion(1L); + pointer.setCatalogRevision(1L); + pointer.setVisible(true); + pointer.setPublicProductionRealm(true); + pointer.setRequiresCharacterSelection(false); + pointer.setStateScope("SHARED"); + pointer.setCharacterCreationPolicy("ALLOW_NEW"); + return pointer; + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 8d1e514af6..32a0621249 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -763,14 +763,14 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { GameplayAdmissionPointerSnapshot policyChanged = authorityService.upsertPointer(pointerMutation(44L, false, 1L)); GameplayAdmissionPointerSnapshot routeChanged = - authorityService.upsertPointer(pointerMutation(45L, false, 2L)); + authorityService.upsertPointer(pointerMutation(45L, false, 1L)); assertEquals(1L, created.catalogRevision()); assertEquals(1L, created.pointerVersion()); assertEquals(2L, policyChanged.catalogRevision()); - assertEquals(2L, policyChanged.pointerVersion()); + assertEquals(1L, policyChanged.pointerVersion()); assertEquals(2L, routeChanged.catalogRevision()); - assertEquals(3L, routeChanged.pointerVersion()); + assertEquals(2L, routeChanged.pointerVersion()); } private static GameplayAdmissionPointerMutation pointerMutation( From caf1c9437ae5cb0f9635a30d62efaa29c0705962 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 07:54:52 +1300 Subject: [PATCH 12/75] Retain JOIN scope evidence and stabilize Account replay --- .../account-service/runtime-and-data.md | 2 + .../player-access-and-session.md | 2 +- .../AccountConnectScopeRepository.java | 43 ++++++ .../ExpiredConnectScopeCleanupJob.java | 70 ++++++++++ .../service/impl/AccountServiceImpl.java | 51 +++---- .../src/main/resources/application-prod.yml | 4 + .../src/main/resources/application.yml | 4 + .../V27__retain_join_connect_scopes.sql | 10 ++ .../AccountRepositoryIntegrationTest.java | 126 +++++++++++++++++- .../service/impl/AccountServiceImplTest.java | 94 ++++++++++++- 10 files changed, 372 insertions(+), 34 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java create mode 100644 services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 108d19b6e1..f421afdae9 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -16,6 +16,8 @@ Account V25 enforces the live tenant-scoped profile identity `(tenantId, account Account implements bounded owner-local cleanup of expired password-reset, email-verification, and email-login-challenge SQL rows, with per-family deleted-row counts and oldest-expired-row lag metrics. The cleanup uses the same process-local wall-clock basis as current credential issuance and validation against timezone-less SQL timestamps; cross-node timezone normalization and existing-row migration are not established by this cleanup. Six focused unit cases in `ExpiredCredentialCleanupJobTest` executed locally; seven PostgreSQL integration cases in `CredentialCleanupRepositoryIntegrationTest` passed in hosted CI, while local execution compiles but skips them when Docker is unavailable. This cleanup does not claim atomic token consumption, session revocation, or completion of the full [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) retention contract; shared retention classes, dependency horizons, blockers, holds, and cross-service proof remain outstanding. +Account also performs a bounded sweep of public connect-scope evidence after its configured scope expiry. It deletes only rows with a valid parsed expiry at or before the captured UTC time and no `account_join_operations` reference of any status; malformed expiry rows remain untouched without blocking valid rows. V27 adds a restrictive foreign key from each JOIN operation to its exact scope row, fencing concurrent intent insertion against deletion. The sweep does not expire JOIN operation receipts or change account-deletion retention. + The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback returns a stored terminal outcome when present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. Successful repeated JOINs replay the stored operation result; `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index b70063cb42..e5899fc3b9 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -30,7 +30,7 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current registration creates global Account identity plus platform audit outbox evidence only; it does not create a tenant membership or profile, and legacy tenant input is not authority. Source covers the zero-membership/profile registration boundary, but PostgreSQL runtime proof and deployment retained-row disposition/readback remain open. The current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. Lifecycle-state retention is tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, rechecks fresh entitlement and public-join policy at the commit gate, binds a v1 digest to the verified caller/scope and policy evidence, and writes the membership, stored operation outcome, and tenant audit outbox evidence in one Account transaction. Global-only registration no longer creates an admitting membership. The durable recovery/reconciliation seam for JOIN left `PENDING` after an unknown database commit outcome remains unresolved under the Overseer decision and ADR 0025; do not mark ADR 0025 complete. PostgreSQL runtime proof and direct text-client end-to-end proof remain unclaimed. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, rechecks fresh entitlement and public-join policy at the commit gate, binds a v1 digest to the verified caller/scope and policy evidence, and writes the membership, stored operation outcome, and tenant audit outbox evidence in one Account transaction. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are now swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. The durable recovery/reconciliation seam for JOIN left `PENDING` after an unknown database commit outcome remains unresolved under the Overseer decision and ADR 0025; do not mark ADR 0025 complete. PostgreSQL runtime proof and direct text-client end-to-end proof remain unclaimed. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. Generic payment scaffolds still retain provider-mutating drift. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java index 79de6c47e6..113107071e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java @@ -3,6 +3,9 @@ import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNT_CONNECT_SCOPE_RECORDS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; import java.util.Optional; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; @@ -16,6 +19,28 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class AccountConnectScopeRepository { + private static final String DELETE_EXPIRED_UNREFERENCED_SQL = + "DELETE FROM account_connect_scope_records scope " + + "WHERE scope.ctid IN (" + + " SELECT candidate.ctid " + + " FROM account_connect_scope_records candidate " + + " WHERE CASE " + + " WHEN candidate.connect_scope_expires_at ~ " + + " '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{1,9})?Z$' " + + " AND pg_input_is_valid(candidate.connect_scope_expires_at, " + + " 'timestamp with time zone') " + + " THEN candidate.connect_scope_expires_at::timestamptz <= CAST(? AS timestamptz) " + + " ELSE FALSE " + + " END " + + " AND NOT EXISTS (" + + " SELECT 1 FROM account_join_operations operation " + + " WHERE operation.scope_token_hash = candidate.scope_token_hash" + + " ) " + + " ORDER BY candidate.account_id, candidate.scope_token_hash " + + " LIMIT ? " + + " FOR UPDATE OF candidate SKIP LOCKED" + + ")"; + private final DSLContext dsl; public AccountConnectScopeRepository(DSLContext dsl) { @@ -54,6 +79,24 @@ public Optional find(String connectScopeId) { .fetchOptional(record -> toScope(record, connectScopeId)); } + /** + * Deletes a bounded batch of expired scopes only when no JOIN receipt references them. + * Malformed expiry values are retained. The database FK from JOIN receipts is the concurrent + * insert fence for the anti-join predicate. + */ + public int deleteExpiredUnreferenced(Instant capturedNow, int batchSize) { + if (capturedNow == null) { + throw new IllegalArgumentException("Captured cleanup time is required"); + } + if (batchSize <= 0) { + throw new IllegalArgumentException("Cleanup batch size must be positive"); + } + return dsl.execute( + DELETE_EXPIRED_UNREFERENCED_SQL, + OffsetDateTime.ofInstant(capturedNow, ZoneOffset.UTC), + batchSize); + } + private VerifiedJoinScope toScope(Record record, String connectScopeId) { if (!"PUBLIC_PRODUCTION".equals(record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.TARGET_CLASS))) { throw new IllegalStateException("JOIN scope is not public production"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java new file mode 100644 index 0000000000..19b8f9bbff --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java @@ -0,0 +1,70 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.micrometer.core.annotation.Timed; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.MeterRegistry; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.common.LoggingUtil; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** Bounded owner-local cleanup of expired connect scopes not retained by a JOIN receipt. */ +@Component +@SuppressFBWarnings( + value = {"EI_EXPOSE_REP2", "CT_CONSTRUCTOR_THROW"}, + justification = + "Injected Spring collaborators are internal; invalid cleanup configuration must fail startup.") +public class ExpiredConnectScopeCleanupJob { + private static final Logger logger = LoggingUtil.getLogger(ExpiredConnectScopeCleanupJob.class); + + private final AccountConnectScopeRepository connectScopeRepository; + private final int batchSize; + private final Counter deleted; + private final Counter failures; + + public ExpiredConnectScopeCleanupJob( + AccountConnectScopeRepository connectScopeRepository, + MeterRegistry meterRegistry, + @Value("${firemud.account.connect-scopes.cleanup.batch-size:100}") int batchSize, + @Value("${firemud.account.connect-scopes.cleanup.interval-ms:60000}") long intervalMs) { + if (batchSize <= 0) { + throw new IllegalArgumentException( + "firemud.account.connect-scopes.cleanup.batch-size must be positive"); + } + if (intervalMs <= 0) { + throw new IllegalArgumentException( + "firemud.account.connect-scopes.cleanup.interval-ms must be positive"); + } + this.connectScopeRepository = connectScopeRepository; + this.batchSize = batchSize; + this.deleted = + Counter.builder("account.connect_scopes.cleanup.deleted") + .description("Expired unreferenced Account connect-scope rows deleted") + .register(meterRegistry); + this.failures = + Counter.builder("account.connect_scopes.cleanup.failure") + .description("Account connect-scope cleanup failures") + .register(meterRegistry); + } + + @Timed(value = "account.connect_scopes.cleanup") + @Scheduled( + fixedDelayString = "${firemud.account.connect-scopes.cleanup.interval-ms:60000}", + timeUnit = TimeUnit.MILLISECONDS) + public void cleanupExpiredConnectScopes() { + Instant capturedNow = Instant.now(); + try { + deleted.increment( + connectScopeRepository.deleteExpiredUnreferenced(capturedNow, batchSize)); + } catch (RuntimeException ex) { + failures.increment(); + logger.warn( + "Expired connect-scope cleanup step failed ({})", ex.getClass().getSimpleName()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 1228b3e583..a8fbb8394e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -388,7 +388,19 @@ public List listBootstrapRealms(String bootstrapToken, String Instant evaluatedAt = Instant.now(); Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); return listAdmissibleRuntimeRealmTargets(bootstrapContext, worldSlug).stream() - .map(realm -> requireRealmTarget(realm.tenantId(), realm.worldSlug(), realm.realmSlug())) + .map( + discovered -> { + RuntimeRealmTarget current = + requireRealmTarget( + discovered.tenantId(), discovered.worldSlug(), discovered.realmSlug()); + if (discovered.visible() != current.visible() + || discovered.publicProductionRealm() != current.publicProductionRealm()) { + throw admissionPointerUnavailable( + new IllegalStateException( + "Public realm is no longer visible for bootstrap discovery")); + } + return current; + }) .map( realm -> new BootstrapRealmDto( @@ -562,6 +574,10 @@ private JoinPublicProductionResult joinPublicProductionForTrustedCaller( } catch (RuntimeException ex) { Optional claimReadback = safeFindJoinOperation(requestId); if (claimReadback.isEmpty()) { + if (connectScopeEvidenceIsMissing(request.connectScopeId())) { + throw new AuthenticationException( + "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable", ex); + } throw new AuthenticationException( "AUTH_UNAVAILABLE", "JOIN request claim is uncertain; retry the same request", ex); } @@ -611,7 +627,7 @@ private JoinPublicProductionResult executeJoinAttempt( requireMatchingJoinIntent(operation, requestId, callerBinding, scope); if (!"PENDING".equals(operation.status())) { - return replayJoinOperation(operation, callerBinding, scope); + return resultFromJoinOperation(operation, true); } if (isConnectScopeExpired(scope)) { @@ -783,6 +799,14 @@ private VerifiedJoinScope retainedJoinScope(String connectScopeId) { "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable")); } + private boolean connectScopeEvidenceIsMissing(String connectScopeId) { + try { + return accountConnectScopeRepository.find(connectScopeId).isEmpty(); + } catch (RuntimeException ex) { + return false; + } + } + private void validateSignedJoinScope( ConnectScopeContext signedScope, VerifiedJoinScope retained, long accountId) { if (retained.accountId() != accountId @@ -820,29 +844,6 @@ private void requireMatchingJoinIntent( } } - private JoinPublicProductionResult replayJoinOperation( - JoinOperation operation, String callerBinding, VerifiedJoinScope scope) { - if (operation.requestDigest() != null) { - JoinEvaluation evaluation = evaluateJoin(scope); - if (evaluation.failureCode() != null) { - throw new AuthenticationException( - evaluation.failureCode(), "Current JOIN authority could not be revalidated"); - } - if (!"AVAILABLE".equals(evaluation.authorityAvailability())) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", "Current JOIN policy could not be revalidated"); - } - String currentDigest = - AccountJoinDigest.request( - scope, callerBinding, evaluation.allowPublicJoin(), evaluation.entitlementVersion()); - if (!Integer.valueOf(1).equals(operation.requestDigestVersion()) - || !operation.requestDigest().equals(currentDigest)) { - throw new AuthenticationException("IDEMPOTENCY_CONFLICT", "JOIN request digest changed"); - } - } - return resultFromJoinOperation(operation, true); - } - private JoinPublicProductionResult resultFromJoinOperation( JoinOperation operation, boolean replayed) { return new JoinPublicProductionResult( diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 9ac4dcca75..a0058cdd88 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -85,6 +85,10 @@ firemud: cleanup: batch-size: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_BATCH_SIZE:100} interval-ms: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_INTERVAL_MS:60000} + connect-scopes: + cleanup: + batch-size: ${FIREMUD_ACCOUNT_CONNECT_SCOPE_CLEANUP_BATCH_SIZE:100} + interval-ms: ${FIREMUD_ACCOUNT_CONNECT_SCOPE_CLEANUP_INTERVAL_MS:60000} tokens: session-expiration-ms: ${FIREMUD_ACCOUNT_TOKENS_SESSION_EXPIRATION_MS:3600000} player-bootstrap-expiration-ms: ${FIREMUD_ACCOUNT_TOKENS_PLAYER_BOOTSTRAP_EXPIRATION_MS:300000} diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 320f48b2c5..526520c5d0 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -45,6 +45,10 @@ firemud: cleanup: batch-size: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_BATCH_SIZE:100} interval-ms: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_INTERVAL_MS:60000} + connect-scopes: + cleanup: + batch-size: ${FIREMUD_ACCOUNT_CONNECT_SCOPE_CLEANUP_BATCH_SIZE:100} + interval-ms: ${FIREMUD_ACCOUNT_CONNECT_SCOPE_CLEANUP_INTERVAL_MS:60000} tokens: session-expiration-ms: 3600000 player-bootstrap-expiration-ms: 300000 diff --git a/services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql b/services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql new file mode 100644 index 0000000000..000416cd86 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql @@ -0,0 +1,10 @@ +-- JOIN operation rows are durable replay evidence and always depend on the exact scope snapshot. +-- Restrictive FK semantics serialize scope reclamation against concurrent intent insertion. +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_operation_scope_reference_fk + FOREIGN KEY (scope_token_hash) + REFERENCES account_connect_scope_records(scope_token_hash) + ON DELETE RESTRICT; + +CREATE INDEX idx_account_join_operations_scope_token_hash + ON account_join_operations(scope_token_hash); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index 1b6005e154..aaf88d6a5b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -3,7 +3,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.nio.file.Path; +import java.time.Instant; +import java.util.List; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; @@ -12,6 +15,7 @@ import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.service.ExpiredConnectScopeCleanupJob; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.FlywayException; import org.jooq.DSLContext; @@ -89,6 +93,7 @@ void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { AccountTenantMembershipRepository memberships = new AccountTenantMembershipRepository(transactionAwareDsl); AccountAuditOutboxRepository outbox = new AccountAuditOutboxRepository(transactionAwareDsl); + AccountConnectScopeRepository scopes = new AccountConnectScopeRepository(transactionAwareDsl); long accountId = Objects.requireNonNull( jdbc.queryForObject( @@ -98,6 +103,7 @@ void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { "two-phase-join@example.com", "hash")); VerifiedJoinScope scope = joinScope(accountId); + scopes.insert(scope); String callerBinding = "bootstrap-jti-two-phase"; String requestId = "join-two-phase-1"; String intentDigest = AccountJoinDigest.intent(requestId, scope, callerBinding); @@ -300,6 +306,100 @@ void connectScopeRepositoryRetainsCanonicalRealmUuidAndDetectsTampering() { .hasMessage("JOIN scope digest mismatch"); } + @Test + void expiredConnectScopeCleanupPreservesEveryReferencedStatusAndMalformedEvidence() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + AccountConnectScopeRepository scopes = new AccountConnectScopeRepository(dsl); + AccountJoinOperationRepository joinOperations = new AccountJoinOperationRepository(dsl); + AccountTenantMembershipRepository memberships = new AccountTenantMembershipRepository(dsl); + long accountId = + Objects.requireNonNull( + jdbc.queryForObject( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + Long.class, + "scope-cleanup", + "scope-cleanup@example.com", + "hash")); + Instant capturedNow = Instant.now(); + String expiredAt = capturedNow.minusSeconds(60).toString(); + VerifiedJoinScope unreferenced = joinScope(accountId, "scope-cleanup-free", expiredAt); + VerifiedJoinScope pending = joinScope(accountId, "scope-cleanup-pending", expiredAt); + VerifiedJoinScope committed = joinScope(accountId, "scope-cleanup-committed", expiredAt); + VerifiedJoinScope failed = joinScope(accountId, "scope-cleanup-failed", expiredAt); + VerifiedJoinScope future = + joinScope(accountId, "scope-cleanup-future", capturedNow.plusSeconds(86_400).toString()); + VerifiedJoinScope malformed = joinScope(accountId, "scope-cleanup-malformed", expiredAt); + VerifiedJoinScope invalidCalendarDate = + joinScope(accountId, "scope-cleanup-invalid-date", expiredAt); + for (VerifiedJoinScope scope : + List.of(unreferenced, pending, committed, failed, future, malformed, invalidCalendarDate)) { + scopes.insert(scope); + } + jdbc.update( + "UPDATE account_connect_scope_records SET connect_scope_expires_at = ? WHERE scope_token_hash = ?", + "not-an-instant", + AccountJoinDigest.tokenHash(malformed.connectScopeId())); + jdbc.update( + "UPDATE account_connect_scope_records SET connect_scope_expires_at = ? WHERE scope_token_hash = ?", + "2026-02-30T10:02:00Z", + AccountJoinDigest.tokenHash(invalidCalendarDate.connectScopeId())); + + insertJoinIntent(joinOperations, pending, "join-scope-pending"); + insertJoinIntent(joinOperations, committed, "join-scope-committed"); + insertJoinIntent(joinOperations, failed, "join-scope-failed"); + joinOperations.finish( + "join-scope-failed", "FAILED", "CONNECT_SCOPE_INVALID", null, null, null); + joinOperations.bindPolicyEvidence( + "join-scope-committed", + AccountJoinDigest.request(committed, "scope-cleanup-committed-caller", true, 1L), + 1L, + true); + Account account = new Account(); + account.setId(accountId); + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setAccount(account); + membership.setTenantId(committed.tenantId()); + membership.setLifecycleState("ACTIVE"); + membership.setGameplayAdmissionAllowed(true); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(1L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + memberships.save(membership); + joinOperations.finish( + "join-scope-committed", + "COMMITTED", + "JOINED", + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration()); + + SimpleMeterRegistry meters = new SimpleMeterRegistry(); + ExpiredConnectScopeCleanupJob cleanupJob = + new ExpiredConnectScopeCleanupJob(scopes, meters, 100, 60_000); + cleanupJob.cleanupExpiredConnectScopes(); + + assertThat(meters.get("account.connect_scopes.cleanup.deleted").counter().count()) + .isEqualTo(1); + assertThat(meters.get("account.connect_scopes.cleanup.failure").counter().count()).isZero(); + assertThat(scopeCount(jdbc, unreferenced)).isZero(); + assertThat(scopeCount(jdbc, pending)).isEqualTo(1); + assertThat(scopeCount(jdbc, committed)).isEqualTo(1); + assertThat(scopeCount(jdbc, failed)).isEqualTo(1); + assertThat(scopeCount(jdbc, future)).isEqualTo(1); + assertThat(scopeCount(jdbc, malformed)).isEqualTo(1); + assertThat(scopeCount(jdbc, invalidCalendarDate)).isEqualTo(1); + assertThatThrownBy( + () -> + jdbc.update( + "DELETE FROM account_connect_scope_records WHERE scope_token_hash = ?", + AccountJoinDigest.tokenHash(pending.connectScopeId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> insertJoinIntent(joinOperations, unreferenced, "join-scope-after-cleanup")) + .isInstanceOf(DataAccessException.class); + assertThat(joinOperations.find("join-scope-after-cleanup")).isEmpty(); + } + private void commitJoinOutcome( AccountJoinOperationRepository joinOperations, AccountTenantMembershipRepository memberships, @@ -338,15 +438,37 @@ private void commitJoinOutcome( } } + private void insertJoinIntent( + AccountJoinOperationRepository joinOperations, VerifiedJoinScope scope, String requestId) { + joinOperations.insertIntent( + requestId, + scope, + "scope-cleanup-committed-caller", + AccountJoinDigest.intent(requestId, scope, "scope-cleanup-committed-caller")); + } + + private static long scopeCount(JdbcTemplate jdbc, VerifiedJoinScope scope) { + return Objects.requireNonNull( + jdbc.queryForObject( + "SELECT COUNT(*) FROM account_connect_scope_records WHERE scope_token_hash = ?", + Long.class, + AccountJoinDigest.tokenHash(scope.connectScopeId()))); + } + private AccountJoinOperationRepository.JoinOperation joinOperation( AccountJoinOperationRepository joinOperations, String requestId) { return joinOperations.find(requestId).orElseThrow(); } private static VerifiedJoinScope joinScope(long accountId) { + return joinScope(accountId, "two-phase-connect-scope", "2026-09-24T10:02:00Z"); + } + + private static VerifiedJoinScope joinScope( + long accountId, String connectScopeId, String expiresAt) { VerifiedJoinScope base = new VerifiedJoinScope( - "two-phase-connect-scope", + connectScopeId, accountId, 7L, REALM_ID, @@ -358,7 +480,7 @@ private static VerifiedJoinScope joinScope(long accountId) { 23L, 17L, "2026-09-24T10:00:00Z", - "2026-09-24T10:02:00Z", + expiresAt, "unused"); String digest = AccountJoinDigest.scope(base); return new VerifiedJoinScope( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 5a92fe42b9..98a65c28d4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -444,15 +444,16 @@ void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { assertEquals("FAILED", retainedOperation.get().status()); grace.setStatus("active"); grace.setEntitlementVersion(2L); - AuthenticationException changedPolicy = - assertThrows( - AuthenticationException.class, - () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); - assertEquals("IDEMPOTENCY_CONFLICT", changedPolicy.getCode()); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); + JoinPublicProductionResult unavailableAuthorityReplay = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertFalse(unavailableAuthorityReplay.success()); + assertTrue(unavailableAuthorityReplay.replayed()); + assertEquals(denied.outcomeCode(), unavailableAuthorityReplay.outcomeCode()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) .findByTenantIdForUpdate(7L); } @@ -868,6 +869,52 @@ void joinPublicProductionReturnsConflictWhenGlobalRequestIdClaimIsLost() { org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); } + @Test + void reclaimedScopeRaceReturnsConnectScopeInvalid() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + VerifiedJoinScope scope = retainedScope.get(); + org.mockito.Mockito.clearInvocations( + subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + when(accountConnectScopeRepository.find(connectScopeId)) + .thenReturn(Optional.of(scope), Optional.empty()); + org.mockito.Mockito.doThrow(new org.jooq.exception.DataAccessException("scope reclaimed")) + .when(accountJoinOperationRepository) + .insertIntent( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-reclaimed-scope"))); + + assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); + verifyNoInteractions( + subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + } + @Test void quarantinedLegacyMembershipIsNeverRestoredByPublicJoin() { Account account = new Account(); @@ -1713,6 +1760,41 @@ void listBootstrapRealmsAcceptsExactlyOneVisiblePublicRealm() { assertEquals("production", realms.getFirst().realmSlug()); } + @Test + void listBootstrapRealmsDoesNotIssueScopeWhenPublicPointerBecomesPrivateBeforeFinalRead() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + 11L, 7L, "demo", "production")) + .thenReturn(true); + + var initiallyPublic = gameSessionClient.listGameplayRealms("demo").getFirst(); + var currentlyPrivate = initiallyPublic.toBuilder().setPublicProductionRealm(false).build(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(java.util.List.of(initiallyPublic), java.util.List.of(currentlyPrivate)); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, false, "SHARED", "ALLOW_NEW")); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any()); + } + @ParameterizedTest @ValueSource(strings = {"101", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { From bb62fbd223774bbc7299b99f6a6c048266431257 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 07:54:57 +1300 Subject: [PATCH 13/75] Fence admission catalog writes with version pairs --- .../v1/game_session_service.proto | 3 + ...yAdmissionPointerBootstrapInitializer.java | 3 +- .../entity/GameplayAdmissionPointerEvent.java | 1 + ...meplayAdmissionPointerEventRepository.java | 3 + .../GameplayAdmissionPointerAuditEntry.java | 1 + .../GameplayAdmissionPointerMutation.java | 1 + ...eplayAdmissionPointerAuthorityService.java | 28 +++-- ...onAdmissionPointerControlPlaneService.java | 12 +- ...SessionRuntimeControlPlaneReadService.java | 32 ++--- .../V7__audit_gameplay_catalog_revision.sql | 4 + ...essionWebSocketHandlerIntegrationTest.java | 16 +-- ...issionPointerBootstrapInitializerTest.java | 5 +- ...yAdmissionPointerAuthorityServiceTest.java | 109 +++++++++++++++++- ...ameSessionControlPlaneGrpcServiceTest.java | 99 +++++++++++++++- .../impl/GameSessionGrpcServiceTest.java | 12 +- .../testsupport/GameplayLoadScenarios.java | 3 +- .../loggingadmin/dto/AdmissionPointerDto.java | 1 + .../ExecutePreparedVersionCutoverRequest.java | 3 +- .../dto/SetAdmissionPointerRequest.java | 4 +- .../impl/AdmissionPointerServiceImpl.java | 7 ++ .../src/main/resources/openapi.yaml | 3 + .../AdmissionPointerControllerTest.java | 9 +- .../impl/AdmissionPointerServiceImplTest.java | 12 +- 23 files changed, 321 insertions(+), 50 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index f3e63f02bc..af6f522d73 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -416,6 +416,7 @@ message AdmissionPointerControlPlaneEntry { int64 occurred_at_ms = 15; string prepared_version_upgrade_id = 16; bool public_production_realm = 17; + optional int64 catalog_revision = 18; } message ListAdmissionPointersRequest {} @@ -1097,6 +1098,7 @@ message SetAdmissionPointerRequest { optional int64 expected_pointer_version = 14; string prepared_version_upgrade_id = 15; bool public_production_realm = 16; + optional int64 expected_catalog_revision = 17; } message SetAdmissionPointerResponse { @@ -1114,6 +1116,7 @@ message ExecutePreparedVersionCutoverRequest { string reason = 7; string control_plane_request_id = 8; optional int64 expected_pointer_version = 9; + optional int64 expected_catalog_revision = 10; } message ExecutePreparedVersionCutoverResponse { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java index d71a6d4518..bf5f0c2d1d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java @@ -68,7 +68,8 @@ public void run(ApplicationArguments args) { + pointer.getWorldSlug() + ":" + pointer.getRealmSlug(), - null, + 0L, + 0L, null)); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointerEvent.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointerEvent.java index 45ff8daf90..00a115379a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointerEvent.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointerEvent.java @@ -13,6 +13,7 @@ public class GameplayAdmissionPointerEvent { private Long tenantId; private Long gameInstanceId; private Long pointerVersion; + private Long catalogRevision; private boolean visible; private boolean publicProductionRealm; private boolean requiresCharacterSelection; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java index 1acf68a0f3..6b4f1a2928 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java @@ -69,6 +69,7 @@ public GameplayAdmissionPointerEvent save(GameplayAdmissionPointerEvent entity) .set(GAMEPLAY_ADMISSION_POINTER_EVENT.TENANT_ID, entity.getTenantId()) .set(GAMEPLAY_ADMISSION_POINTER_EVENT.GAME_INSTANCE_ID, entity.getGameInstanceId()) .set(GAMEPLAY_ADMISSION_POINTER_EVENT.POINTER_VERSION, entity.getPointerVersion()) + .set(GAMEPLAY_ADMISSION_POINTER_EVENT.CATALOG_REVISION, entity.getCatalogRevision()) .set(GAMEPLAY_ADMISSION_POINTER_EVENT.VISIBLE, entity.isVisible()) .set( GAMEPLAY_ADMISSION_POINTER_EVENT.PUBLIC_PRODUCTION_REALM, @@ -120,6 +121,7 @@ private void populate( record.setTenantId(entity.getTenantId()); record.setGameInstanceId(entity.getGameInstanceId()); record.setPointerVersion(entity.getPointerVersion()); + record.setCatalogRevision(entity.getCatalogRevision()); record.setVisible(entity.isVisible()); record.setPublicProductionRealm(entity.isPublicProductionRealm()); record.setRequiresCharacterSelection(entity.isRequiresCharacterSelection()); @@ -142,6 +144,7 @@ private GameplayAdmissionPointerEvent toEntity(Record record) { entity.setTenantId(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.TENANT_ID)); entity.setGameInstanceId(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.GAME_INSTANCE_ID)); entity.setPointerVersion(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.POINTER_VERSION)); + entity.setCatalogRevision(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.CATALOG_REVISION)); entity.setVisible(Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.VISIBLE))); entity.setPublicProductionRealm( Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.PUBLIC_PRODUCTION_REALM))); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuditEntry.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuditEntry.java index 5e61c7f8d4..8c8f3b4839 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuditEntry.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuditEntry.java @@ -10,6 +10,7 @@ public record GameplayAdmissionPointerAuditEntry( long tenantId, long gameInstanceId, long pointerVersion, + Long catalogRevision, boolean visible, boolean publicProductionRealm, boolean requiresCharacterSelection, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerMutation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerMutation.java index dbe44b3784..b38d0d3359 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerMutation.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerMutation.java @@ -16,4 +16,5 @@ public record GameplayAdmissionPointerMutation( String reason, String controlPlaneRequestId, Long expectedPointerVersion, + Long expectedCatalogRevision, String preparedVersionUpgradeId) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index f2e4ec779e..079c0ec271 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -83,7 +83,8 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu throw new IllegalArgumentException( "state_scope changes require a new playable-state lifecycle"); } - enforceExpectedPointerVersion(pointer, mutation.expectedPointerVersion()); + enforceExpectedVersions( + pointer, mutation.expectedPointerVersion(), mutation.expectedCatalogRevision()); if (pointer.getId() != null && runtimeTargetMatches(pointer, mutation) && catalogPolicyMatches(pointer, mutation)) { @@ -125,6 +126,7 @@ && catalogPolicyMatches(pointer, mutation)) { event.setTenantId(saved.getTenantId()); event.setGameInstanceId(saved.getGameInstanceId()); event.setPointerVersion(saved.getPointerVersion()); + event.setCatalogRevision(saved.getCatalogRevision()); event.setVisible(saved.isVisible()); event.setPublicProductionRealm(saved.isPublicProductionRealm()); event.setRequiresCharacterSelection(saved.isRequiresCharacterSelection()); @@ -157,6 +159,7 @@ public List listPointerAudit( event.getTenantId(), event.getGameInstanceId(), event.getPointerVersion(), + event.getCatalogRevision(), event.isVisible(), event.isPublicProductionRealm(), event.isRequiresCharacterSelection(), @@ -248,15 +251,24 @@ private void requireText(String value, String message) { } } - private void enforceExpectedPointerVersion( - GameplayAdmissionPointer pointer, Long expectedPointerVersion) { - if (expectedPointerVersion == null) { - return; + private void enforceExpectedVersions( + GameplayAdmissionPointer pointer, Long expectedPointerVersion, Long expectedCatalogRevision) { + if (expectedPointerVersion == null || expectedCatalogRevision == null) { + throw new AdmissionPointerVersionMismatchException( + "expected_pointer_version and expected_catalog_revision are required"); } - long currentPointerVersion = pointer.getId() == null ? 0L : pointer.getPointerVersion(); - if (currentPointerVersion != expectedPointerVersion) { + long currentPointerVersion = + pointer.getId() == null + ? 0L + : pointer.getPointerVersion() == null ? -1L : pointer.getPointerVersion(); + long currentCatalogRevision = + pointer.getId() == null + ? 0L + : pointer.getCatalogRevision() == null ? -1L : pointer.getCatalogRevision(); + if (currentPointerVersion != expectedPointerVersion + || currentCatalogRevision != expectedCatalogRevision) { throw new AdmissionPointerVersionMismatchException( - "expected_pointer_version does not match current pointer version"); + "expected admission-pointer version pair does not match current pointer state"); } } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java index 614b33e18c..1fa09446cd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java @@ -52,7 +52,7 @@ ListAdmissionPointersResponse listAdmissionPointers() { + "/" + pointer.realmSlug()); } - return toEntry(audit.getFirst()); + return toEntry(audit.getFirst(), pointer.catalogRevision()); }) .toList(); return ListAdmissionPointersResponse.newBuilder().addAllPointers(entries).build(); @@ -94,6 +94,7 @@ SetAdmissionPointerResponse setAdmissionPointer( request.getReason(), request.getControlPlaneRequestId(), request.hasExpectedPointerVersion() ? request.getExpectedPointerVersion() : null, + request.hasExpectedCatalogRevision() ? request.getExpectedCatalogRevision() : null, normalizeBlank(request.getPreparedVersionUpgradeId()))); return SetAdmissionPointerResponse.newBuilder() .setPointer(latestAuditEntry(tenantId, request.getWorldSlug(), request.getRealmSlug())) @@ -150,6 +151,7 @@ ExecutePreparedVersionCutoverResponse executePreparedVersionCutover( request.getReason(), request.getControlPlaneRequestId(), request.hasExpectedPointerVersion() ? request.getExpectedPointerVersion() : null, + request.hasExpectedCatalogRevision() ? request.getExpectedCatalogRevision() : null, request.getPreparedVersionUpgradeId())); AdmissionPointerControlPlaneEntry entry = latestAuditEntry(tenantId, request.getWorldSlug(), request.getRealmSlug()); @@ -191,12 +193,20 @@ private AdmissionPointerControlPlaneEntry toEntry(GameplayAdmissionPointerAuditE .setReason(entry.reason()) .setControlPlaneRequestId(entry.controlPlaneRequestId()) .setOccurredAtMs(entry.occurredAt().toEpochMilli()); + if (entry.catalogRevision() != null && entry.catalogRevision() > 0L) { + builder.setCatalogRevision(entry.catalogRevision()); + } if (!normalizeBlank(entry.preparedVersionUpgradeId()).isEmpty()) { builder.setPreparedVersionUpgradeId(entry.preparedVersionUpgradeId()); } return builder.build(); } + private AdmissionPointerControlPlaneEntry toEntry( + GameplayAdmissionPointerAuditEntry entry, long currentCatalogRevision) { + return toEntry(entry).toBuilder().setCatalogRevision(currentCatalogRevision).build(); + } + private void validatePreparedUpgradeForPointerChange( SetAdmissionPointerRequest request, long tenantId, long targetGameInstanceId) { GameplayAdmissionPointerSnapshot currentPointer = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java index abced3a9f8..dc7cbf3e8f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java @@ -369,20 +369,24 @@ private GameplayRoutingBundle toGameplayRoutingBundle(GameplayAdmissionPointerSn private AdmissionPointerControlPlaneEntry toControlPlaneEntry( GameplayAdmissionPointerSnapshot pointer) { - return AdmissionPointerControlPlaneEntry.newBuilder() - .setWorldSlug(normalizeBlank(pointer.worldSlug())) - .setWorldDisplayName(normalizeBlank(pointer.worldDisplayName())) - .setRealmSlug(normalizeBlank(pointer.realmSlug())) - .setRealmDisplayName(normalizeBlank(pointer.realmDisplayName())) - .setTenantId(Long.toString(pointer.tenantId())) - .setGameInstanceId(Long.toString(pointer.gameInstanceId())) - .setPointerVersion(pointer.pointerVersion()) - .setVisible(pointer.visible()) - .setRequiresCharacterSelection(pointer.requiresCharacterSelection()) - .setStateScope(normalizeBlank(pointer.stateScope())) - .setCharacterCreationPolicy(normalizeBlank(pointer.characterCreationPolicy())) - .setPublicProductionRealm(pointer.publicProductionRealm()) - .build(); + AdmissionPointerControlPlaneEntry.Builder builder = + AdmissionPointerControlPlaneEntry.newBuilder() + .setWorldSlug(normalizeBlank(pointer.worldSlug())) + .setWorldDisplayName(normalizeBlank(pointer.worldDisplayName())) + .setRealmSlug(normalizeBlank(pointer.realmSlug())) + .setRealmDisplayName(normalizeBlank(pointer.realmDisplayName())) + .setTenantId(Long.toString(pointer.tenantId())) + .setGameInstanceId(Long.toString(pointer.gameInstanceId())) + .setPointerVersion(pointer.pointerVersion()) + .setVisible(pointer.visible()) + .setRequiresCharacterSelection(pointer.requiresCharacterSelection()) + .setStateScope(normalizeBlank(pointer.stateScope())) + .setCharacterCreationPolicy(normalizeBlank(pointer.characterCreationPolicy())) + .setPublicProductionRealm(pointer.publicProductionRealm()); + if (pointer.catalogRevision() > 0L) { + builder.setCatalogRevision(pointer.catalogRevision()); + } + return builder.build(); } private ScriptPatchPublicationLink scriptPatchPublicationLink( diff --git a/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql b/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql new file mode 100644 index 0000000000..9c8f7892ae --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql @@ -0,0 +1,4 @@ +ALTER TABLE gameplay_admission_pointer_event + ADD COLUMN catalog_revision bigint, + ADD CONSTRAINT gameplay_admission_pointer_event_catalog_revision_positive + CHECK (catalog_revision IS NULL OR catalog_revision > 0); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 5e34a62b3a..0fc35c4d5f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -1609,7 +1609,7 @@ private void performLogoutFlow(String sessionId) throws Exception { private void bumpProductionAdmissionPointer( long newGameInstanceId, boolean requiresCharacterSelection) { - long expectedPointerVersion = + GameplayAdmissionPointerSnapshot currentPointer = gameplayAdmissionPointerAuthorityService.listPointers().stream() .filter( pointer -> @@ -1617,8 +1617,7 @@ private void bumpProductionAdmissionPointer( && "demo".equals(pointer.worldSlug()) && "production".equals(pointer.realmSlug())) .findFirst() - .orElseThrow() - .pointerVersion(); + .orElseThrow(); gameplayAdmissionPointerAuthorityService.upsertPointer( new GameplayAdmissionPointerMutation( "demo", @@ -1634,8 +1633,9 @@ private void bumpProductionAdmissionPointer( "ALLOW_NEW", "integration-test", "cutover-proof", - "req-cutover-" + newGameInstanceId + "-" + expectedPointerVersion, - expectedPointerVersion, + "req-cutover-" + newGameInstanceId + "-" + currentPointer.pointerVersion(), + currentPointer.pointerVersion(), + currentPointer.catalogRevision(), "integration-test-prep-" + newGameInstanceId)); } @@ -1658,7 +1658,8 @@ private void resetAdmissionPointers() { "integration-test", "reset-default-demo-pointer", "req-reset-demo", - null, + 0L, + 0L, null)); gameplayAdmissionPointerAuthorityService.upsertPointer( new GameplayAdmissionPointerMutation( @@ -1676,7 +1677,8 @@ private void resetAdmissionPointers() { "integration-test", "reset-default-sandbox-pointer", "req-reset-sandbox", - null, + 0L, + 0L, null)); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index 732b5c72a5..ac6a03a73d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -61,17 +61,20 @@ void runSeedsBootstrapPointersWhenAuthorityStoreIsEmpty() throws Exception { assertEquals("system/bootstrap", mutations.get(0).actorPrincipal()); assertEquals("Initial gameplay pointer bootstrap", mutations.get(0).reason()); assertEquals("bootstrap:1:1:demo:production", mutations.get(0).controlPlaneRequestId()); + assertEquals(0L, mutations.get(0).expectedPointerVersion()); + assertEquals(0L, mutations.get(0).expectedCatalogRevision()); assertEquals("sandbox", mutations.get(1).worldSlug()); assertTrue(mutations.get(1).requiresCharacterSelection()); } @Test - void runDoesNothingWhenAuthorityStoreAlreadyHasPointers() throws Exception { + void runSkipsSeedMutationsOnRestartWhenAuthorityStoreAlreadyHasPointers() throws Exception { when(pointerRepository.count()).thenReturn(3L); initializer.run(new DefaultApplicationArguments(new String[] {})); verify(authorityService, never()).upsertPointer(org.mockito.ArgumentMatchers.any()); + verify(pointerRepository).count(); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index cc13f21eb4..698c7c2759 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -8,6 +8,7 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.util.List; import java.util.Optional; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; @@ -64,6 +65,7 @@ void upsertPointerRejectsMismatchedExpectedVersion() { "cutover", "req-1", 2L, + 1L, null))); } @@ -89,11 +91,12 @@ void upsertPointerRejectsUnknownStateScope() { "cutover", "req-invalid-scope", null, + null, null))); } @Test - void upsertPointerAllowsCreateWhenExpectedVersionIsZero() { + void upsertPointerAllowsCreateWhenExpectedVersionPairIsZero() { when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) .thenReturn(Optional.empty()); when(pointerRepository.save(any(GameplayAdmissionPointer.class))) @@ -124,6 +127,7 @@ void upsertPointerAllowsCreateWhenExpectedVersionIsZero() { "cutover", "req-2", 0L, + 0L, "pvu-1")); ArgumentCaptor pointerCaptor = @@ -131,7 +135,11 @@ void upsertPointerAllowsCreateWhenExpectedVersionIsZero() { verify(pointerRepository).save(pointerCaptor.capture()); assertEquals(1L, pointerCaptor.getValue().getPointerVersion()); assertEquals(1L, snapshot.pointerVersion()); - verify(eventRepository).save(any(GameplayAdmissionPointerEvent.class)); + assertEquals(1L, snapshot.catalogRevision()); + ArgumentCaptor eventCaptor = + ArgumentCaptor.forClass(GameplayAdmissionPointerEvent.class); + verify(eventRepository).save(eventCaptor.capture()); + assertEquals(1L, eventCaptor.getValue().getCatalogRevision()); } @Test @@ -160,12 +168,16 @@ void upsertPointerAdvancesCatalogRevisionWithoutAdvancingPointerVersion() { "display update", "req-catalog-only", 1L, + 1L, null)); assertEquals(1L, snapshot.pointerVersion()); assertEquals(2L, snapshot.catalogRevision()); verify(pointerRepository).save(any(GameplayAdmissionPointer.class)); - verify(eventRepository).save(any(GameplayAdmissionPointerEvent.class)); + ArgumentCaptor eventCaptor = + ArgumentCaptor.forClass(GameplayAdmissionPointerEvent.class); + verify(eventRepository).save(eventCaptor.capture()); + assertEquals(2L, eventCaptor.getValue().getCatalogRevision()); } @Test @@ -192,6 +204,7 @@ void upsertPointerExactNoOpDoesNotAdvanceOrPersistVersions() { "repeat", "req-no-op", 1L, + 1L, null)); assertEquals(1L, snapshot.pointerVersion()); @@ -200,6 +213,96 @@ void upsertPointerExactNoOpDoesNotAdvanceOrPersistVersions() { verifyNoInteractions(eventRepository); } + @Test + void upsertPointerRejectsStaleCatalogRevisionEvenWhenPointerVersionMatches() { + GameplayAdmissionPointer existing = existingPointer(); + existing.setCatalogRevision(2L); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + .thenReturn(Optional.of(existing)); + + assertThrows( + AdmissionPointerVersionMismatchException.class, + () -> + service.upsertPointer( + new GameplayAdmissionPointerMutation( + "demo", + "Stale Demo World", + "production", + "Live Realm", + 1L, + 7L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "stale catalog edit", + "req-stale-catalog", + 1L, + 1L, + null))); + + verify(pointerRepository, never()).save(any(GameplayAdmissionPointer.class)); + verifyNoInteractions(eventRepository); + } + + @Test + void upsertPointerRejectsExistingMutationWithoutExpectedPair() { + GameplayAdmissionPointer existing = existingPointer(); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + .thenReturn(Optional.of(existing)); + + assertThrows( + AdmissionPointerVersionMismatchException.class, + () -> + service.upsertPointer( + new GameplayAdmissionPointerMutation( + "demo", + "Renamed Demo World", + "production", + "Live Realm", + 1L, + 7L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "missing precondition", + "req-missing-pair", + null, + null, + null))); + + verify(pointerRepository, never()).save(any(GameplayAdmissionPointer.class)); + verifyNoInteractions(eventRepository); + } + + @Test + void listPointerAuditExposesPersistedCatalogRevision() { + GameplayAdmissionPointerEvent event = new GameplayAdmissionPointerEvent(); + event.setWorldSlug("demo"); + event.setRealmSlug("production"); + event.setWorldDisplayName("Renamed Demo World"); + event.setRealmDisplayName("Live Realm"); + event.setTenantId(1L); + event.setGameInstanceId(7L); + event.setPointerVersion(1L); + event.setCatalogRevision(2L); + event.setStateScope("SHARED"); + event.setCharacterCreationPolicy("ALLOW_NEW"); + event.setOccurredAt(java.time.Instant.parse("2026-09-29T00:00:00Z")); + when(eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc( + 1L, "demo", "production")) + .thenReturn(List.of(event)); + + assertEquals( + 2L, + service.listPointerAudit(1L, "demo", "production").getFirst().catalogRevision()); + } + @Test void findPointerByTenantAndRealmSlugDelegatesToRepository() { GameplayAdmissionPointer existing = new GameplayAdmissionPointer(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 33d48d2244..33a4ec009c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -547,7 +547,8 @@ void getGameInstanceRuntimeStateReturnsCanonicalVersionAndPinMetadata() { true, true, "SHARED", - "CREATE_ALLOWED"))); + "CREATE_ALLOWED", + 12L))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = @@ -599,6 +600,9 @@ public void onNext(GetGameInstanceRuntimeStateResponse value) { assertEquals(1, responseRef.get().getRuntimeState().getCurrentAdmissionPointersCount()); assertEquals( "demo", responseRef.get().getRuntimeState().getCurrentAdmissionPointers(0).getWorldSlug()); + assertEquals( + 12L, + responseRef.get().getRuntimeState().getCurrentAdmissionPointers(0).getCatalogRevision()); assertEquals("region-7", responseRef.get().getRuntimeState().getRegionId()); assertEquals(22L, responseRef.get().getRuntimeState().getRegionEpoch()); assertEquals(17L, responseRef.get().getRuntimeState().getPublication().getVersionId()); @@ -1201,6 +1205,7 @@ void setAdmissionPointerAllowsAdminCaller() { 1L, 7L, 3L, + 1L, true, true, false, @@ -1262,6 +1267,7 @@ void setAdmissionPointerAllowsAdminCaller() { .setReason("cutover") .setControlPlaneRequestId("req-1") .setExpectedPointerVersion(2L) + .setExpectedCatalogRevision(1L) .setPreparedVersionUpgradeId("pvu-1") .build(), new NoopObserver<>() { @@ -1279,6 +1285,7 @@ public void onNext(SetAdmissionPointerResponse value) { Mockito.argThat( mutation -> Objects.equals(mutation.expectedPointerVersion(), 2L) + && Objects.equals(mutation.expectedCatalogRevision(), 1L) && Objects.equals(mutation.preparedVersionUpgradeId(), "pvu-1"))); } @@ -1338,6 +1345,7 @@ void setAdmissionPointerRejectsTargetChangeWithoutPreparedUpgrade() { .setReason("cutover") .setControlPlaneRequestId("req-1") .setExpectedPointerVersion(2L) + .setExpectedCatalogRevision(1L) .build(), new NoopObserver<>() { @Override @@ -1433,6 +1441,7 @@ void setAdmissionPointerRejectsStaleExpectedVersion() { .setReason("cutover") .setControlPlaneRequestId("req-2") .setExpectedPointerVersion(2L) + .setExpectedCatalogRevision(1L) .setPreparedVersionUpgradeId("pvu-1") .build(), new NoopObserver<>() { @@ -1480,6 +1489,7 @@ void setAdmissionPointerRejectsZeroGameInstanceId() { .setReason("cutover") .setControlPlaneRequestId("req-1") .setExpectedPointerVersion(2L) + .setExpectedCatalogRevision(1L) .build(), new NoopObserver<>() { @Override @@ -1535,6 +1545,7 @@ void executePreparedVersionCutoverSwapsPointerUsingPreparedProof() { 1L, 7L, 3L, + 1L, true, true, false, @@ -1591,6 +1602,7 @@ void executePreparedVersionCutoverSwapsPointerUsingPreparedProof() { .setReason("cutover") .setControlPlaneRequestId("req-1") .setExpectedPointerVersion(2L) + .setExpectedCatalogRevision(1L) .build(), new NoopObserver<>() { @Override @@ -1609,6 +1621,7 @@ public void onNext(ExecutePreparedVersionCutoverResponse value) { mutation -> Objects.equals(mutation.preparedVersionUpgradeId(), "pvu-1") && Objects.equals(mutation.expectedPointerVersion(), 2L) + && Objects.equals(mutation.expectedCatalogRevision(), 1L) && mutation.gameInstanceId() == 7L)); } @@ -1631,7 +1644,8 @@ void executePreparedVersionCutoverIsIdempotentAfterSameRequestAlreadyMovedPointe true, false, "SHARED", - "ALLOW_NEW"))); + "ALLOW_NEW", + 1L))); Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) .thenReturn( List.of( @@ -1643,6 +1657,7 @@ void executePreparedVersionCutoverIsIdempotentAfterSameRequestAlreadyMovedPointe 1L, 7L, 3L, + 1L, true, true, false, @@ -1699,6 +1714,7 @@ void executePreparedVersionCutoverIsIdempotentAfterSameRequestAlreadyMovedPointe .setReason("cutover") .setControlPlaneRequestId("req-1") .setExpectedPointerVersion(2L) + .setExpectedCatalogRevision(1L) .build(), new NoopObserver<>() { @Override @@ -1765,7 +1781,8 @@ void listAdmissionPointersFailsClosedWhenCurrentPointerHasNoAuditHistory() { true, false, "SHARED", - "ALLOW_NEW"))); + "ALLOW_NEW", + 2L))); Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")).thenReturn(List.of()); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = @@ -1793,6 +1810,75 @@ public void onNext(ListAdmissionPointersResponse value) { assertEquals(0, responseRef.get().getPointersCount()); } + @Test + void listAdmissionPointersUsesCurrentCatalogRevisionWhenLegacyAuditHasNone() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(authorityService.listPointers()) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 1L, + 7L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 6L))); + Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) + .thenReturn( + List.of( + new GameplayAdmissionPointerAuditEntry( + "demo", + "production", + "Demo World", + "Live Realm", + 1L, + 7L, + 3L, + null, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "legacy event", + "req-1", + null, + Instant.parse("2026-04-15T00:00:00Z")))); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + controlPlaneService( + Mockito.mock(GameInstanceRepository.class), + Mockito.mock(GameplayCommandRepository.class), + Mockito.mock(RuntimeRegionStatusRepository.class), + authorityService, + Mockito.mock(InstanceCutoverCompatibilityService.class), + Mockito.mock(VersionUpgradePreparationService.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + + AtomicReference responseRef = new AtomicReference<>(); + service.listAdmissionPointers( + ListAdmissionPointersRequest.getDefaultInstance(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertTrue(responseRef.get().getPointers(0).hasCatalogRevision()); + assertEquals(6L, responseRef.get().getPointers(0).getCatalogRevision()); + } + @Test void listAdmissionPointersReturnsInternalForUnrelatedIllegalStateFailure() { GameplayAdmissionPointerAuthorityService authorityService = @@ -1812,7 +1898,8 @@ void listAdmissionPointersReturnsInternalForUnrelatedIllegalStateFailure() { true, false, "SHARED", - "ALLOW_NEW"))); + "ALLOW_NEW", + 2L))); Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) .thenThrow(new IllegalStateException("audit store failed")); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); @@ -1856,6 +1943,7 @@ void listAdmissionPointerAuditReturnsEntriesForAdminCaller() { 1L, 7L, 3L, + 2L, true, true, false, @@ -1874,6 +1962,7 @@ void listAdmissionPointerAuditReturnsEntriesForAdminCaller() { 1L, 6L, 2L, + null, true, true, false, @@ -1914,6 +2003,8 @@ public void onNext(ListAdmissionPointerAuditResponse value) { assertEquals(2, responseRef.get().getAuditCount()); assertEquals("demo", responseRef.get().getAudit(0).getWorldSlug()); assertEquals(3L, responseRef.get().getAudit(0).getPointerVersion()); + assertEquals(2L, responseRef.get().getAudit(0).getCatalogRevision()); + assertFalse(responseRef.get().getAudit(1).hasCatalogRevision()); Mockito.verify(authorityService).listPointerAudit(1L, "demo", "production"); Mockito.verify(authorityService, Mockito.never()).listPointers(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 32a0621249..8aeebd69a1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -759,11 +759,11 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { new DatabaseGameplayAdmissionPointerAuthorityService(pointerRepository, eventRepository); GameplayAdmissionPointerSnapshot created = - authorityService.upsertPointer(pointerMutation(44L, true, 0L)); + authorityService.upsertPointer(pointerMutation(44L, true, 0L, 0L)); GameplayAdmissionPointerSnapshot policyChanged = - authorityService.upsertPointer(pointerMutation(44L, false, 1L)); + authorityService.upsertPointer(pointerMutation(44L, false, 1L, 1L)); GameplayAdmissionPointerSnapshot routeChanged = - authorityService.upsertPointer(pointerMutation(45L, false, 1L)); + authorityService.upsertPointer(pointerMutation(45L, false, 1L, 2L)); assertEquals(1L, created.catalogRevision()); assertEquals(1L, created.pointerVersion()); @@ -774,7 +774,10 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { } private static GameplayAdmissionPointerMutation pointerMutation( - long gameInstanceId, boolean publicProductionRealm, Long expectedPointerVersion) { + long gameInstanceId, + boolean publicProductionRealm, + Long expectedPointerVersion, + Long expectedCatalogRevision) { return new GameplayAdmissionPointerMutation( "demo", "Demo World", @@ -791,6 +794,7 @@ private static GameplayAdmissionPointerMutation pointerMutation( "catalog revision test", "catalog-revision-test-" + expectedPointerVersion, expectedPointerVersion, + expectedCatalogRevision, null); } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java index 1217c2c65f..3e04f1a0d4 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java @@ -60,7 +60,8 @@ public static List seedPlayers( GameplayCrossServiceStack.SYNTHETIC_LOAD_ACTOR, "Seed per-player load-test admission pointer", "load-test:" + accountId, - null, + 0L, + 0L, null)); long sessionId = firstAccountId + 10_000L + i + 1; String email = "player" + (i + 1) + "@example.com"; diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AdmissionPointerDto.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AdmissionPointerDto.java index d19975bd8c..4e9c216624 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AdmissionPointerDto.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AdmissionPointerDto.java @@ -10,6 +10,7 @@ public record AdmissionPointerDto( Long tenantId, Long gameInstanceId, long pointerVersion, + Long catalogRevision, boolean visible, boolean publicProductionRealm, boolean requiresCharacterSelection, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ExecutePreparedVersionCutoverRequest.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ExecutePreparedVersionCutoverRequest.java index 641163510d..d8f8e3aa41 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ExecutePreparedVersionCutoverRequest.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ExecutePreparedVersionCutoverRequest.java @@ -13,4 +13,5 @@ public record ExecutePreparedVersionCutoverRequest( @NotBlank @Size(max = 64) String preparedVersionUpgradeId, @Size(max = 255) String reason, @Size(max = 128) String controlPlaneRequestId, - Long expectedPointerVersion) {} + @NotNull @Positive Long expectedPointerVersion, + @NotNull @Positive Long expectedCatalogRevision) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/SetAdmissionPointerRequest.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/SetAdmissionPointerRequest.java index f27f22ac12..c35cc2eba8 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/SetAdmissionPointerRequest.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/SetAdmissionPointerRequest.java @@ -3,6 +3,7 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; +import jakarta.validation.constraints.PositiveOrZero; import jakarta.validation.constraints.Size; public record SetAdmissionPointerRequest( @@ -19,5 +20,6 @@ public record SetAdmissionPointerRequest( @NotBlank @Size(max = 50) String characterCreationPolicy, @Size(max = 255) String reason, @Size(max = 128) String controlPlaneRequestId, - Long expectedPointerVersion, + @NotNull @PositiveOrZero Long expectedPointerVersion, + @NotNull @PositiveOrZero Long expectedCatalogRevision, @Size(max = 64) String preparedVersionUpgradeId) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java index 89196cd3f5..5837a1245c 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java @@ -99,6 +99,9 @@ public AdmissionPointerDto setPointer(SetAdmissionPointerRequest request) { if (request.expectedPointerVersion() != null) { builder.setExpectedPointerVersion(request.expectedPointerVersion()); } + if (request.expectedCatalogRevision() != null) { + builder.setExpectedCatalogRevision(request.expectedCatalogRevision()); + } if (request.preparedVersionUpgradeId() != null && !request.preparedVersionUpgradeId().isBlank()) { builder.setPreparedVersionUpgradeId(request.preparedVersionUpgradeId()); @@ -137,6 +140,9 @@ public AdmissionPointerDto executePreparedVersionCutover( if (request.expectedPointerVersion() != null) { builder.setExpectedPointerVersion(request.expectedPointerVersion()); } + if (request.expectedCatalogRevision() != null) { + builder.setExpectedCatalogRevision(request.expectedCatalogRevision()); + } ExecutePreparedVersionCutoverResponse response = gameSessionControlPlaneClient.executePreparedVersionCutover(builder.build()); requireNoError(response.getError()); @@ -245,6 +251,7 @@ private AdmissionPointerDto toDto(AdmissionPointerControlPlaneEntry entry) { parseLong(entry.getTenantId(), "tenant_id"), parseLong(entry.getGameInstanceId(), "game_instance_id"), entry.getPointerVersion(), + entry.hasCatalogRevision() ? entry.getCatalogRevision() : null, entry.getVisible(), entry.getPublicProductionRealm(), entry.getRequiresCharacterSelection(), diff --git a/services/logging-admin-service/src/main/resources/openapi.yaml b/services/logging-admin-service/src/main/resources/openapi.yaml index 301a5cc89e..dc33be9af8 100644 --- a/services/logging-admin-service/src/main/resources/openapi.yaml +++ b/services/logging-admin-service/src/main/resources/openapi.yaml @@ -1242,6 +1242,9 @@ components: type: integer pointerVersion: type: integer + catalogRevision: + type: integer + nullable: true visible: type: boolean publicProductionRealm: diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java index d5d03bc7ec..e8f06c055a 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java @@ -61,6 +61,7 @@ void listPointersReturnsVisibleEntries() throws Exception { 2L, 7L, 3L, + 5L, true, true, false, @@ -77,7 +78,8 @@ void listPointersReturnsVisibleEntries() throws Exception { .perform(get("/admission-pointers").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.data[0].worldSlug").value("demo")) - .andExpect(jsonPath("$.data[0].tenantId").value(2)); + .andExpect(jsonPath("$.data[0].tenantId").value(2)) + .andExpect(jsonPath("$.data[0].catalogRevision").value(5)); } @Test @@ -93,6 +95,7 @@ void auditReturnsEntries() throws Exception { 2L, 7L, 3L, + 5L, true, true, false, @@ -111,7 +114,8 @@ void auditReturnsEntries() throws Exception { get("/admission-pointers/2/demo/production/audit") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) - .andExpect(jsonPath("$.data[0].pointerVersion").value(3)); + .andExpect(jsonPath("$.data[0].pointerVersion").value(3)) + .andExpect(jsonPath("$.data[0].catalogRevision").value(5)); } @Test @@ -304,6 +308,7 @@ private GameInstanceRuntimeStateDto runtimeStateDto() { 2L, 7L, 11L, + 7L, true, true, false, diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java index 07d93f5312..cab89dbc20 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java @@ -141,15 +141,18 @@ void setPointerUsesSessionAccountIdAsActorPrincipal() { "cutover", "req-1", 3L, + 4L, "pvu-1")); assertEquals(4L, result.pointerVersion()); + assertEquals(4L, result.catalogRevision()); verify(gameSessionControlPlaneClient) .setAdmissionPointer( org.mockito.ArgumentMatchers.argThat( request -> request.getActorPrincipal().equals("42") && request.getExpectedPointerVersion() == 3L + && request.getExpectedCatalogRevision() == 4L && request.getPreparedVersionUpgradeId().equals("pvu-1"))); } @@ -186,6 +189,7 @@ void setPointerMapsVersionMismatchToConflict() { "cutover", "req-1", 3L, + 4L, "pvu-1"))); assertEquals(409, ex.getStatusCode().value()); @@ -215,6 +219,7 @@ void setPointerRejectsMalformedCurrentAccountClaimBeforeMutation() { "cutover", "req-1", 3L, + 4L, "pvu-1"))); assertEquals(400, ex.getStatusCode().value()); @@ -233,16 +238,18 @@ void executePreparedVersionCutoverUsesSessionAccountIdAsActorPrincipal() { AdmissionPointerDto result = service.executePreparedVersionCutover( new ExecutePreparedVersionCutoverRequest( - "demo", "production", 2L, 7L, "pvu-1", "cutover", "req-1", 3L)); + "demo", "production", 2L, 7L, "pvu-1", "cutover", "req-1", 3L, 4L)); assertEquals(4L, result.pointerVersion()); + assertEquals(4L, result.catalogRevision()); verify(gameSessionControlPlaneClient) .executePreparedVersionCutover( org.mockito.ArgumentMatchers.argThat( request -> request.getActorPrincipal().equals("42") && request.getPreparedVersionUpgradeId().equals("pvu-1") - && request.getExpectedPointerVersion() == 3L)); + && request.getExpectedPointerVersion() == 3L + && request.getExpectedCatalogRevision() == 4L)); } @Test @@ -410,6 +417,7 @@ private AdmissionPointerControlPlaneEntry pointerEntry( .setTenantId(Long.toString(tenantId)) .setGameInstanceId(Long.toString(gameInstanceId)) .setPointerVersion(pointerVersion) + .setCatalogRevision(pointerVersion) .setVisible(true) .setRequiresCharacterSelection(false) .setStateScope("SHARED") From 94aa1965bb415815d97ba321d2b010a90a83abaf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 08:05:59 +1300 Subject: [PATCH 14/75] Keep admission pointer mutations fail closed before pair CAS --- ...onAdmissionPointerControlPlaneService.java | 29 +++- ...ameSessionControlPlaneGrpcServiceTest.java | 144 ++++-------------- 2 files changed, 54 insertions(+), 119 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java index 614b33e18c..4761a658bd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java @@ -3,6 +3,7 @@ import net.firedevops.firemud.gamesession.dto.PreparedVersionUpgradeDto; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; @@ -76,7 +77,26 @@ ListAdmissionPointerAuditResponse listAdmissionPointerAudit( SetAdmissionPointerResponse setAdmissionPointer( long tenantId, long targetGameInstanceId, SetAdmissionPointerRequest request) { - validatePreparedUpgradeForPointerChange(request, tenantId, targetGameInstanceId); + GameplayAdmissionPointerSnapshot currentPointer = + gameplayAdmissionPointerAuthorityService + .findPointer(tenantId, request.getWorldSlug(), request.getRealmSlug()) + .orElse(null); + if (currentPointer != null) { + throw new AdmissionPointerVersionMismatchException( + "admission-pointer updates are temporarily disabled until catalog revision " + + "preconditions are supported"); + } + if (!request.hasExpectedPointerVersion() || request.getExpectedPointerVersion() != 0L) { + throw new AdmissionPointerVersionMismatchException( + "new admission-pointer creation requires an explicit expected_pointer_version of 0"); + } + validatePreparedUpgradeForPointerChange( + request.getWorldSlug(), + request.getRealmSlug(), + tenantId, + targetGameInstanceId, + request.getPreparedVersionUpgradeId(), + currentPointer); gameplayAdmissionPointerAuthorityService.upsertPointer( new GameplayAdmissionPointerMutation( request.getWorldSlug(), @@ -107,6 +127,7 @@ ExecutePreparedVersionCutoverResponse executePreparedVersionCutover( requireText(request.getPreparedVersionUpgradeId(), "prepared_version_upgrade_id is required"); requireText(request.getActorPrincipal(), "actor_principal is required"); requireText(request.getControlPlaneRequestId(), "control_plane_request_id is required"); + rejectPreparedCutoverUntilCatalogRevisionPreconditionsAreSupported(); GameplayAdmissionPointerSnapshot currentPointer = gameplayAdmissionPointerAuthorityService .findPointer(tenantId, request.getWorldSlug(), request.getRealmSlug()) @@ -287,6 +308,12 @@ private AdmissionPointerControlPlaneEntry currentExecutedCutoverEntryIfSameReque return entry; } + private void rejectPreparedCutoverUntilCatalogRevisionPreconditionsAreSupported() { + throw new AdmissionPointerVersionMismatchException( + "prepared cutover is temporarily disabled until catalog revision preconditions " + + "are supported"); + } + private GameInstance getInstanceOrThrow(long gameInstanceId) { return gameInstanceRepository .findById(gameInstanceId) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 33d48d2244..399230d8e0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -42,7 +42,6 @@ import net.firedevops.firemud.gamesession.repository.RemoteFollowupResultRepository; import net.firedevops.firemud.gamesession.repository.RuntimeRegionStatusRepository; import net.firedevops.firemud.gamesession.repository.ScriptPinMutationResult; -import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; @@ -1163,7 +1162,7 @@ public void onNext(GetGameSessionPinConvergenceResponse value) { } @Test - void setAdmissionPointerAllowsAdminCaller() { + void setAdmissionPointerAllowsExplicitZeroCreationForAdminCaller() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); GameInstance targetInstance = runningGameInstance(); targetInstance.setId(7L); @@ -1175,21 +1174,7 @@ void setAdmissionPointerAllowsAdminCaller() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(authorityService.findPointer(1L, "demo", "production")) - .thenReturn( - Optional.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo World", - "production", - "Live Realm", - 1L, - 5L, - 2L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"))); + .thenReturn(Optional.empty()); Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) .thenReturn( List.of( @@ -1200,39 +1185,19 @@ void setAdmissionPointerAllowsAdminCaller() { "Live Realm", 1L, 7L, - 3L, + 1L, true, true, false, "SHARED", "ALLOW_NEW", "tester", - "cutover", + "initial create", "req-1", - "pvu-1", + null, Instant.parse("2026-04-15T00:00:00Z")))); VersionUpgradePreparationService versionUpgradePreparationService = Mockito.mock(VersionUpgradePreparationService.class); - Mockito.when(versionUpgradePreparationService.getPreparedVersionUpgrade(1L, "pvu-1")) - .thenReturn( - new net.firedevops.firemud.gamesession.dto.PreparedVersionUpgradeDto( - "pvu-1", - "prep-req-1", - 1L, - 5L, - 7L, - 9L, - "ld-9", - "remap-1", - "COMPATIBLE", - List.of(), - List.of("WORLD", "ENTITY"), - Instant.parse("2026-04-16T00:00:00Z"), - List.of(), - null, - null, - null, - null)); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( @@ -1259,10 +1224,9 @@ void setAdmissionPointerAllowsAdminCaller() { .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .setActorPrincipal("tester") - .setReason("cutover") + .setReason("initial create") .setControlPlaneRequestId("req-1") - .setExpectedPointerVersion(2L) - .setPreparedVersionUpgradeId("pvu-1") + .setExpectedPointerVersion(0L) .build(), new NoopObserver<>() { @Override @@ -1272,43 +1236,22 @@ public void onNext(SetAdmissionPointerResponse value) { }); assertEquals("demo", responseRef.get().getPointer().getWorldSlug()); - assertEquals(3L, responseRef.get().getPointer().getPointerVersion()); - assertEquals("pvu-1", responseRef.get().getPointer().getPreparedVersionUpgradeId()); + assertEquals(1L, responseRef.get().getPointer().getPointerVersion()); Mockito.verify(authorityService) .upsertPointer( Mockito.argThat( mutation -> - Objects.equals(mutation.expectedPointerVersion(), 2L) - && Objects.equals(mutation.preparedVersionUpgradeId(), "pvu-1"))); + Objects.equals(mutation.expectedPointerVersion(), 0L) + && mutation.preparedVersionUpgradeId().isBlank())); } @Test - void setAdmissionPointerRejectsTargetChangeWithoutPreparedUpgrade() { + void setAdmissionPointerRejectsCreateWithoutExplicitZeroVersion() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); - GameInstance targetInstance = runningGameInstance(); - targetInstance.setId(7L); - targetInstance.setTenantId(1L); - targetInstance.setVersionId(9L); - targetInstance.setLaunchDescriptorId("ld-9"); - Mockito.when(gameInstanceRepository.findById(7L)).thenReturn(Optional.of(targetInstance)); GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(authorityService.findPointer(1L, "demo", "production")) - .thenReturn( - Optional.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo World", - "production", - "Live Realm", - 1L, - 5L, - 2L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"))); + .thenReturn(Optional.empty()); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( @@ -1337,7 +1280,6 @@ void setAdmissionPointerRejectsTargetChangeWithoutPreparedUpgrade() { .setActorPrincipal("tester") .setReason("cutover") .setControlPlaneRequestId("req-1") - .setExpectedPointerVersion(2L) .build(), new NoopObserver<>() { @Override @@ -1346,12 +1288,13 @@ public void onNext(SetAdmissionPointerResponse value) { } }); - assertEquals("CUTOVER_PREPARATION_INVALID", responseRef.get().getError().getCode()); + assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); Mockito.verify(authorityService, Mockito.never()).upsertPointer(Mockito.any()); + Mockito.verifyNoInteractions(gameInstanceRepository); } @Test - void setAdmissionPointerRejectsStaleExpectedVersion() { + void setAdmissionPointerRejectsMutationOfExistingPointerUntilCatalogRevisionIsSupported() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); GameInstance targetInstance = runningGameInstance(); targetInstance.setId(7L); @@ -1378,32 +1321,8 @@ void setAdmissionPointerRejectsStaleExpectedVersion() { false, "SHARED", "ALLOW_NEW"))); - Mockito.when(authorityService.upsertPointer(Mockito.any())) - .thenThrow( - new AdmissionPointerVersionMismatchException( - "expected_pointer_version does not match current pointer version")); VersionUpgradePreparationService versionUpgradePreparationService = Mockito.mock(VersionUpgradePreparationService.class); - Mockito.when(versionUpgradePreparationService.getPreparedVersionUpgrade(1L, "pvu-1")) - .thenReturn( - new net.firedevops.firemud.gamesession.dto.PreparedVersionUpgradeDto( - "pvu-1", - "prep-req-1", - 1L, - 5L, - 7L, - 9L, - "ld-9", - "remap-1", - "COMPATIBLE", - List.of(), - List.of("WORLD", "ENTITY"), - Instant.parse("2026-04-16T00:00:00Z"), - List.of(), - null, - null, - null, - null)); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( @@ -1443,6 +1362,9 @@ public void onNext(SetAdmissionPointerResponse value) { }); assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); + Mockito.verify(authorityService, Mockito.never()).upsertPointer(Mockito.any()); + Mockito.verifyNoInteractions(gameInstanceRepository); + Mockito.verifyNoInteractions(versionUpgradePreparationService); } @Test @@ -1497,7 +1419,7 @@ public void onNext(SetAdmissionPointerResponse value) { } @Test - void executePreparedVersionCutoverSwapsPointerUsingPreparedProof() { + void executePreparedVersionCutoverFailsClosedUntilCatalogRevisionIsSupported() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); GameInstance targetInstance = runningGameInstance(); targetInstance.setId(7L); @@ -1599,17 +1521,10 @@ public void onNext(ExecutePreparedVersionCutoverResponse value) { } }); - assertEquals(3L, responseRef.get().getPointer().getPointerVersion()); - assertEquals("pvu-1", responseRef.get().getPointer().getPreparedVersionUpgradeId()); - Mockito.verify(versionUpgradePreparationService) - .markPreparedVersionUpgradeExecuted(1L, "pvu-1", 7L, 3L, "req-1"); - Mockito.verify(authorityService) - .upsertPointer( - Mockito.argThat( - mutation -> - Objects.equals(mutation.preparedVersionUpgradeId(), "pvu-1") - && Objects.equals(mutation.expectedPointerVersion(), 2L) - && mutation.gameInstanceId() == 7L)); + assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + Mockito.verifyNoInteractions(versionUpgradePreparationService); + Mockito.verifyNoInteractions(gameInstanceRepository); } @Test @@ -1707,16 +1622,9 @@ public void onNext(ExecutePreparedVersionCutoverResponse value) { } }); - assertEquals(3L, responseRef.get().getPointer().getPointerVersion()); - assertEquals("pvu-1", responseRef.get().getPointer().getPreparedVersionUpgradeId()); - Mockito.verify(authorityService, Mockito.never()).upsertPointer(Mockito.any()); - Mockito.verify(versionUpgradePreparationService, Mockito.never()) - .markPreparedVersionUpgradeExecuted( - Mockito.anyLong(), - Mockito.anyString(), - Mockito.anyLong(), - Mockito.anyLong(), - Mockito.anyString()); + assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + Mockito.verifyNoInteractions(versionUpgradePreparationService); } @Test From 5ed245db917e3ca6a6b65d2103c9caca44184c25 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 08:10:44 +1300 Subject: [PATCH 15/75] Clear front-stage static analysis and owned formatting --- ...ameSessionAdmissionPointerControlPlaneService.java | 8 +------- .../command/text/GameplayWorldCatalogTest.java | 7 ++++--- .../GameplayAdmissionPointerRepositoryTest.java | 11 +++-------- 3 files changed, 8 insertions(+), 18 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java index 4761a658bd..d082afc040 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java @@ -90,13 +90,7 @@ SetAdmissionPointerResponse setAdmissionPointer( throw new AdmissionPointerVersionMismatchException( "new admission-pointer creation requires an explicit expected_pointer_version of 0"); } - validatePreparedUpgradeForPointerChange( - request.getWorldSlug(), - request.getRealmSlug(), - tenantId, - targetGameInstanceId, - request.getPreparedVersionUpgradeId(), - currentPointer); + validatePreparedUpgradeForPointerChange(request, tenantId, targetGameInstanceId); gameplayAdmissionPointerAuthorityService.upsertPointer( new GameplayAdmissionPointerMutation( request.getWorldSlug(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 60dbe07f7a..3314b29263 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -169,8 +169,7 @@ void normalizeWorldsDropsRealmViewsWithoutSlugsBeforeAdmissionLookup() { @Test void authoritativePointerIdentityAndCatalogRevisionReachRealmView() { - java.util.UUID realmId = - java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"); + java.util.UUID realmId = java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"); java.util.UUID playableStateNamespaceId = java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412"); when(authorityService.listPointers()) @@ -195,7 +194,9 @@ void authoritativePointerIdentityAndCatalogRevisionReachRealmView() { GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); GameplayWorldCatalog.RealmView realm = - catalog.resolveRealm(catalog.resolveWorld("demo").orElseThrow(), "production").orElseThrow(); + catalog + .resolveRealm(catalog.resolveWorld("demo").orElseThrow(), "production") + .orElseThrow(); assertThat(realm.catalogRevision()).isEqualTo(29L); assertThat(realm.realmId()).isEqualTo(realmId); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index 113067382e..c38195a515 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -83,18 +83,13 @@ void catalogOnlyUpdatePreservesPointerVersionAndFencesStaleCatalogRevision() thr "jdbc:h2:mem:gameplay-pointer-catalog-cas;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { DSLContext dsl = DSL.using(connection, SQLDialect.H2); createSchema(dsl); - GameplayAdmissionPointerRepository repository = - new GameplayAdmissionPointerRepository(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); repository.save(pointer(7L, 44L, "SHARED", "production")); GameplayAdmissionPointer stale = - repository - .findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production") - .orElseThrow(); + repository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production").orElseThrow(); GameplayAdmissionPointer catalogUpdate = - repository - .findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production") - .orElseThrow(); + repository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production").orElseThrow(); catalogUpdate.setWorldDisplayName("Renamed Demo World"); catalogUpdate.setPointerVersion(1L); catalogUpdate.setCatalogRevision(2L); From b53b14faf27a80c725fe85dc2ea5f23ba2a34b6d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 08:12:04 +1300 Subject: [PATCH 16/75] Keep inherited exact-base client guard formatted --- .../firemud/gamesession/client/GameDesignClient.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java index 1396cfbd90..ca97ef1158 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java @@ -104,7 +104,8 @@ public GetPublishedScriptPatchVersionResponse getPublishedScriptPatchVersion( .setError( ErrorDetail.newBuilder() .setCode("INVALID_ARGUMENT") - .setMessage("base_version_id must be positive for script-patch publication lookup") + .setMessage( + "base_version_id must be positive for script-patch publication lookup") .build()) .build(); } From 6118508e421bcadd1be74411baca765445a9800e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 08:27:00 +1300 Subject: [PATCH 17/75] Keep catalog CAS child formatting stable --- .../firemud/gamesession/client/GameDesignClient.java | 3 ++- .../command/text/GameplayWorldCatalogTest.java | 7 ++++--- .../GameplayAdmissionPointerRepositoryTest.java | 11 +++-------- ...eGameplayAdmissionPointerAuthorityServiceTest.java | 3 +-- 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java index 1396cfbd90..ca97ef1158 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java @@ -104,7 +104,8 @@ public GetPublishedScriptPatchVersionResponse getPublishedScriptPatchVersion( .setError( ErrorDetail.newBuilder() .setCode("INVALID_ARGUMENT") - .setMessage("base_version_id must be positive for script-patch publication lookup") + .setMessage( + "base_version_id must be positive for script-patch publication lookup") .build()) .build(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 60dbe07f7a..3314b29263 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -169,8 +169,7 @@ void normalizeWorldsDropsRealmViewsWithoutSlugsBeforeAdmissionLookup() { @Test void authoritativePointerIdentityAndCatalogRevisionReachRealmView() { - java.util.UUID realmId = - java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"); + java.util.UUID realmId = java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"); java.util.UUID playableStateNamespaceId = java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412"); when(authorityService.listPointers()) @@ -195,7 +194,9 @@ void authoritativePointerIdentityAndCatalogRevisionReachRealmView() { GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); GameplayWorldCatalog.RealmView realm = - catalog.resolveRealm(catalog.resolveWorld("demo").orElseThrow(), "production").orElseThrow(); + catalog + .resolveRealm(catalog.resolveWorld("demo").orElseThrow(), "production") + .orElseThrow(); assertThat(realm.catalogRevision()).isEqualTo(29L); assertThat(realm.realmId()).isEqualTo(realmId); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index 113067382e..c38195a515 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -83,18 +83,13 @@ void catalogOnlyUpdatePreservesPointerVersionAndFencesStaleCatalogRevision() thr "jdbc:h2:mem:gameplay-pointer-catalog-cas;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { DSLContext dsl = DSL.using(connection, SQLDialect.H2); createSchema(dsl); - GameplayAdmissionPointerRepository repository = - new GameplayAdmissionPointerRepository(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); repository.save(pointer(7L, 44L, "SHARED", "production")); GameplayAdmissionPointer stale = - repository - .findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production") - .orElseThrow(); + repository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production").orElseThrow(); GameplayAdmissionPointer catalogUpdate = - repository - .findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production") - .orElseThrow(); + repository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production").orElseThrow(); catalogUpdate.setWorldDisplayName("Renamed Demo World"); catalogUpdate.setPointerVersion(1L); catalogUpdate.setCatalogRevision(2L); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index 698c7c2759..175cc4c55e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -299,8 +299,7 @@ void listPointerAuditExposesPersistedCatalogRevision() { .thenReturn(List.of(event)); assertEquals( - 2L, - service.listPointerAudit(1L, "demo", "production").getFirst().catalogRevision()); + 2L, service.listPointerAudit(1L, "demo", "production").getFirst().catalogRevision()); } @Test From 8b3a08df4fa2fb2a2b262ae62e2a8785fcccdd2f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 08:29:19 +1300 Subject: [PATCH 18/75] Compile catalog CAS integration proof --- .../websocket/GameSessionWebSocketHandlerIntegrationTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 0fc35c4d5f..2e83f690bd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -41,6 +41,7 @@ import net.firedevops.firemud.gamesession.service.CommandService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayPresence; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.SessionContextService; From 8ed5b4f5d007c3cd0569e62b526f25975bf4724d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 08:30:16 +1300 Subject: [PATCH 19/75] Format front-stage Account scope retention proof --- .../repository/AccountConnectScopeRepository.java | 6 +++--- .../service/ExpiredConnectScopeCleanupJob.java | 6 ++---- .../repository/AccountRepositoryIntegrationTest.java | 6 ++---- .../accountservice/service/impl/AccountGrpcServiceTest.java | 3 +-- 4 files changed, 8 insertions(+), 13 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java index 113107071e..de441fb2de 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java @@ -80,9 +80,9 @@ public Optional find(String connectScopeId) { } /** - * Deletes a bounded batch of expired scopes only when no JOIN receipt references them. - * Malformed expiry values are retained. The database FK from JOIN receipts is the concurrent - * insert fence for the anti-join predicate. + * Deletes a bounded batch of expired scopes only when no JOIN receipt references them. Malformed + * expiry values are retained. The database FK from JOIN receipts is the concurrent insert fence + * for the anti-join predicate. */ public int deleteExpiredUnreferenced(Instant capturedNow, int batchSize) { if (capturedNow == null) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java index 19b8f9bbff..7c2b4f22b1 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java @@ -59,12 +59,10 @@ public ExpiredConnectScopeCleanupJob( public void cleanupExpiredConnectScopes() { Instant capturedNow = Instant.now(); try { - deleted.increment( - connectScopeRepository.deleteExpiredUnreferenced(capturedNow, batchSize)); + deleted.increment(connectScopeRepository.deleteExpiredUnreferenced(capturedNow, batchSize)); } catch (RuntimeException ex) { failures.increment(); - logger.warn( - "Expired connect-scope cleanup step failed ({})", ex.getClass().getSimpleName()); + logger.warn("Expired connect-scope cleanup step failed ({})", ex.getClass().getSimpleName()); } } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index aaf88d6a5b..691527c0e3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -347,8 +347,7 @@ void expiredConnectScopeCleanupPreservesEveryReferencedStatusAndMalformedEvidenc insertJoinIntent(joinOperations, pending, "join-scope-pending"); insertJoinIntent(joinOperations, committed, "join-scope-committed"); insertJoinIntent(joinOperations, failed, "join-scope-failed"); - joinOperations.finish( - "join-scope-failed", "FAILED", "CONNECT_SCOPE_INVALID", null, null, null); + joinOperations.finish("join-scope-failed", "FAILED", "CONNECT_SCOPE_INVALID", null, null, null); joinOperations.bindPolicyEvidence( "join-scope-committed", AccountJoinDigest.request(committed, "scope-cleanup-committed-caller", true, 1L), @@ -378,8 +377,7 @@ void expiredConnectScopeCleanupPreservesEveryReferencedStatusAndMalformedEvidenc new ExpiredConnectScopeCleanupJob(scopes, meters, 100, 60_000); cleanupJob.cleanupExpiredConnectScopes(); - assertThat(meters.get("account.connect_scopes.cleanup.deleted").counter().count()) - .isEqualTo(1); + assertThat(meters.get("account.connect_scopes.cleanup.deleted").counter().count()).isEqualTo(1); assertThat(meters.get("account.connect_scopes.cleanup.failure").counter().count()).isZero(); assertThat(scopeCount(jdbc, unreferenced)).isZero(); assertThat(scopeCount(jdbc, pending)).isEqualTo(1); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 001edbf111..c64e116fc8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -325,8 +325,7 @@ void issueDirectTextConnectScopeRejectsBlankRequestIdBeforeServiceCall(String re GAME_SESSION_PEER, () -> service.issueDirectTextConnectScope( - validScopeRequest() - .toBuilder() + validScopeRequest().toBuilder() .setPlayerContext(validPlayerContext().toBuilder().setRequestId(requestId)) .build(), observer)); From 765e69667c204cbebba3778c565d2ffbf7d04965 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 08:51:05 +1300 Subject: [PATCH 20/75] Reject catalog pointers without durable identity --- .../command/text/GameplayWorldCatalog.java | 4 + .../text/GameplayWorldCatalogTest.java | 121 +++++++++++++++++- .../command/text/PlayCommandHandlerTest.java | 60 +++++++++ 3 files changed, 184 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 861fff6a18..25571db9ad 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -271,6 +271,10 @@ private static List toWorlds(List p private static boolean hasCompleteAuthorityPointer(GameplayAdmissionPointerSnapshot pointer) { return GameplayAdmissionPointerSnapshots.hasCompleteRoutingBundle(pointer) + && pointer.catalogRevision() > 0L + && pointer.realmId() != null + && pointer.playableStateNamespaceId() != null + && ("SHARED".equals(pointer.stateScope()) || "ISOLATED".equals(pointer.stateScope())) && pointer.characterCreationPolicy() != null && !pointer.characterCreationPolicy().isBlank(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 3314b29263..d26413a146 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -3,10 +3,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.UUID; +import java.util.stream.Stream; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; class GameplayWorldCatalogTest { @@ -76,6 +82,18 @@ void visibleWorldsDropIncompleteAuthorityPointers() { assertThat(catalog.resolveRuntimeTarget(1L, 11L)).isEmpty(); } + @ParameterizedTest(name = "authority projection rejects {0}") + @MethodSource("incompleteAuthorityPointers") + void visibleWorldsDropPointersWithoutCompleteCatalogIdentity( + String reason, GameplayAdmissionPointerSnapshot pointer) { + when(authorityService.listPointers()).thenReturn(List.of(pointer)); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isEmpty(); + assertThat(catalog.resolveRuntimeTarget(1L, 11L)).isEmpty(); + } + @Test void visibleWorldsDropPointersMissingCharacterCreationPolicy() { when(authorityService.listPointers()) @@ -252,6 +270,7 @@ private static GameplayAdmissionPointerSnapshot pointer( long gameInstanceId, long pointerVersion, boolean visible) { + UUID realmId = stableId("realm/" + tenantId + "/" + worldSlug + "/" + realmSlug); return new GameplayAdmissionPointerSnapshot( worldSlug, worldDisplayName, @@ -264,6 +283,106 @@ private static GameplayAdmissionPointerSnapshot pointer( "production".equals(realmSlug), false, "SHARED", - "ALLOW_NEW"); + "ALLOW_NEW", + 1L, + realmId, + stableId("namespace/" + realmId)); + } + + private static Stream incompleteAuthorityPointers() { + GameplayAdmissionPointerSnapshot complete = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 1L, + 11L, + 7L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + stableId("realm/demo/production"), + stableId("namespace/demo/production")); + return Stream.of( + Arguments.of( + "non-positive catalog revision", + copyAuthorityPointer( + complete, + 0L, + complete.realmId(), + complete.playableStateNamespaceId(), + complete.stateScope())), + Arguments.of( + "negative catalog revision", + copyAuthorityPointer( + complete, + -1L, + complete.realmId(), + complete.playableStateNamespaceId(), + complete.stateScope())), + Arguments.of( + "missing realm identity", + copyAuthorityPointer( + complete, + complete.catalogRevision(), + null, + complete.playableStateNamespaceId(), + complete.stateScope())), + Arguments.of( + "missing playable-state namespace", + copyAuthorityPointer( + complete, + complete.catalogRevision(), + complete.realmId(), + null, + complete.stateScope())), + Arguments.of( + "unknown playable-state scope", + copyAuthorityPointer( + complete, + complete.catalogRevision(), + complete.realmId(), + complete.playableStateNamespaceId(), + "UNKNOWN")), + Arguments.of( + "non-canonical playable-state scope", + copyAuthorityPointer( + complete, + complete.catalogRevision(), + complete.realmId(), + complete.playableStateNamespaceId(), + "shared"))); + } + + private static GameplayAdmissionPointerSnapshot copyAuthorityPointer( + GameplayAdmissionPointerSnapshot pointer, + long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId, + String stateScope) { + return new GameplayAdmissionPointerSnapshot( + pointer.worldSlug(), + pointer.worldDisplayName(), + pointer.realmSlug(), + pointer.realmDisplayName(), + pointer.tenantId(), + pointer.gameInstanceId(), + pointer.pointerVersion(), + pointer.visible(), + pointer.publicProductionRealm(), + pointer.requiresCharacterSelection(), + stateScope, + pointer.characterCreationPolicy(), + catalogRevision, + realmId, + playableStateNamespaceId); + } + + private static UUID stableId(String value) { + return UUID.nameUUIDFromBytes(value.getBytes(StandardCharsets.UTF_8)); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 6f9274fad8..4ccf288f87 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -24,6 +24,8 @@ import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; @@ -691,6 +693,64 @@ void unknownWorldReturnsSelectionGuidance() { assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); } + @Test + void playDoesNotAdmitV6QuarantinedPointerWithoutCatalogIdentity() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + when(authorityService.listPointers()) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 22L, + 11L, + 1L, + true, + true, + false, + "UNKNOWN_LEGACY_SCOPE", + "ALLOW_NEW", + 0L, + null, + null))); + GameplayWorldCatalog authorityBackedCatalog = new GameplayWorldCatalog(authorityService); + PlayCommandHandler authorityBackedHandler = + new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + authorityBackedCatalog, + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry); + SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult result = + authorityBackedHandler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "production"), "PLAY demo production")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + moderationPolicyClient, + sessionContextService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + @Test void sandboxWithoutCharacterReturnsSelectionRequired() { SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); From 4586c3c4095c62a5f4d5a50b6ef89fb1e19b838f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:02:59 +1300 Subject: [PATCH 21/75] Record durable realm and namespace identity in pointer audit --- .../v1/game_session_service.proto | 4 + .../entity/GameplayAdmissionPointerEvent.java | 3 + ...meplayAdmissionPointerEventRepository.java | 9 ++ .../GameplayAdmissionPointerAuditEntry.java | 3 + ...eplayAdmissionPointerAuthorityService.java | 4 + ...onAdmissionPointerControlPlaneService.java | 6 ++ .../V7__audit_gameplay_catalog_revision.sql | 6 +- ...yAdmissionPointerAuthorityServiceTest.java | 35 ++++++- ...ameSessionControlPlaneGrpcServiceTest.java | 96 +++++++++++++++++++ .../loggingadmin/dto/AdmissionPointerDto.java | 3 + .../impl/AdmissionPointerServiceImpl.java | 13 +++ .../src/main/resources/openapi.yaml | 8 ++ .../AdmissionPointerControllerTest.java | 19 +++- .../impl/AdmissionPointerServiceImplTest.java | 31 ++++++ 14 files changed, 235 insertions(+), 5 deletions(-) diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index af6f522d73..b745ca1c13 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -417,6 +417,10 @@ message AdmissionPointerControlPlaneEntry { string prepared_version_upgrade_id = 16; bool public_production_realm = 17; optional int64 catalog_revision = 18; + // Empty for historical audit rows that predate durable pointer identity. + string realm_id = 19; + // Empty for historical audit rows that predate durable pointer identity. + string playable_state_namespace_id = 20; } message ListAdmissionPointersRequest {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointerEvent.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointerEvent.java index 00a115379a..9656c1b7cf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointerEvent.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointerEvent.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.entity; import java.time.Instant; +import java.util.UUID; import lombok.Data; @Data @@ -14,6 +15,8 @@ public class GameplayAdmissionPointerEvent { private Long gameInstanceId; private Long pointerVersion; private Long catalogRevision; + private UUID realmId; + private UUID playableStateNamespaceId; private boolean visible; private boolean publicProductionRealm; private boolean requiresCharacterSelection; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java index 6b4f1a2928..276817318a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java @@ -70,6 +70,10 @@ public GameplayAdmissionPointerEvent save(GameplayAdmissionPointerEvent entity) .set(GAMEPLAY_ADMISSION_POINTER_EVENT.GAME_INSTANCE_ID, entity.getGameInstanceId()) .set(GAMEPLAY_ADMISSION_POINTER_EVENT.POINTER_VERSION, entity.getPointerVersion()) .set(GAMEPLAY_ADMISSION_POINTER_EVENT.CATALOG_REVISION, entity.getCatalogRevision()) + .set(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_ID, entity.getRealmId()) + .set( + GAMEPLAY_ADMISSION_POINTER_EVENT.PLAYABLE_STATE_NAMESPACE_ID, + entity.getPlayableStateNamespaceId()) .set(GAMEPLAY_ADMISSION_POINTER_EVENT.VISIBLE, entity.isVisible()) .set( GAMEPLAY_ADMISSION_POINTER_EVENT.PUBLIC_PRODUCTION_REALM, @@ -122,6 +126,8 @@ private void populate( record.setGameInstanceId(entity.getGameInstanceId()); record.setPointerVersion(entity.getPointerVersion()); record.setCatalogRevision(entity.getCatalogRevision()); + record.setRealmId(entity.getRealmId()); + record.setPlayableStateNamespaceId(entity.getPlayableStateNamespaceId()); record.setVisible(entity.isVisible()); record.setPublicProductionRealm(entity.isPublicProductionRealm()); record.setRequiresCharacterSelection(entity.isRequiresCharacterSelection()); @@ -145,6 +151,9 @@ private GameplayAdmissionPointerEvent toEntity(Record record) { entity.setGameInstanceId(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.GAME_INSTANCE_ID)); entity.setPointerVersion(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.POINTER_VERSION)); entity.setCatalogRevision(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.CATALOG_REVISION)); + entity.setRealmId(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_ID)); + entity.setPlayableStateNamespaceId( + record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.PLAYABLE_STATE_NAMESPACE_ID)); entity.setVisible(Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.VISIBLE))); entity.setPublicProductionRealm( Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.PUBLIC_PRODUCTION_REALM))); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuditEntry.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuditEntry.java index 8c8f3b4839..1375b51bfb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuditEntry.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuditEntry.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.service; import java.time.Instant; +import java.util.UUID; public record GameplayAdmissionPointerAuditEntry( String worldSlug, @@ -11,6 +12,8 @@ public record GameplayAdmissionPointerAuditEntry( long gameInstanceId, long pointerVersion, Long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId, boolean visible, boolean publicProductionRealm, boolean requiresCharacterSelection, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index 079c0ec271..66d1ca5287 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -127,6 +127,8 @@ && catalogPolicyMatches(pointer, mutation)) { event.setGameInstanceId(saved.getGameInstanceId()); event.setPointerVersion(saved.getPointerVersion()); event.setCatalogRevision(saved.getCatalogRevision()); + event.setRealmId(saved.getRealmId()); + event.setPlayableStateNamespaceId(saved.getPlayableStateNamespaceId()); event.setVisible(saved.isVisible()); event.setPublicProductionRealm(saved.isPublicProductionRealm()); event.setRequiresCharacterSelection(saved.isRequiresCharacterSelection()); @@ -160,6 +162,8 @@ public List listPointerAudit( event.getGameInstanceId(), event.getPointerVersion(), event.getCatalogRevision(), + event.getRealmId(), + event.getPlayableStateNamespaceId(), event.isVisible(), event.isPublicProductionRealm(), event.isRequiresCharacterSelection(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java index 1fa09446cd..038271ea93 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java @@ -196,6 +196,12 @@ private AdmissionPointerControlPlaneEntry toEntry(GameplayAdmissionPointerAuditE if (entry.catalogRevision() != null && entry.catalogRevision() > 0L) { builder.setCatalogRevision(entry.catalogRevision()); } + if (entry.realmId() != null) { + builder.setRealmId(entry.realmId().toString()); + } + if (entry.playableStateNamespaceId() != null) { + builder.setPlayableStateNamespaceId(entry.playableStateNamespaceId().toString()); + } if (!normalizeBlank(entry.preparedVersionUpgradeId()).isEmpty()) { builder.setPreparedVersionUpgradeId(entry.preparedVersionUpgradeId()); } diff --git a/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql b/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql index 9c8f7892ae..f310583acc 100644 --- a/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql +++ b/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql @@ -1,4 +1,8 @@ ALTER TABLE gameplay_admission_pointer_event ADD COLUMN catalog_revision bigint, + ADD COLUMN realm_id uuid, + ADD COLUMN playable_state_namespace_id uuid, ADD CONSTRAINT gameplay_admission_pointer_event_catalog_revision_positive - CHECK (catalog_revision IS NULL OR catalog_revision > 0); + CHECK (catalog_revision IS NULL OR catalog_revision > 0), + ADD CONSTRAINT gameplay_admission_pointer_event_identity_pair_complete + CHECK ((realm_id IS NULL) = (playable_state_namespace_id IS NULL)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index 175cc4c55e..57a720ce87 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; @@ -10,6 +11,7 @@ import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; @@ -140,6 +142,10 @@ void upsertPointerAllowsCreateWhenExpectedVersionPairIsZero() { ArgumentCaptor.forClass(GameplayAdmissionPointerEvent.class); verify(eventRepository).save(eventCaptor.capture()); assertEquals(1L, eventCaptor.getValue().getCatalogRevision()); + assertEquals(pointerCaptor.getValue().getRealmId(), eventCaptor.getValue().getRealmId()); + assertEquals( + pointerCaptor.getValue().getPlayableStateNamespaceId(), + eventCaptor.getValue().getPlayableStateNamespaceId()); } @Test @@ -291,6 +297,8 @@ void listPointerAuditExposesPersistedCatalogRevision() { event.setGameInstanceId(7L); event.setPointerVersion(1L); event.setCatalogRevision(2L); + event.setRealmId(UUID.fromString("11111111-1111-1111-1111-111111111111")); + event.setPlayableStateNamespaceId(UUID.fromString("22222222-2222-2222-2222-222222222222")); event.setStateScope("SHARED"); event.setCharacterCreationPolicy("ALLOW_NEW"); event.setOccurredAt(java.time.Instant.parse("2026-09-29T00:00:00Z")); @@ -298,8 +306,29 @@ void listPointerAuditExposesPersistedCatalogRevision() { 1L, "demo", "production")) .thenReturn(List.of(event)); - assertEquals( - 2L, service.listPointerAudit(1L, "demo", "production").getFirst().catalogRevision()); + var auditEntry = service.listPointerAudit(1L, "demo", "production").getFirst(); + assertEquals(2L, auditEntry.catalogRevision()); + assertEquals(event.getRealmId(), auditEntry.realmId()); + assertEquals(event.getPlayableStateNamespaceId(), auditEntry.playableStateNamespaceId()); + } + + @Test + void listPointerAuditLeavesHistoricalIdentityAbsent() { + GameplayAdmissionPointerEvent historicalEvent = new GameplayAdmissionPointerEvent(); + historicalEvent.setWorldSlug("demo"); + historicalEvent.setRealmSlug("production"); + historicalEvent.setTenantId(1L); + historicalEvent.setGameInstanceId(7L); + historicalEvent.setPointerVersion(1L); + historicalEvent.setCatalogRevision(1L); + when(eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc( + 1L, "demo", "production")) + .thenReturn(List.of(historicalEvent)); + + var auditEntry = service.listPointerAudit(1L, "demo", "production").getFirst(); + assertEquals(1L, auditEntry.catalogRevision()); + assertNull(auditEntry.realmId()); + assertNull(auditEntry.playableStateNamespaceId()); } @Test @@ -334,6 +363,8 @@ private static GameplayAdmissionPointer existingPointer() { pointer.setGameInstanceId(7L); pointer.setPointerVersion(1L); pointer.setCatalogRevision(1L); + pointer.setRealmId(UUID.fromString("11111111-1111-1111-1111-111111111111")); + pointer.setPlayableStateNamespaceId(UUID.fromString("22222222-2222-2222-2222-222222222222")); pointer.setVisible(true); pointer.setPublicProductionRealm(true); pointer.setRequiresCharacterSelection(false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 33a4ec009c..0598d233c5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -14,6 +14,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.automationscripting.v1.GetScriptPatchStatusResponse; @@ -1206,6 +1207,8 @@ void setAdmissionPointerAllowsAdminCaller() { 7L, 3L, 1L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), true, true, false, @@ -1546,6 +1549,8 @@ void executePreparedVersionCutoverSwapsPointerUsingPreparedProof() { 7L, 3L, 1L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), true, true, false, @@ -1658,6 +1663,8 @@ void executePreparedVersionCutoverIsIdempotentAfterSameRequestAlreadyMovedPointe 7L, 3L, 1L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), true, true, false, @@ -1843,6 +1850,8 @@ void listAdmissionPointersUsesCurrentCatalogRevisionWhenLegacyAuditHasNone() { 7L, 3L, null, + null, + null, true, true, false, @@ -1879,6 +1888,82 @@ public void onNext(ListAdmissionPointersResponse value) { assertEquals(6L, responseRef.get().getPointers(0).getCatalogRevision()); } + @Test + void listAdmissionPointersExposesDurableIdentityFromAuditEntry() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(authorityService.listPointers()) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 1L, + 7L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 6L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); + Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) + .thenReturn( + List.of( + new GameplayAdmissionPointerAuditEntry( + "demo", + "production", + "Demo World", + "Live Realm", + 1L, + 7L, + 3L, + 6L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "cutover", + "req-1", + null, + Instant.parse("2026-04-15T00:00:00Z")))); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + controlPlaneService( + Mockito.mock(GameInstanceRepository.class), + Mockito.mock(GameplayCommandRepository.class), + Mockito.mock(RuntimeRegionStatusRepository.class), + authorityService, + Mockito.mock(InstanceCutoverCompatibilityService.class), + Mockito.mock(VersionUpgradePreparationService.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + + AtomicReference responseRef = new AtomicReference<>(); + service.listAdmissionPointers( + ListAdmissionPointersRequest.getDefaultInstance(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals( + "11111111-1111-1111-1111-111111111111", responseRef.get().getPointers(0).getRealmId()); + assertEquals( + "22222222-2222-2222-2222-222222222222", + responseRef.get().getPointers(0).getPlayableStateNamespaceId()); + } + @Test void listAdmissionPointersReturnsInternalForUnrelatedIllegalStateFailure() { GameplayAdmissionPointerAuthorityService authorityService = @@ -1944,6 +2029,8 @@ void listAdmissionPointerAuditReturnsEntriesForAdminCaller() { 7L, 3L, 2L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), true, true, false, @@ -1963,6 +2050,8 @@ void listAdmissionPointerAuditReturnsEntriesForAdminCaller() { 6L, 2L, null, + null, + null, true, true, false, @@ -2004,7 +2093,14 @@ public void onNext(ListAdmissionPointerAuditResponse value) { assertEquals("demo", responseRef.get().getAudit(0).getWorldSlug()); assertEquals(3L, responseRef.get().getAudit(0).getPointerVersion()); assertEquals(2L, responseRef.get().getAudit(0).getCatalogRevision()); + assertEquals( + "11111111-1111-1111-1111-111111111111", responseRef.get().getAudit(0).getRealmId()); + assertEquals( + "22222222-2222-2222-2222-222222222222", + responseRef.get().getAudit(0).getPlayableStateNamespaceId()); assertFalse(responseRef.get().getAudit(1).hasCatalogRevision()); + assertTrue(responseRef.get().getAudit(1).getRealmId().isEmpty()); + assertTrue(responseRef.get().getAudit(1).getPlayableStateNamespaceId().isEmpty()); Mockito.verify(authorityService).listPointerAudit(1L, "demo", "production"); Mockito.verify(authorityService, Mockito.never()).listPointers(); } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AdmissionPointerDto.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AdmissionPointerDto.java index 4e9c216624..1c78b32457 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AdmissionPointerDto.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AdmissionPointerDto.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.loggingadmin.dto; import java.time.Instant; +import java.util.UUID; public record AdmissionPointerDto( String worldSlug, @@ -11,6 +12,8 @@ public record AdmissionPointerDto( Long gameInstanceId, long pointerVersion, Long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId, boolean visible, boolean publicProductionRealm, boolean requiresCharacterSelection, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java index 5837a1245c..46ec995462 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java @@ -252,6 +252,8 @@ private AdmissionPointerDto toDto(AdmissionPointerControlPlaneEntry entry) { parseLong(entry.getGameInstanceId(), "game_instance_id"), entry.getPointerVersion(), entry.hasCatalogRevision() ? entry.getCatalogRevision() : null, + parseOptionalUuid(entry.getRealmId(), "realm_id"), + parseOptionalUuid(entry.getPlayableStateNamespaceId(), "playable_state_namespace_id"), entry.getVisible(), entry.getPublicProductionRealm(), entry.getRequiresCharacterSelection(), @@ -264,6 +266,17 @@ private AdmissionPointerDto toDto(AdmissionPointerControlPlaneEntry entry) { entry.getOccurredAtMs() <= 0 ? null : Instant.ofEpochMilli(entry.getOccurredAtMs())); } + private UUID parseOptionalUuid(String value, String fieldName) { + if (value == null || value.isBlank()) { + return null; + } + try { + return UUID.fromString(value); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException(fieldName + " must be a UUID", ex); + } + } + private PreparedVersionUpgradeDto toDto(PreparedVersionUpgrade preparation) { return new PreparedVersionUpgradeDto( preparation.getPreparationId(), diff --git a/services/logging-admin-service/src/main/resources/openapi.yaml b/services/logging-admin-service/src/main/resources/openapi.yaml index dc33be9af8..6d9d52fb39 100644 --- a/services/logging-admin-service/src/main/resources/openapi.yaml +++ b/services/logging-admin-service/src/main/resources/openapi.yaml @@ -1245,6 +1245,14 @@ components: catalogRevision: type: integer nullable: true + realmId: + type: string + format: uuid + nullable: true + playableStateNamespaceId: + type: string + format: uuid + nullable: true visible: type: boolean publicProductionRealm: diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java index e8f06c055a..80f1ecd48a 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java @@ -9,6 +9,7 @@ import java.time.Instant; import java.util.List; import java.util.Map; +import java.util.UUID; import net.firedevops.firemud.common.GlobalExceptionHandler; import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; import net.firedevops.firemud.common.config.CommonSecurityServletAutoConfiguration; @@ -62,6 +63,8 @@ void listPointersReturnsVisibleEntries() throws Exception { 7L, 3L, 5L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), true, true, false, @@ -79,7 +82,11 @@ void listPointersReturnsVisibleEntries() throws Exception { .andExpect(status().isOk()) .andExpect(jsonPath("$.data[0].worldSlug").value("demo")) .andExpect(jsonPath("$.data[0].tenantId").value(2)) - .andExpect(jsonPath("$.data[0].catalogRevision").value(5)); + .andExpect(jsonPath("$.data[0].catalogRevision").value(5)) + .andExpect(jsonPath("$.data[0].realmId").value("11111111-1111-1111-1111-111111111111")) + .andExpect( + jsonPath("$.data[0].playableStateNamespaceId") + .value("22222222-2222-2222-2222-222222222222")); } @Test @@ -96,6 +103,8 @@ void auditReturnsEntries() throws Exception { 7L, 3L, 5L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), true, true, false, @@ -115,7 +124,11 @@ void auditReturnsEntries() throws Exception { .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.data[0].pointerVersion").value(3)) - .andExpect(jsonPath("$.data[0].catalogRevision").value(5)); + .andExpect(jsonPath("$.data[0].catalogRevision").value(5)) + .andExpect(jsonPath("$.data[0].realmId").value("11111111-1111-1111-1111-111111111111")) + .andExpect( + jsonPath("$.data[0].playableStateNamespaceId") + .value("22222222-2222-2222-2222-222222222222")); } @Test @@ -309,6 +322,8 @@ private GameInstanceRuntimeStateDto runtimeStateDto() { 7L, 11L, 7L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), true, true, false, diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java index cab89dbc20..2667612522 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.loggingadmin.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; @@ -96,6 +97,34 @@ void listPointerAuditUsesCanonicalTenantKey() { assertEquals(1, result.size()); assertEquals(2L, result.get(0).tenantId()); + assertEquals( + java.util.UUID.fromString("11111111-1111-1111-1111-111111111111"), result.get(0).realmId()); + assertEquals( + java.util.UUID.fromString("22222222-2222-2222-2222-222222222222"), + result.get(0).playableStateNamespaceId()); + } + + @Test + void listPointerAuditLeavesHistoricalIdentityAbsent() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + when(gameSessionControlPlaneClient.listAdmissionPointerAudit(2L, "sandbox", "preview")) + .thenReturn( + ListAdmissionPointerAuditResponse.newBuilder() + .addAudit( + AdmissionPointerControlPlaneEntry.newBuilder() + .setWorldSlug("sandbox") + .setRealmSlug("preview") + .setTenantId("2") + .setGameInstanceId("11") + .setPointerVersion(4L) + .setCatalogRevision(4L) + .build()) + .build()); + + AdmissionPointerDto result = service.listPointerAudit(2L, "sandbox", "preview").getFirst(); + + assertNull(result.realmId()); + assertNull(result.playableStateNamespaceId()); } @Test @@ -418,6 +447,8 @@ private AdmissionPointerControlPlaneEntry pointerEntry( .setGameInstanceId(Long.toString(gameInstanceId)) .setPointerVersion(pointerVersion) .setCatalogRevision(pointerVersion) + .setRealmId("11111111-1111-1111-1111-111111111111") + .setPlayableStateNamespaceId("22222222-2222-2222-2222-222222222222") .setVisible(true) .setRequiresCharacterSelection(false) .setStateScope("SHARED") From 11bea5f07d2a7b812e85030a32d0aaa6dc18bed9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:08:42 +1300 Subject: [PATCH 22/75] Keep front-stage pointer writes closed pending complete audit --- ...yAdmissionPointerBootstrapInitializer.java | 2 - ...onAdmissionPointerControlPlaneService.java | 5 +++ ...issionPointerBootstrapInitializerTest.java | 8 ++++ ...ameSessionControlPlaneGrpcServiceTest.java | 45 +++---------------- 4 files changed, 18 insertions(+), 42 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java index d71a6d4518..74a539c686 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java @@ -8,14 +8,12 @@ import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; /** * Bootstraps the persisted gameplay admission-pointer authority from configuration only when the * authority store is empty. */ -@Component @RequiredArgsConstructor @ConditionalOnProperty( prefix = "firemud.database", diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java index d082afc040..1c020a2e8a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java @@ -86,6 +86,11 @@ SetAdmissionPointerResponse setAdmissionPointer( "admission-pointer updates are temporarily disabled until catalog revision " + "preconditions are supported"); } + if (currentPointer == null) { + throw new AdmissionPointerVersionMismatchException( + "admission-pointer creation is temporarily disabled until catalog revision and " + + "stable realm/namespace identity preconditions are supported"); + } if (!request.hasExpectedPointerVersion() || request.getExpectedPointerVersion() != 0L) { throw new AdmissionPointerVersionMismatchException( "new admission-pointer creation requires an explicit expected_pointer_version of 0"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index 732b5c72a5..8fa1a0d4e2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.data; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -18,6 +19,7 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.stereotype.Component; @ExtendWith(MockitoExtension.class) class GameplayAdmissionPointerBootstrapInitializerTest { @@ -111,6 +113,12 @@ void runDefaultsNullEnumFieldsDuringBootstrapMutation() throws Exception { assertEquals("ALLOW_NEW", mutationCaptor.getValue().characterCreationPolicy()); } + @Test + void initializerIsNotRegisteredAsSpringComponent() { + assertFalse( + GameplayAdmissionPointerBootstrapInitializer.class.isAnnotationPresent(Component.class)); + } + private static GameplayAdmissionPointerBootstrapProperties.PointerSeed pointerSeed( String worldSlug, String worldDisplayName, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 399230d8e0..3cfea47372 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -1162,42 +1162,12 @@ public void onNext(GetGameSessionPinConvergenceResponse value) { } @Test - void setAdmissionPointerAllowsExplicitZeroCreationForAdminCaller() { + void setAdmissionPointerRejectsInitialCreationUntilCatalogIdentityIsSupported() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); - GameInstance targetInstance = runningGameInstance(); - targetInstance.setId(7L); - targetInstance.setTenantId(1L); - targetInstance.setVersionId(9L); - targetInstance.setLaunchDescriptorId("ld-9"); - targetInstance.setRemapSetId("remap-1"); - Mockito.when(gameInstanceRepository.findById(7L)).thenReturn(Optional.of(targetInstance)); GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(authorityService.findPointer(1L, "demo", "production")) .thenReturn(Optional.empty()); - Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) - .thenReturn( - List.of( - new GameplayAdmissionPointerAuditEntry( - "demo", - "production", - "Demo World", - "Live Realm", - 1L, - 7L, - 1L, - true, - true, - false, - "SHARED", - "ALLOW_NEW", - "tester", - "initial create", - "req-1", - null, - Instant.parse("2026-04-15T00:00:00Z")))); - VersionUpgradePreparationService versionUpgradePreparationService = - Mockito.mock(VersionUpgradePreparationService.class); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( @@ -1206,7 +1176,7 @@ void setAdmissionPointerAllowsExplicitZeroCreationForAdminCaller() { Mockito.mock(RuntimeRegionStatusRepository.class), authorityService, Mockito.mock(InstanceCutoverCompatibilityService.class), - versionUpgradePreparationService, + Mockito.mock(VersionUpgradePreparationService.class), Mockito.mock(TickService.class), new SimpleMeterRegistry()); @@ -1235,14 +1205,9 @@ public void onNext(SetAdmissionPointerResponse value) { } }); - assertEquals("demo", responseRef.get().getPointer().getWorldSlug()); - assertEquals(1L, responseRef.get().getPointer().getPointerVersion()); - Mockito.verify(authorityService) - .upsertPointer( - Mockito.argThat( - mutation -> - Objects.equals(mutation.expectedPointerVersion(), 0L) - && mutation.preparedVersionUpgradeId().isBlank())); + assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); + Mockito.verify(authorityService, Mockito.never()).upsertPointer(Mockito.any()); + Mockito.verifyNoInteractions(gameInstanceRepository); } @Test From 0dfa86ba6a1745a5c8992cf549996d3e99127283 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:09:30 +1300 Subject: [PATCH 23/75] Keep pointer mutation RPCs closed until owner proof converges --- ...onAdmissionPointerControlPlaneService.java | 9 ++ ...ameSessionControlPlaneGrpcServiceTest.java | 137 ++++-------------- 2 files changed, 36 insertions(+), 110 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java index 038271ea93..f93363e514 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java @@ -3,6 +3,7 @@ import net.firedevops.firemud.gamesession.dto.PreparedVersionUpgradeDto; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; @@ -76,6 +77,7 @@ ListAdmissionPointerAuditResponse listAdmissionPointerAudit( SetAdmissionPointerResponse setAdmissionPointer( long tenantId, long targetGameInstanceId, SetAdmissionPointerRequest request) { + rejectAdmissionPointerMutationsUntilOwnerContractsAreSupported(); validatePreparedUpgradeForPointerChange(request, tenantId, targetGameInstanceId); gameplayAdmissionPointerAuthorityService.upsertPointer( new GameplayAdmissionPointerMutation( @@ -108,6 +110,7 @@ ExecutePreparedVersionCutoverResponse executePreparedVersionCutover( requireText(request.getPreparedVersionUpgradeId(), "prepared_version_upgrade_id is required"); requireText(request.getActorPrincipal(), "actor_principal is required"); requireText(request.getControlPlaneRequestId(), "control_plane_request_id is required"); + rejectAdmissionPointerMutationsUntilOwnerContractsAreSupported(); GameplayAdmissionPointerSnapshot currentPointer = gameplayAdmissionPointerAuthorityService .findPointer(tenantId, request.getWorldSlug(), request.getRealmSlug()) @@ -303,6 +306,12 @@ private AdmissionPointerControlPlaneEntry currentExecutedCutoverEntryIfSameReque return entry; } + private void rejectAdmissionPointerMutationsUntilOwnerContractsAreSupported() { + throw new AdmissionPointerVersionMismatchException( + "admission-pointer mutations are temporarily disabled until owner hold, drain, and " + + "durable execution contracts are supported"); + } + private GameInstance getInstanceOrThrow(long gameInstanceId) { return gameInstanceRepository .findById(gameInstanceId) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 0598d233c5..65bcb0218d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -43,7 +43,6 @@ import net.firedevops.firemud.gamesession.repository.RemoteFollowupResultRepository; import net.firedevops.firemud.gamesession.repository.RuntimeRegionStatusRepository; import net.firedevops.firemud.gamesession.repository.ScriptPinMutationResult; -import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; @@ -1168,7 +1167,7 @@ public void onNext(GetGameSessionPinConvergenceResponse value) { } @Test - void setAdmissionPointerAllowsAdminCaller() { + void setAdmissionPointerRejectsInitialCreateUntilOwnerContractsAreSupported() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); GameInstance targetInstance = runningGameInstance(); targetInstance.setId(7L); @@ -1180,67 +1179,9 @@ void setAdmissionPointerAllowsAdminCaller() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(authorityService.findPointer(1L, "demo", "production")) - .thenReturn( - Optional.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo World", - "production", - "Live Realm", - 1L, - 5L, - 2L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"))); - Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) - .thenReturn( - List.of( - new GameplayAdmissionPointerAuditEntry( - "demo", - "production", - "Demo World", - "Live Realm", - 1L, - 7L, - 3L, - 1L, - UUID.fromString("11111111-1111-1111-1111-111111111111"), - UUID.fromString("22222222-2222-2222-2222-222222222222"), - true, - true, - false, - "SHARED", - "ALLOW_NEW", - "tester", - "cutover", - "req-1", - "pvu-1", - Instant.parse("2026-04-15T00:00:00Z")))); + .thenReturn(Optional.empty()); VersionUpgradePreparationService versionUpgradePreparationService = Mockito.mock(VersionUpgradePreparationService.class); - Mockito.when(versionUpgradePreparationService.getPreparedVersionUpgrade(1L, "pvu-1")) - .thenReturn( - new net.firedevops.firemud.gamesession.dto.PreparedVersionUpgradeDto( - "pvu-1", - "prep-req-1", - 1L, - 5L, - 7L, - 9L, - "ld-9", - "remap-1", - "COMPATIBLE", - List.of(), - List.of("WORLD", "ENTITY"), - Instant.parse("2026-04-16T00:00:00Z"), - List.of(), - null, - null, - null, - null)); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( @@ -1267,11 +1208,9 @@ void setAdmissionPointerAllowsAdminCaller() { .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .setActorPrincipal("tester") - .setReason("cutover") + .setReason("initial create") .setControlPlaneRequestId("req-1") - .setExpectedPointerVersion(2L) - .setExpectedCatalogRevision(1L) - .setPreparedVersionUpgradeId("pvu-1") + .setExpectedPointerVersion(0L) .build(), new NoopObserver<>() { @Override @@ -1280,20 +1219,14 @@ public void onNext(SetAdmissionPointerResponse value) { } }); - assertEquals("demo", responseRef.get().getPointer().getWorldSlug()); - assertEquals(3L, responseRef.get().getPointer().getPointerVersion()); - assertEquals("pvu-1", responseRef.get().getPointer().getPreparedVersionUpgradeId()); - Mockito.verify(authorityService) - .upsertPointer( - Mockito.argThat( - mutation -> - Objects.equals(mutation.expectedPointerVersion(), 2L) - && Objects.equals(mutation.expectedCatalogRevision(), 1L) - && Objects.equals(mutation.preparedVersionUpgradeId(), "pvu-1"))); + assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + Mockito.verifyNoInteractions(gameInstanceRepository); + Mockito.verifyNoInteractions(versionUpgradePreparationService); } @Test - void setAdmissionPointerRejectsTargetChangeWithoutPreparedUpgrade() { + void setAdmissionPointerRejectsExistingTargetMetadataEditUntilOwnerContractsAreSupported() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); GameInstance targetInstance = runningGameInstance(); targetInstance.setId(7L); @@ -1335,20 +1268,19 @@ void setAdmissionPointerRejectsTargetChangeWithoutPreparedUpgrade() { service.setAdmissionPointer( SetAdmissionPointerRequest.newBuilder() .setWorldSlug("demo") - .setWorldDisplayName("Demo World") + .setWorldDisplayName("Renamed Demo World") .setRealmSlug("production") .setRealmDisplayName("Live Realm") .setTenantId("1") - .setGameInstanceId("7") + .setGameInstanceId("5") .setVisible(true) .setRequiresCharacterSelection(false) .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .setActorPrincipal("tester") - .setReason("cutover") + .setReason("metadata edit") .setControlPlaneRequestId("req-1") .setExpectedPointerVersion(2L) - .setExpectedCatalogRevision(1L) .build(), new NoopObserver<>() { @Override @@ -1357,12 +1289,13 @@ public void onNext(SetAdmissionPointerResponse value) { } }); - assertEquals("CUTOVER_PREPARATION_INVALID", responseRef.get().getError().getCode()); + assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); Mockito.verify(authorityService, Mockito.never()).upsertPointer(Mockito.any()); + Mockito.verifyNoInteractions(gameInstanceRepository); } @Test - void setAdmissionPointerRejectsStaleExpectedVersion() { + void setAdmissionPointerRejectsExistingTargetMoveUntilOwnerContractsAreSupported() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); GameInstance targetInstance = runningGameInstance(); targetInstance.setId(7L); @@ -1389,10 +1322,6 @@ void setAdmissionPointerRejectsStaleExpectedVersion() { false, "SHARED", "ALLOW_NEW"))); - Mockito.when(authorityService.upsertPointer(Mockito.any())) - .thenThrow( - new AdmissionPointerVersionMismatchException( - "expected_pointer_version does not match current pointer version")); VersionUpgradePreparationService versionUpgradePreparationService = Mockito.mock(VersionUpgradePreparationService.class); Mockito.when(versionUpgradePreparationService.getPreparedVersionUpgrade(1L, "pvu-1")) @@ -1455,6 +1384,9 @@ public void onNext(SetAdmissionPointerResponse value) { }); assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); + Mockito.verify(authorityService, Mockito.never()).upsertPointer(Mockito.any()); + Mockito.verifyNoInteractions(gameInstanceRepository); + Mockito.verifyNoInteractions(versionUpgradePreparationService); } @Test @@ -1510,7 +1442,7 @@ public void onNext(SetAdmissionPointerResponse value) { } @Test - void executePreparedVersionCutoverSwapsPointerUsingPreparedProof() { + void executePreparedVersionCutoverFailsClosedBeforeAuthorityMutation() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); GameInstance targetInstance = runningGameInstance(); targetInstance.setId(7L); @@ -1616,22 +1548,14 @@ public void onNext(ExecutePreparedVersionCutoverResponse value) { } }); - assertEquals(3L, responseRef.get().getPointer().getPointerVersion()); - assertEquals("pvu-1", responseRef.get().getPointer().getPreparedVersionUpgradeId()); - Mockito.verify(versionUpgradePreparationService) - .markPreparedVersionUpgradeExecuted(1L, "pvu-1", 7L, 3L, "req-1"); - Mockito.verify(authorityService) - .upsertPointer( - Mockito.argThat( - mutation -> - Objects.equals(mutation.preparedVersionUpgradeId(), "pvu-1") - && Objects.equals(mutation.expectedPointerVersion(), 2L) - && Objects.equals(mutation.expectedCatalogRevision(), 1L) - && mutation.gameInstanceId() == 7L)); + assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + Mockito.verifyNoInteractions(versionUpgradePreparationService); + Mockito.verifyNoInteractions(gameInstanceRepository); } @Test - void executePreparedVersionCutoverIsIdempotentAfterSameRequestAlreadyMovedPointer() { + void executePreparedVersionCutoverDoesNotMarkPreparedExecutionWhenDisabled() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(authorityService.findPointer(1L, "demo", "production")) @@ -1730,16 +1654,9 @@ public void onNext(ExecutePreparedVersionCutoverResponse value) { } }); - assertEquals(3L, responseRef.get().getPointer().getPointerVersion()); - assertEquals("pvu-1", responseRef.get().getPointer().getPreparedVersionUpgradeId()); - Mockito.verify(authorityService, Mockito.never()).upsertPointer(Mockito.any()); - Mockito.verify(versionUpgradePreparationService, Mockito.never()) - .markPreparedVersionUpgradeExecuted( - Mockito.anyLong(), - Mockito.anyString(), - Mockito.anyLong(), - Mockito.anyLong(), - Mockito.anyString()); + assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + Mockito.verifyNoInteractions(versionUpgradePreparationService); } @Test From 6a18e704bdebab97c606e10ce72e8f4721af4510 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:15:26 +1300 Subject: [PATCH 24/75] Fail closed on mismatched admission pointer audit readback --- ...onAdmissionPointerControlPlaneService.java | 39 +++++++- ...ameSessionControlPlaneGrpcServiceTest.java | 88 +++++++++++++++++-- 2 files changed, 117 insertions(+), 10 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java index f93363e514..a2f575f845 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.service.impl; +import java.util.Objects; import net.firedevops.firemud.gamesession.dto.PreparedVersionUpgradeDto; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; @@ -53,7 +54,17 @@ ListAdmissionPointersResponse listAdmissionPointers() { + "/" + pointer.realmSlug()); } - return toEntry(audit.getFirst(), pointer.catalogRevision()); + GameplayAdmissionPointerAuditEntry latestAudit = audit.getFirst(); + if (!matchesCurrentPointer(pointer, latestAudit)) { + throw new AdmissionPointerAuditUnavailableException( + "Admission pointer audit does not match current pointer " + + pointer.tenantId() + + ":" + + pointer.worldSlug() + + "/" + + pointer.realmSlug()); + } + return toEntry(latestAudit); }) .toList(); return ListAdmissionPointersResponse.newBuilder().addAllPointers(entries).build(); @@ -211,9 +222,29 @@ private AdmissionPointerControlPlaneEntry toEntry(GameplayAdmissionPointerAuditE return builder.build(); } - private AdmissionPointerControlPlaneEntry toEntry( - GameplayAdmissionPointerAuditEntry entry, long currentCatalogRevision) { - return toEntry(entry).toBuilder().setCatalogRevision(currentCatalogRevision).build(); + private static boolean matchesCurrentPointer( + GameplayAdmissionPointerSnapshot pointer, GameplayAdmissionPointerAuditEntry audit) { + return audit != null + && Objects.equals(pointer.worldSlug(), audit.worldSlug()) + && Objects.equals(pointer.worldDisplayName(), audit.worldDisplayName()) + && Objects.equals(pointer.realmSlug(), audit.realmSlug()) + && Objects.equals(pointer.realmDisplayName(), audit.realmDisplayName()) + && pointer.tenantId() == audit.tenantId() + && pointer.gameInstanceId() == audit.gameInstanceId() + && pointer.pointerVersion() == audit.pointerVersion() + && pointer.catalogRevision() > 0L + && audit.catalogRevision() != null + && audit.catalogRevision() > 0L + && pointer.catalogRevision() == audit.catalogRevision() + && pointer.realmId() != null + && pointer.realmId().equals(audit.realmId()) + && pointer.playableStateNamespaceId() != null + && pointer.playableStateNamespaceId().equals(audit.playableStateNamespaceId()) + && pointer.visible() == audit.visible() + && pointer.publicProductionRealm() == audit.publicProductionRealm() + && pointer.requiresCharacterSelection() == audit.requiresCharacterSelection() + && Objects.equals(pointer.stateScope(), audit.stateScope()) + && Objects.equals(pointer.characterCreationPolicy(), audit.characterCreationPolicy()); } private void validatePreparedUpgradeForPointerChange( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index f875aae32b..77b0f1133e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -1728,7 +1728,7 @@ public void onNext(ListAdmissionPointersResponse value) { } @Test - void listAdmissionPointersUsesCurrentCatalogRevisionWhenLegacyAuditHasNone() { + void listAdmissionPointersFailsClosedWhenLatestAuditHasNoCatalogRevision() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(authorityService.listPointers()) @@ -1747,7 +1747,9 @@ void listAdmissionPointersUsesCurrentCatalogRevisionWhenLegacyAuditHasNone() { false, "SHARED", "ALLOW_NEW", - 6L))); + 6L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) .thenReturn( List.of( @@ -1760,8 +1762,8 @@ void listAdmissionPointersUsesCurrentCatalogRevisionWhenLegacyAuditHasNone() { 7L, 3L, null, - null, - null, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), true, true, false, @@ -1794,8 +1796,81 @@ public void onNext(ListAdmissionPointersResponse value) { } }); - assertTrue(responseRef.get().getPointers(0).hasCatalogRevision()); - assertEquals(6L, responseRef.get().getPointers(0).getCatalogRevision()); + assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); + assertEquals(0, responseRef.get().getPointersCount()); + } + + @Test + void listAdmissionPointersFailsClosedWhenLatestAuditDoesNotMatchCurrentPointer() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(authorityService.listPointers()) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 1L, + 7L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 6L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); + Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) + .thenReturn( + List.of( + new GameplayAdmissionPointerAuditEntry( + "demo", + "production", + "Demo World", + "Live Realm", + 1L, + 6L, + 2L, + 5L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "historical event", + "req-0", + null, + Instant.parse("2026-04-14T00:00:00Z")))); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + controlPlaneService( + Mockito.mock(GameInstanceRepository.class), + Mockito.mock(GameplayCommandRepository.class), + Mockito.mock(RuntimeRegionStatusRepository.class), + authorityService, + Mockito.mock(InstanceCutoverCompatibilityService.class), + Mockito.mock(VersionUpgradePreparationService.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + + AtomicReference responseRef = new AtomicReference<>(); + service.listAdmissionPointers( + ListAdmissionPointersRequest.getDefaultInstance(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); + assertEquals(0, responseRef.get().getPointersCount()); } @Test @@ -1872,6 +1947,7 @@ public void onNext(ListAdmissionPointersResponse value) { assertEquals( "22222222-2222-2222-2222-222222222222", responseRef.get().getPointers(0).getPlayableStateNamespaceId()); + assertEquals(6L, responseRef.get().getPointers(0).getCatalogRevision()); } @Test From f0c585971fe687ad16e97cd1dd925ed947365eb9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:22:43 +1300 Subject: [PATCH 25/75] Preserve unavailable catalog status for valid world selectors --- .../service/impl/GameSessionGrpcService.java | 19 +++++++- .../impl/GameSessionGrpcServiceTest.java | 47 +++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 896ca96837..1d2887463f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -541,10 +541,14 @@ public void listGameplayRealms( ListGameplayRealmsRequest request, StreamObserver responseObserver) { try { + String worldSelector = requireWorldSelector(request.getWorldSlug()); WorldView world = gameplayWorldCatalog - .resolveWorld(request.getWorldSlug()) - .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay world selection")); + .resolveWorld(worldSelector) + .orElseThrow( + () -> + new CatalogRevisionUnavailableException( + "Authoritative gameplay world selection is unavailable")); List realms = gameplayWorldCatalog.visibleRealms(world).stream() .map(realm -> toGameplayRealm(world.slug(), realm)) @@ -807,6 +811,17 @@ private net.firedevops.firemud.gamesession.v1.GameplayRealm toGameplayRealm( .build(); } + private static String requireWorldSelector(String worldSelector) { + if (worldSelector == null || worldSelector.isBlank()) { + throw new IllegalArgumentException("worldSlug is required"); + } + String trimmed = worldSelector.trim(); + if (!trimmed.matches("[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*")) { + throw new IllegalArgumentException("worldSlug must be a valid selector"); + } + return worldSelector; + } + private static String requireIdentity(java.util.UUID identity, String fieldName) { if (identity == null) { throw new CatalogRevisionUnavailableException( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 8aeebd69a1..ba3f11eabf 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -734,6 +734,53 @@ public void onCompleted() {} assertFalse(pointerResponse.get().hasAdmissionPointer()); } + @Test + void unknownNamedWorldFailsClosedAsAdmissionPointerUnavailable() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of()); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + ListGameplayRealmsResponse response = listGameplayRealms(service, "unknown-world"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertEquals(0, response.getRealmsCount()); + } + + @Test + void malformedWorldSelectorRemainsInvalidArgument() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + ListGameplayRealmsResponse response = listGameplayRealms(service, "not a world"); + + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + assertEquals(0, response.getRealmsCount()); + } + @Test void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { GameplayAdmissionPointerRepository pointerRepository = From b4ec4dda53ff70bd535981a74409ce25cec2c21d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:50:56 +1300 Subject: [PATCH 26/75] Expose exact bootstrap realm catalog and namespace snapshot --- .../accountservice/dto/BootstrapRealmDto.java | 3 +++ .../service/impl/AccountServiceImpl.java | 3 +++ .../src/main/resources/openapi.yaml | 18 +++++++++++++++++- .../controller/AuthControllerTest.java | 9 +++++++++ .../service/impl/AccountServiceImplTest.java | 3 +++ 5 files changed, 35 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java index 51b97cb66e..239ad9298d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/BootstrapRealmDto.java @@ -9,6 +9,9 @@ public record BootstrapRealmDto( long tenantId, long gameInstanceId, long pointerVersion, + long catalogRevision, + String playableStateNamespaceId, + String playableStateScope, boolean requiresCharacterSelection, String stateScope, String characterCreationPolicy, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index a8fbb8394e..96ec0a8cdc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -411,6 +411,9 @@ public List listBootstrapRealms(String bootstrapToken, String realm.tenantId(), realm.gameInstanceId(), realm.pointerVersion(), + realm.catalogRevision(), + realm.playableStateNamespaceId(), + toPlayableStateScope(realm).name(), realm.requiresCharacterSelection(), realm.stateScope(), realm.characterCreationPolicy(), diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index ecb448c374..bb407e7ef7 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -191,7 +191,8 @@ components: type: string BootstrapRealmDto: type: object - required: [worldSlug, realmSlug, realmId] + required: + [worldSlug, realmSlug, realmId, catalogRevision, playableStateNamespaceId, playableStateScope] properties: worldSlug: type: string @@ -208,8 +209,23 @@ components: type: integer pointerVersion: type: integer + catalogRevision: + type: integer + format: int64 + minimum: 1 + playableStateNamespaceId: + type: string + format: uuid + playableStateScope: + type: string + enum: [PLAYABLE_STATE_SCOPE_SHARED, PLAYABLE_STATE_SCOPE_ISOLATED] requiresCharacterSelection: type: boolean + stateScope: + type: string + enum: [SHARED, ISOLATED] + characterCreationPolicy: + type: string evaluatedAt: type: string connectScopeExpiresAt: diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java index 926a4dc7a4..1c604f3f24 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java @@ -175,6 +175,9 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { 1L, 42L, 17L, + 23L, + "8b1a9953-c461-4f4c-9f6d-1f5c5c0d2d88", + "PLAYABLE_STATE_SCOPE_SHARED", false, "SHARED", "ALLOW_NEW", @@ -190,6 +193,12 @@ void listBootstrapRealmsReturnsVisibleRealms() throws Exception { .andExpect(jsonPath("$.status").value("SUCCESS")) .andExpect(jsonPath("$.data[0].realmSlug").value("production")) .andExpect(jsonPath("$.data[0].realmId").value("4c4b57d8-e3a2-48fe-9977-e7df0fdce901")) + .andExpect(jsonPath("$.data[0].catalogRevision").value(23)) + .andExpect( + jsonPath("$.data[0].playableStateNamespaceId") + .value("8b1a9953-c461-4f4c-9f6d-1f5c5c0d2d88")) + .andExpect(jsonPath("$.data[0].playableStateScope").value("PLAYABLE_STATE_SCOPE_SHARED")) + .andExpect(jsonPath("$.data[0].stateScope").value("SHARED")) .andExpect(jsonPath("$.data[0].connectScopeId").value("scope-1")); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 98a65c28d4..de4026b9e4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -3451,6 +3451,9 @@ void listBootstrapRealmsIncludesRealmStatePolicy() { .getPayload() .get("realmId")); assertEquals("SHARED", realms.getFirst().stateScope()); + assertEquals(23L, realms.getFirst().catalogRevision()); + assertEquals("production-namespace-7", realms.getFirst().playableStateNamespaceId()); + assertEquals("PLAYABLE_STATE_SCOPE_SHARED", realms.getFirst().playableStateScope()); assertEquals("ALLOW_NEW", realms.getFirst().characterCreationPolicy()); } From c99ea251b0e92fb659b704115369f0708be0c70e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 10:00:49 +1300 Subject: [PATCH 27/75] Preserve durable admission identity in runtime state --- ...SessionRuntimeControlPlaneReadService.java | 15 +- ...ameSessionControlPlaneGrpcServiceTest.java | 45 ++++-- ...ionRuntimeControlPlaneReadServiceTest.java | 148 +++++++++++++++++- .../impl/AdmissionPointerServiceImplTest.java | 6 + 4 files changed, 192 insertions(+), 22 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java index dc7cbf3e8f..a62c1ce81a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java @@ -369,6 +369,13 @@ private GameplayRoutingBundle toGameplayRoutingBundle(GameplayAdmissionPointerSn private AdmissionPointerControlPlaneEntry toControlPlaneEntry( GameplayAdmissionPointerSnapshot pointer) { + if (pointer.catalogRevision() <= 0L + || pointer.realmId() == null + || pointer.playableStateNamespaceId() == null) { + throw new RuntimeStateException( + "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE", + "current admission pointer durable identity or catalog revision is unavailable"); + } AdmissionPointerControlPlaneEntry.Builder builder = AdmissionPointerControlPlaneEntry.newBuilder() .setWorldSlug(normalizeBlank(pointer.worldSlug())) @@ -382,10 +389,10 @@ private AdmissionPointerControlPlaneEntry toControlPlaneEntry( .setRequiresCharacterSelection(pointer.requiresCharacterSelection()) .setStateScope(normalizeBlank(pointer.stateScope())) .setCharacterCreationPolicy(normalizeBlank(pointer.characterCreationPolicy())) - .setPublicProductionRealm(pointer.publicProductionRealm()); - if (pointer.catalogRevision() > 0L) { - builder.setCatalogRevision(pointer.catalogRevision()); - } + .setPublicProductionRealm(pointer.publicProductionRealm()) + .setRealmId(pointer.realmId().toString()) + .setPlayableStateNamespaceId(pointer.playableStateNamespaceId().toString()) + .setCatalogRevision(pointer.catalogRevision()); return builder.build(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 77b0f1133e..a592176a26 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -548,7 +548,9 @@ void getGameInstanceRuntimeStateReturnsCanonicalVersionAndPinMetadata() { true, "SHARED", "CREATE_ALLOWED", - 12L))); + 12L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = @@ -603,6 +605,16 @@ public void onNext(GetGameInstanceRuntimeStateResponse value) { assertEquals( 12L, responseRef.get().getRuntimeState().getCurrentAdmissionPointers(0).getCatalogRevision()); + assertEquals( + "11111111-1111-1111-1111-111111111111", + responseRef.get().getRuntimeState().getCurrentAdmissionPointers(0).getRealmId()); + assertEquals( + "22222222-2222-2222-2222-222222222222", + responseRef + .get() + .getRuntimeState() + .getCurrentAdmissionPointers(0) + .getPlayableStateNamespaceId()); assertEquals("region-7", responseRef.get().getRuntimeState().getRegionId()); assertEquals(22L, responseRef.get().getRuntimeState().getRegionEpoch()); assertEquals(17L, responseRef.get().getRuntimeState().getPublication().getVersionId()); @@ -714,7 +726,10 @@ void getGameInstanceRuntimeStateClearsSingularRoutingBundleWhenRuntimeHasMultipl true, true, "SHARED", - "CREATE_ALLOWED"), + "CREATE_ALLOWED", + 11L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")), new GameplayAdmissionPointerSnapshot( "sandbox", "Sandbox World", @@ -727,7 +742,10 @@ void getGameInstanceRuntimeStateClearsSingularRoutingBundleWhenRuntimeHasMultipl false, true, "SHARED", - "CREATE_ALLOWED"))); + "CREATE_ALLOWED", + 12L, + UUID.fromString("33333333-3333-3333-3333-333333333333"), + UUID.fromString("44444444-4444-4444-4444-444444444444")))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = @@ -803,7 +821,10 @@ void getGameInstanceRuntimeStateClearsSingularRoutingBundleWhenOnlyPointerIsInco true, true, "SHARED", - "CREATE_ALLOWED"))); + "CREATE_ALLOWED", + 11L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = @@ -848,7 +869,7 @@ public void onNext(GetGameInstanceRuntimeStateResponse value) { } @Test - void getGameInstanceRuntimeStateClearsSingularRoutingBundleWhenOnlyPointerLacksRuntimeIdentity() { + void getGameInstanceRuntimeStateFailsClosedWhenPointerLacksDurableIdentity() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); @@ -909,18 +930,8 @@ public void onNext(GetGameInstanceRuntimeStateResponse value) { }); assertNotNull(responseRef.get()); - assertEquals( - PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED, - responseRef.get().getRuntimeState().getPlayableStateScope()); - assertEquals("", responseRef.get().getRuntimeState().getWorldSlug()); - assertEquals("", responseRef.get().getRuntimeState().getRealmSlug()); - assertEquals(0L, responseRef.get().getRuntimeState().getPointerVersion()); - assertEquals(1, responseRef.get().getRuntimeState().getCurrentAdmissionPointersCount()); - assertEquals( - "demo", responseRef.get().getRuntimeState().getCurrentAdmissionPointers(0).getWorldSlug()); - assertEquals( - "production", - responseRef.get().getRuntimeState().getCurrentAdmissionPointers(0).getRealmSlug()); + assertEquals("ADMISSION_POINTER_AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); + assertFalse(responseRef.get().hasRuntimeState()); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java index 24b52c2e58..f90285201b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java @@ -7,7 +7,9 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.v1.GetPublishedScriptPatchVersionResponse; import net.firedevops.firemud.gamedesign.v1.PublishedScriptPatchVersion; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; @@ -20,6 +22,7 @@ import net.firedevops.firemud.gamesession.repository.RemoteFollowupRepository; import net.firedevops.firemud.gamesession.repository.RuntimeRegionStatusRepository; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.v1.GetGameInstanceRuntimeStateRequest; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; @@ -65,6 +68,131 @@ void runtimeReadReturnsPersistedScriptPinEpoch() { assertEquals(9L, state.getScriptPinEpoch()); } + @Test + void runtimeReadMapsDurableAdmissionPointerIdentity() { + WorldManagementClient world = mock(WorldManagementClient.class); + when(world.getWorldInstanceLifecycle(1L, 7L)) + .thenReturn( + worldLifecycle( + 1L, 7L, 3L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); + GameplayAdmissionPointerAuthorityService authority = + mock(GameplayAdmissionPointerAuthorityService.class); + when(authority.listByRuntimeTarget(1L, 7L)) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Production", + 1L, + 7L, + 11L, + true, + true, + true, + "SHARED", + "CREATE_ALLOWED", + 12L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); + GameSessionRuntimeControlPlaneReadService service = + service(world, "RUNNING", null, null, null, null, authority); + + var state = service.getGameInstanceRuntimeState(1L, runtimeRequest()); + + assertEquals(12L, state.getCurrentAdmissionPointers(0).getCatalogRevision()); + assertEquals( + "11111111-1111-1111-1111-111111111111", state.getCurrentAdmissionPointers(0).getRealmId()); + assertEquals( + "22222222-2222-2222-2222-222222222222", + state.getCurrentAdmissionPointers(0).getPlayableStateNamespaceId()); + } + + @Test + void runtimeReadFailsClosedWhenAdmissionPointerIdentityIsMissing() { + WorldManagementClient world = mock(WorldManagementClient.class); + when(world.getWorldInstanceLifecycle(1L, 7L)) + .thenReturn( + worldLifecycle( + 1L, 7L, 3L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); + GameplayAdmissionPointerAuthorityService authority = + mock(GameplayAdmissionPointerAuthorityService.class); + when(authority.listByRuntimeTarget(1L, 7L)) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Production", + 1L, + 7L, + 11L, + true, + true, + true, + "SHARED", + "CREATE_ALLOWED", + 12L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + null))); + GameSessionRuntimeControlPlaneReadService service = + service(world, "RUNNING", null, null, null, null, authority); + + GameSessionRuntimeControlPlaneReadService.RuntimeStateException error = + assertThrows( + GameSessionRuntimeControlPlaneReadService.RuntimeStateException.class, + () -> service.getGameInstanceRuntimeState(1L, runtimeRequest())); + + assertEquals("ADMISSION_POINTER_AUTHORITY_UNAVAILABLE", error.code()); + assertEquals( + "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE: current admission pointer durable identity or catalog revision is unavailable", + error.getMessage()); + } + + @Test + void runtimeReadFailsClosedWhenAdmissionPointerCatalogRevisionIsMissing() { + WorldManagementClient world = mock(WorldManagementClient.class); + when(world.getWorldInstanceLifecycle(1L, 7L)) + .thenReturn( + worldLifecycle( + 1L, 7L, 3L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); + GameplayAdmissionPointerAuthorityService authority = + mock(GameplayAdmissionPointerAuthorityService.class); + when(authority.listByRuntimeTarget(1L, 7L)) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Production", + 1L, + 7L, + 11L, + true, + true, + true, + "SHARED", + "CREATE_ALLOWED", + 0L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); + GameSessionRuntimeControlPlaneReadService service = + service(world, "RUNNING", null, null, null, null, authority); + + GameSessionRuntimeControlPlaneReadService.RuntimeStateException error = + assertThrows( + GameSessionRuntimeControlPlaneReadService.RuntimeStateException.class, + () -> service.getGameInstanceRuntimeState(1L, runtimeRequest())); + + assertEquals("ADMISSION_POINTER_AUTHORITY_UNAVAILABLE", error.code()); + assertEquals( + "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE: current admission pointer durable identity or catalog revision is unavailable", + error.getMessage()); + } + @Test void runtimeReadPublishesStoredPinBaseRatherThanCurrentRuntimeVersion() { WorldManagementClient world = mock(WorldManagementClient.class); @@ -444,6 +572,24 @@ private GameSessionRuntimeControlPlaneReadService service( Long scriptPinEpoch, Long scriptPatchBaseVersionId, GameDesignClient gameDesignClient) { + return service( + world, + status, + scriptPatchVersion, + scriptPinEpoch, + scriptPatchBaseVersionId, + gameDesignClient, + mock(GameplayAdmissionPointerAuthorityService.class)); + } + + private GameSessionRuntimeControlPlaneReadService service( + WorldManagementClient world, + String status, + String scriptPatchVersion, + Long scriptPinEpoch, + Long scriptPatchBaseVersionId, + GameDesignClient gameDesignClient, + GameplayAdmissionPointerAuthorityService authority) { GameInstance instance = new GameInstance(); instance.setId(7L); instance.setTenantId(1L); @@ -470,7 +616,7 @@ private GameSessionRuntimeControlPlaneReadService service( mock(GameplayCommandRepository.class), mock(RemoteFollowupRepository.class), runtime, - mock(GameplayAdmissionPointerAuthorityService.class), + authority, gameDesignClient, world); } diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java index 2667612522..8dc3487a47 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java @@ -333,6 +333,12 @@ void getRuntimeStateReturnsCanonicalRuntimeState() { assertEquals(7L, result.gameInstanceId()); assertEquals("demo", result.worldSlug()); assertEquals("production", result.currentAdmissionPointers().getFirst().realmSlug()); + assertEquals( + java.util.UUID.fromString("11111111-1111-1111-1111-111111111111"), + result.currentAdmissionPointers().getFirst().realmId()); + assertEquals( + java.util.UUID.fromString("22222222-2222-2222-2222-222222222222"), + result.currentAdmissionPointers().getFirst().playableStateNamespaceId()); assertEquals("VERSION_LIFECYCLE_STATE_PUBLISHED", result.publication().publicationState()); } From d64d239170d030add485f4ccfc1e3245cc30224c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 10:04:21 +1300 Subject: [PATCH 28/75] Expose unavailable pointer authority as retryable operator status --- .../impl/AdmissionPointerServiceImpl.java | 2 + .../impl/AdmissionPointerServiceImplTest.java | 41 +++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java index 46ec995462..2f95e85ce7 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java @@ -388,6 +388,8 @@ private void requireNoError(ErrorDetail error) { switch (error.getCode()) { case "INVALID_ARGUMENT" -> HttpStatus.BAD_REQUEST; case "PERMISSION_DENIED" -> HttpStatus.FORBIDDEN; + case "AUTHORITY_UNAVAILABLE", "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE" -> + HttpStatus.SERVICE_UNAVAILABLE; case "POINTER_VERSION_MISMATCH" -> HttpStatus.CONFLICT; case "CUTOVER_PREPARATION_INVALID" -> HttpStatus.CONFLICT; case "NOT_FOUND" -> HttpStatus.NOT_FOUND; diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java index 8dc3487a47..c8c7cfe557 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java @@ -75,6 +75,25 @@ void listPointersFiltersToAccessibleTenant() { assertEquals(2L, result.get(0).tenantId()); } + @Test + void listPointersMapsUnavailableAuthorityToServiceUnavailable() { + when(gameSessionControlPlaneClient.listAdmissionPointers()) + .thenReturn( + ListAdmissionPointersResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("AUTHORITY_UNAVAILABLE") + .setMessage("current pointer authority unavailable") + .build()) + .build()); + + ResponseStatusException ex = + assertThrows(ResponseStatusException.class, () -> service.listPointers()); + + assertEquals(503, ex.getStatusCode().value()); + assertEquals("current pointer authority unavailable", ex.getReason()); + } + @Test void listPointerAuditRequiresAccessibleTenant() { SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); @@ -104,6 +123,28 @@ void listPointerAuditUsesCanonicalTenantKey() { result.get(0).playableStateNamespaceId()); } + @Test + void listPointerAuditMapsAdmissionPointerAuthorityUnavailableToServiceUnavailable() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + when(gameSessionControlPlaneClient.listAdmissionPointerAudit(2L, "sandbox", "preview")) + .thenReturn( + ListAdmissionPointerAuditResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("ADMISSION_POINTER_AUTHORITY_UNAVAILABLE") + .setMessage("current admission pointer authority unavailable") + .build()) + .build()); + + ResponseStatusException ex = + assertThrows( + ResponseStatusException.class, + () -> service.listPointerAudit(2L, "sandbox", "preview")); + + assertEquals(503, ex.getStatusCode().value()); + assertEquals("current admission pointer authority unavailable", ex.getReason()); + } + @Test void listPointerAuditLeavesHistoricalIdentityAbsent() { SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); From 9df59e4179112e841e61eaf220cd016ed9edca26 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 10:05:00 +1300 Subject: [PATCH 29/75] Fail closed on incomplete gameplay discovery authority --- .../client/GameSessionClientTest.java | 21 +++ .../command/text/GameplayWorldCatalog.java | 56 ++++++- .../service/impl/GameSessionGrpcService.java | 50 ++++-- .../impl/GameSessionGrpcServiceTest.java | 150 ++++++++++++++++++ 4 files changed, 261 insertions(+), 16 deletions(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java index 63d5810392..173599a920 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java @@ -87,6 +87,27 @@ void reachableResponseErrorRemainsDomainFailure() throws Exception { verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); } + @Test + void reachableAdmissionPointerUnavailableResponsePropagatesAsDomainFailure() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + when(stub.listGameplayWorlds(any())) + .thenReturn( + ListGameplayWorldsResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("ADMISSION_POINTER_UNAVAILABLE") + .setMessage("incomplete authority")) + .build()); + GameSessionClient client = newClient(stub); + + IllegalStateException failure = + assertThrows(IllegalStateException.class, client::listGameplayWorlds); + + assertThat(failure) + .hasMessage("Gameplay world discovery failed: ADMISSION_POINTER_UNAVAILABLE"); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + @Test void nonRetryableTransportStatusRetainsTransportClassification() throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 25571db9ad..1f1f1782f7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -21,9 +21,17 @@ @Component public final class GameplayWorldCatalog { private final Supplier> worldSupplier; + private final Supplier> authorityPointerSupplier; private GameplayWorldCatalog(Supplier> worldSupplier) { + this(worldSupplier, null); + } + + private GameplayWorldCatalog( + Supplier> worldSupplier, + Supplier> authorityPointerSupplier) { this.worldSupplier = Objects.requireNonNull(worldSupplier, "worldSupplier must not be null"); + this.authorityPointerSupplier = authorityPointerSupplier; } @Autowired @@ -32,6 +40,10 @@ public GameplayWorldCatalog(GameplayAdmissionPointerAuthorityService authoritySe () -> { Objects.requireNonNull(authorityService, "authorityService must not be null"); return toWorlds(authorityService.listPointers()); + }, + () -> { + Objects.requireNonNull(authorityService, "authorityService must not be null"); + return authorityService.listPointers(); }); } @@ -56,7 +68,17 @@ public Optional resolveWorld(String selector) { if (selector == null || selector.isBlank()) { return Optional.empty(); } - List worlds = visibleWorlds(); + return resolveWorld(selector, visibleWorlds()); + } + + public Optional resolveWorldFromAuthoritySnapshot(String selector) { + if (selector == null || selector.isBlank()) { + return Optional.empty(); + } + return resolveWorld(selector, visibleWorldsFromAuthoritySnapshot()); + } + + private Optional resolveWorld(String selector, List worlds) { try { int index = Integer.parseInt(selector); if (index >= 1 && index <= worlds.size()) { @@ -180,6 +202,32 @@ public List visibleWorlds() { .toList(); } + /** + * Builds the visible world projection from one authoritative pointer-list snapshot. + * + *

Text discovery intentionally continues to use {@link #visibleWorlds()}, which filters + * malformed or ambiguous rows for its existing negative-admission behavior. The gRPC discovery + * boundary instead needs to distinguish an empty authority store from an unavailable authority + * row, so it validates the exact snapshot before projecting it. + */ + public List visibleWorldsFromAuthoritySnapshot() { + if (authorityPointerSupplier == null) { + return visibleWorlds(); + } + List pointers = authorityPointerSupplier.get(); + if (pointers == null) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer list is unavailable"); + } + for (GameplayAdmissionPointerSnapshot pointer : pointers) { + if (!hasCompleteAuthorityPointer(pointer)) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer is incomplete"); + } + } + return toWorlds(pointers).stream().filter(this::hasVisibleRealmEntries).toList(); + } + private List worldEntries() { List worlds = visibleWorlds(); ArrayList entries = new ArrayList<>(worlds.size()); @@ -279,6 +327,12 @@ private static boolean hasCompleteAuthorityPointer(GameplayAdmissionPointerSnaps && !pointer.characterCreationPolicy().isBlank(); } + public static final class AuthorityPointerUnavailableException extends RuntimeException { + public AuthorityPointerUnavailableException(String message) { + super(message); + } + } + private static RealmView toRealmView(GameplayAdmissionPointerSnapshot pointer) { return new RealmView( pointer.realmSlug(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 896ca96837..26263256ec 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -519,20 +519,31 @@ public void queryAccountPresence( public void listGameplayWorlds( ListGameplayWorldsRequest request, StreamObserver responseObserver) { - ListGameplayWorldsResponse response = - ListGameplayWorldsResponse.newBuilder() - .addAllWorlds( - gameplayWorldCatalog.visibleWorlds().stream() - .map( - world -> - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug(world.slug()) - .setDisplayName(world.displayName()) - .build()) - .toList()) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); + try { + ListGameplayWorldsResponse response = + ListGameplayWorldsResponse.newBuilder() + .addAllWorlds( + gameplayWorldCatalog.visibleWorldsFromAuthoritySnapshot().stream() + .map( + world -> + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug(world.slug()) + .setDisplayName(world.displayName()) + .build()) + .toList()) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + ListGameplayWorldsResponse response = + ListGameplayWorldsResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } } @Override @@ -543,7 +554,7 @@ public void listGameplayRealms( try { WorldView world = gameplayWorldCatalog - .resolveWorld(request.getWorldSlug()) + .resolveWorldFromAuthoritySnapshot(request.getWorldSlug()) .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay world selection")); List realms = gameplayWorldCatalog.visibleRealms(world).stream() @@ -562,6 +573,15 @@ public void listGameplayRealms( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + ListGameplayRealmsResponse response = + ListGameplayRealmsResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (IllegalArgumentException ex) { ListGameplayRealmsResponse response = ListGameplayRealmsResponse.newBuilder() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 32a0621249..1ca9f2af97 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -41,6 +41,8 @@ import net.firedevops.firemud.gamesession.v1.GetTickStatusResponse; import net.firedevops.firemud.gamesession.v1.ListGameplayRealmsRequest; import net.firedevops.firemud.gamesession.v1.ListGameplayRealmsResponse; +import net.firedevops.firemud.gamesession.v1.ListGameplayWorldsRequest; +import net.firedevops.firemud.gamesession.v1.ListGameplayWorldsResponse; import net.firedevops.firemud.gamesession.v1.PauseTicksRequest; import net.firedevops.firemud.gamesession.v1.PauseTicksResponse; import net.firedevops.firemud.gamesession.v1.PingRequest; @@ -433,6 +435,133 @@ public void onCompleted() {} Mockito.verifyNoInteractions(accountPresenceQueryService); } + @Test + void listGameplayWorldsBuildsVisibleWorldsFromOneAuthoritySnapshot() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot firstSnapshot = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 29L, + java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"), + java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412")); + GameplayAdmissionPointerSnapshot secondSnapshot = + new GameplayAdmissionPointerSnapshot( + "other", + "Other World", + "production", + "Other Realm", + 8L, + 55L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 4L, + java.util.UUID.fromString("c0a801a0-7e42-4cc8-9e18-0c0b20d4e6f9"), + java.util.UUID.fromString("e94d4b9d-7635-4d7f-b70c-12f4e3ea8e27")); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn(List.of(firstSnapshot), List.of(secondSnapshot)); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + ListGameplayWorldsResponse response = listGameplayWorlds(service); + + assertFalse(response.hasError()); + assertEquals(1, response.getWorldsCount()); + assertEquals("demo", response.getWorlds(0).getWorldSlug()); + assertEquals("Demo World", response.getWorlds(0).getDisplayName()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + } + + @Test + void listGameplayWorldsAllowsAnEmptyAuthorityStore() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of()); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + ListGameplayWorldsResponse response = listGameplayWorlds(service); + + assertFalse(response.hasError()); + assertEquals(0, response.getWorldsCount()); + Mockito.verify(pointerAuthorityService).listPointers(); + } + + @Test + void listGameplayWorldsRejectsAnIncompleteAuthorityPointer() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot incompleteSnapshot = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 0L); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(incompleteSnapshot)); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + ListGameplayWorldsResponse response = listGameplayWorlds(service); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertEquals(0, response.getWorldsCount()); + Mockito.verify(pointerAuthorityService).listPointers(); + } + @Test void gameplayCatalogRpcReturnsCanonicalRealmData() { PingService pingService = Mockito.mock(PingService.class); @@ -652,6 +781,27 @@ public void onCompleted() {} return response.get(); } + private static ListGameplayWorldsResponse listGameplayWorlds(GameSessionGrpcService service) { + AtomicReference response = new AtomicReference<>(); + service.listGameplayWorlds( + ListGameplayWorldsRequest.getDefaultInstance(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayWorldsResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + return response.get(); + } + @Test void missingStableRealmIdentityFailsClosedForCatalogReads() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = From 1f5d4f0079ccbc26a2d7cfc6c30b5896b421e9c5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 10:08:25 +1300 Subject: [PATCH 30/75] Lock pointer no-ops and order audit by event sequence --- ...meplayAdmissionPointerEventRepository.java | 12 +-- .../GameplayAdmissionPointerRepository.java | 13 ++++ ...eplayAdmissionPointerAuthorityService.java | 4 +- ...ameplayAdmissionPointerRepositoryTest.java | 78 +++++++++++++++++++ ...yAdmissionPointerAuthorityServiceTest.java | 68 ++++++++++++++-- 5 files changed, 157 insertions(+), 18 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java index 276817318a..446f513199 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java @@ -23,7 +23,7 @@ public GameplayAdmissionPointerEventRepository(DSLContext dsl) { this.dsl = dsl; } - public List findByWorldSlugAndRealmSlugOrderByOccurredAtDesc( + public List findByWorldSlugAndRealmSlugOrderByIdDesc( String worldSlug, String realmSlug) { return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER_EVENT) .where( @@ -31,14 +31,12 @@ public List findByWorldSlugAndRealmSlugOrderByOcc .WORLD_SLUG .eq(worldSlug) .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(realmSlug))) - .orderBy( - GAMEPLAY_ADMISSION_POINTER_EVENT.OCCURRED_AT.desc(), - GAMEPLAY_ADMISSION_POINTER_EVENT.ID.desc()) + .orderBy(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.desc()) .fetch(this::toEntity); } public List - findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc( + findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( Long tenantId, String worldSlug, String realmSlug) { return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER_EVENT) .where( @@ -47,9 +45,7 @@ public List findByWorldSlugAndRealmSlugOrderByOcc .eq(tenantId) .and(GAMEPLAY_ADMISSION_POINTER_EVENT.WORLD_SLUG.eq(worldSlug)) .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(realmSlug))) - .orderBy( - GAMEPLAY_ADMISSION_POINTER_EVENT.OCCURRED_AT.desc(), - GAMEPLAY_ADMISSION_POINTER_EVENT.ID.desc()) + .orderBy(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.desc()) .fetch(this::toEntity); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index 60748667ed..f324de0d6f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -47,6 +47,19 @@ public Optional findByTenantIdAndWorldSlugAndRealmSlug .fetchOptional(this::toEntity); } + public Optional findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + Long tenantId, String worldSlug, String realmSlug) { + return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + .where( + GAMEPLAY_ADMISSION_POINTER + .TENANT_ID + .eq(tenantId) + .and(GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG.eq(worldSlug)) + .and(GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.eq(realmSlug))) + .forUpdate() + .fetchOptional(this::toEntity); + } + public Optional findByTenantIdAndGameInstanceId( Long tenantId, Long gameInstanceId) { return findAllByTenantIdAndGameInstanceId(tenantId, gameInstanceId).stream().findFirst(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index 66d1ca5287..a744dc6d7d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -70,7 +70,7 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu Instant now = Instant.now(); GameplayAdmissionPointer pointer = pointerRepository - .findByTenantIdAndWorldSlugAndRealmSlug( + .findByTenantIdAndWorldSlugAndRealmSlugForUpdate( mutation.tenantId(), mutation.worldSlug(), mutation.realmSlug()) .orElseGet(GameplayAdmissionPointer::new); if (pointer.getId() != null @@ -149,7 +149,7 @@ && catalogPolicyMatches(pointer, mutation)) { public List listPointerAudit( long tenantId, String worldSlug, String realmSlug) { return eventRepository - .findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc(tenantId, worldSlug, realmSlug) + .findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc(tenantId, worldSlug, realmSlug) .stream() .map( event -> diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index c38195a515..1f51e58363 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -10,6 +10,7 @@ import java.time.Instant; import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -106,6 +107,32 @@ void catalogOnlyUpdatePreservesPointerVersionAndFencesStaleCatalogRevision() thr } } + @Test + void pointerAuditOrdersByEventIdWhenPodTimestampMovesBackward() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-audit-order;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createAuditSchema(dsl); + GameplayAdmissionPointerEventRepository repository = + new GameplayAdmissionPointerEventRepository(dsl); + + GameplayAdmissionPointerEvent earlierWrite = pointerEvent("2026-09-29T10:00:00Z"); + GameplayAdmissionPointerEvent firstSaved = repository.save(earlierWrite); + GameplayAdmissionPointerEvent laterWriteWithSkewedClock = + pointerEvent("2026-09-29T09:00:00Z"); + GameplayAdmissionPointerEvent secondSaved = repository.save(laterWriteWithSkewedClock); + + var audit = + repository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( + 7L, "demo", "production"); + + assertEquals(secondSaved.getId(), audit.getFirst().getId()); + assertEquals(firstSaved.getId(), audit.get(1).getId()); + assertEquals(Instant.parse("2026-09-29T09:00:00Z"), audit.getFirst().getOccurredAt()); + } + } + private static GameplayAdmissionPointer pointer( long tenantId, long gameInstanceId, String stateScope, String realmSlug) { GameplayAdmissionPointer pointer = new GameplayAdmissionPointer(); @@ -166,4 +193,55 @@ CONSTRAINT uq_pointer_tenant_runtime UNIQUE (tenant_id, game_instance_id) ) """); } + + private static GameplayAdmissionPointerEvent pointerEvent(String occurredAt) { + GameplayAdmissionPointerEvent event = new GameplayAdmissionPointerEvent(); + event.setWorldSlug("demo"); + event.setRealmSlug("production"); + event.setWorldDisplayName("Demo World"); + event.setRealmDisplayName("Production"); + event.setTenantId(7L); + event.setGameInstanceId(44L); + event.setPointerVersion(1L); + event.setCatalogRevision(1L); + event.setVisible(true); + event.setPublicProductionRealm(true); + event.setRequiresCharacterSelection(false); + event.setStateScope("SHARED"); + event.setCharacterCreationPolicy("ALLOW_NEW"); + event.setActorPrincipal("tester"); + event.setReason("test"); + event.setControlPlaneRequestId(UUID.randomUUID().toString()); + event.setOccurredAt(Instant.parse(occurredAt)); + return event; + } + + private static void createAuditSchema(DSLContext dsl) { + dsl.execute( + """ + CREATE TABLE gameplay_admission_pointer_event ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + world_slug VARCHAR(120) NOT NULL, + realm_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(200) NOT NULL, + realm_display_name VARCHAR(200) NOT NULL, + tenant_id BIGINT NOT NULL, + game_instance_id BIGINT NOT NULL, + pointer_version BIGINT NOT NULL, + catalog_revision BIGINT, + realm_id UUID, + playable_state_namespace_id UUID, + visible BOOLEAN NOT NULL, + public_production_realm BOOLEAN NOT NULL, + requires_character_selection BOOLEAN NOT NULL, + state_scope VARCHAR(32) NOT NULL, + character_creation_policy VARCHAR(32) NOT NULL, + actor_principal VARCHAR(200) NOT NULL, + reason VARCHAR(500) NOT NULL, + control_plane_request_id VARCHAR(120) NOT NULL, + prepared_version_upgrade_id VARCHAR(64), + occurred_at TIMESTAMP NOT NULL + ) + """); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index 57a720ce87..35295ccf69 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -44,7 +44,9 @@ void upsertPointerRejectsMismatchedExpectedVersion() { existing.setId(11L); existing.setPointerVersion(3L); existing.setStateScope("SHARED"); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + when( + pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); assertThrows( @@ -99,7 +101,9 @@ void upsertPointerRejectsUnknownStateScope() { @Test void upsertPointerAllowsCreateWhenExpectedVersionPairIsZero() { - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + when( + pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.empty()); when(pointerRepository.save(any(GameplayAdmissionPointer.class))) .thenAnswer( @@ -151,7 +155,9 @@ void upsertPointerAllowsCreateWhenExpectedVersionPairIsZero() { @Test void upsertPointerAdvancesCatalogRevisionWithoutAdvancingPointerVersion() { GameplayAdmissionPointer existing = existingPointer(); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + when( + pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); when(pointerRepository.save(any(GameplayAdmissionPointer.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -189,7 +195,9 @@ void upsertPointerAdvancesCatalogRevisionWithoutAdvancingPointerVersion() { @Test void upsertPointerExactNoOpDoesNotAdvanceOrPersistVersions() { GameplayAdmissionPointer existing = existingPointer(); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + when( + pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); GameplayAdmissionPointerSnapshot snapshot = @@ -215,6 +223,46 @@ void upsertPointerExactNoOpDoesNotAdvanceOrPersistVersions() { assertEquals(1L, snapshot.pointerVersion()); assertEquals(1L, snapshot.catalogRevision()); + verify(pointerRepository) + .findByTenantIdAndWorldSlugAndRealmSlugForUpdate(1L, "demo", "production"); + verify(pointerRepository, never()).save(any(GameplayAdmissionPointer.class)); + verifyNoInteractions(eventRepository); + } + + @Test + void upsertPointerRejectsStaleExpectedVersionsForExactNoOp() { + GameplayAdmissionPointer current = existingPointer(); + current.setPointerVersion(2L); + current.setCatalogRevision(2L); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) + .thenReturn(Optional.of(current)); + + assertThrows( + AdmissionPointerVersionMismatchException.class, + () -> + service.upsertPointer( + new GameplayAdmissionPointerMutation( + "demo", + "Demo World", + "production", + "Live Realm", + 1L, + 7L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "stale retry", + "req-stale-no-op", + 1L, + 1L, + null))); + + verify(pointerRepository) + .findByTenantIdAndWorldSlugAndRealmSlugForUpdate(1L, "demo", "production"); verify(pointerRepository, never()).save(any(GameplayAdmissionPointer.class)); verifyNoInteractions(eventRepository); } @@ -223,7 +271,9 @@ void upsertPointerExactNoOpDoesNotAdvanceOrPersistVersions() { void upsertPointerRejectsStaleCatalogRevisionEvenWhenPointerVersionMatches() { GameplayAdmissionPointer existing = existingPointer(); existing.setCatalogRevision(2L); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + when( + pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); assertThrows( @@ -256,7 +306,9 @@ void upsertPointerRejectsStaleCatalogRevisionEvenWhenPointerVersionMatches() { @Test void upsertPointerRejectsExistingMutationWithoutExpectedPair() { GameplayAdmissionPointer existing = existingPointer(); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + when( + pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); assertThrows( @@ -302,7 +354,7 @@ void listPointerAuditExposesPersistedCatalogRevision() { event.setStateScope("SHARED"); event.setCharacterCreationPolicy("ALLOW_NEW"); event.setOccurredAt(java.time.Instant.parse("2026-09-29T00:00:00Z")); - when(eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc( + when(eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( 1L, "demo", "production")) .thenReturn(List.of(event)); @@ -321,7 +373,7 @@ void listPointerAuditLeavesHistoricalIdentityAbsent() { historicalEvent.setGameInstanceId(7L); historicalEvent.setPointerVersion(1L); historicalEvent.setCatalogRevision(1L); - when(eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc( + when(eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( 1L, "demo", "production")) .thenReturn(List.of(historicalEvent)); From f6cbd4ca49e61d10eb1cac8309eaae21a92275ef Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 10:50:41 +1300 Subject: [PATCH 31/75] Serialize gameplay pointer bootstrap before empty-store check --- ...layAdmissionPointerBootstrapInitializer.java | 1 + .../GameplayAdmissionPointerRepository.java | 17 +++++++++++++++++ ...dmissionPointerBootstrapInitializerTest.java | 5 +++++ .../GameplayAdmissionPointerRepositoryTest.java | 8 ++++++++ 4 files changed, 31 insertions(+) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java index fea7518664..69be4769e1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java @@ -30,6 +30,7 @@ public class GameplayAdmissionPointerBootstrapInitializer implements Application @Override @Transactional public void run(ApplicationArguments args) { + pointerRepository.lockForBootstrap(); if (pointerRepository.count() > 0) { return; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index f324de0d6f..797c93a2cf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -25,6 +25,8 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class GameplayAdmissionPointerRepository { + private static final String BOOTSTRAP_ADVISORY_LOCK_KEY = "gameplay-admission-pointer-bootstrap"; + private final DSLContext dsl; public GameplayAdmissionPointerRepository(DSLContext dsl) { @@ -35,6 +37,17 @@ public long count() { return dsl.fetchCount(GAMEPLAY_ADMISSION_POINTER); } + /** + * Serializes the empty-store bootstrap check and seed writes across Game Session pods. + * + *

The caller must invoke this inside the transaction that performs the subsequent count and + * any seed writes so PostgreSQL retains the advisory lock through commit or rollback. Non-Postgres + * dialects skip the lock for local test compatibility. + */ + public void lockForBootstrap() { + lockAdvisoryTransaction(BOOTSTRAP_ADVISORY_LOCK_KEY); + } + public Optional findByTenantIdAndWorldSlugAndRealmSlug( Long tenantId, String worldSlug, String realmSlug) { return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) @@ -266,6 +279,10 @@ private void lockRuntimeTargets( } private void lockRuntimeTarget(String lockKey) { + lockAdvisoryTransaction(lockKey); + } + + private void lockAdvisoryTransaction(String lockKey) { // The test profile uses H2, which does not implement PostgreSQL advisory locks. // Production remains protected by the transaction-scoped PostgreSQL lock. if (dsl.dialect().family() != SQLDialect.POSTGRES) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index f4848b5c1b..a89593a35f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -15,6 +16,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.DefaultApplicationArguments; @@ -49,6 +51,9 @@ void runSeedsBootstrapPointersWhenAuthorityStoreIsEmpty() throws Exception { ArgumentCaptor mutationCaptor = ArgumentCaptor.forClass(GameplayAdmissionPointerMutation.class); verify(authorityService, org.mockito.Mockito.times(2)).upsertPointer(mutationCaptor.capture()); + InOrder bootstrapOrder = inOrder(pointerRepository); + bootstrapOrder.verify(pointerRepository).lockForBootstrap(); + bootstrapOrder.verify(pointerRepository).count(); List mutations = mutationCaptor.getAllValues(); assertEquals(2, mutations.size()); assertEquals("demo", mutations.get(0).worldSlug()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index 1f51e58363..aea1612a36 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -18,6 +18,14 @@ import org.junit.jupiter.api.Test; class GameplayAdmissionPointerRepositoryTest { + @Test + void bootstrapAdvisoryLockIsSkippedForH2() { + GameplayAdmissionPointerRepository repository = + new GameplayAdmissionPointerRepository(DSL.using(SQLDialect.H2)); + + repository.lockForBootstrap(); + } + @Test void stableRealmAndNamespaceIdentitySurviveRuntimeReplacement() throws Exception { try (Connection connection = From 49ffae936ff936934771ef147975bd52231befe5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 10:54:20 +1300 Subject: [PATCH 32/75] Enforce public join policy and tenant realm uniqueness --- .../service/impl/AccountServiceImpl.java | 21 +++ .../service/impl/AccountServiceImplTest.java | 85 ++++++++++ .../command/text/GameplayWorldCatalog.java | 69 +++++++- .../service/impl/GameSessionGrpcService.java | 12 ++ .../text/GameplayWorldCatalogTest.java | 72 +++++++++ .../impl/GameSessionGrpcServiceTest.java | 150 ++++++++++++++++++ 6 files changed, 407 insertions(+), 2 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 96ec0a8cdc..b222af32d6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -1057,6 +1057,17 @@ private ConnectTokenResult issueConnectTokenFresh( throw new AuthenticationException( "CONNECT_TOKEN_REJECTED", "Membership authority requires reconciliation"); } + if (membership.membershipExists() + && "INACTIVE".equals(membership.membershipLifecycleState()) + && isPublicProductionRealm(realm)) { + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException( + "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); + } if (membership.membershipExists() && !membership.gameplayAdmissionAllowed()) { throw new AuthenticationException( "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); @@ -1681,6 +1692,16 @@ private RuntimeRealmTarget requireCurrentAdmissibleConnectScopeTarget( Optional maybeMembership = accountTenantMembershipRepository.findByAccountIdAndTenantId( bootstrapContext.accountId(), currentRealm.tenantId()); + if (maybeMembership.isPresent() + && "INACTIVE".equals(maybeMembership.orElseThrow().getLifecycleState()) + && publicProductionRealm) { + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException("JOIN_REQUIRED", JOIN_REQUIRED_CHARACTERS_MESSAGE); + } if (maybeMembership.isPresent() && !maybeMembership.orElseThrow().isGameplayAdmissionAllowed()) { throw new AuthenticationException( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index de4026b9e4..1cb4d6e11b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -2858,6 +2858,49 @@ void issueConnectTokenRejectsMissingMembershipWhenPublicJoiningIsDisabled() { assertEquals("Public joining is not allowed for the selected game", exception.getMessage()); } + @ParameterizedTest + @CsvSource({"active, JOIN_REQUIRED", "grace, PUBLIC_PRODUCTION_ADMISSION_DENIED"}) + void issueConnectTokenClassifiesInactivePublicMembershipByJoinPolicy( + String subscriptionStatus, String expectedCode) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AccountTenantMembership inactiveMembership = membership(account, 7L); + inactiveMembership.setLifecycleState("INACTIVE"); + inactiveMembership.setGameplayAdmissionAllowed(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(inactiveMembership)); + Subscription subscription = new Subscription(); + subscription.setId(22L); + subscription.setTenantId(7L); + subscription.setStatus(subscriptionStatus); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(subscription)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "req-inactive-public"))); + + assertEquals(expectedCode, exception.getCode()); + if ("JOIN_REQUIRED".equals(expectedCode)) { + assertEquals( + "Join the selected world before requesting a connect token", exception.getMessage()); + } else { + assertEquals("Public joining is not allowed for the selected game", exception.getMessage()); + } + } + @Test void issueConnectTokenClassifiesKnownBillingDenialAndReplaysItDeterministically() { Account account = new Account(); @@ -3224,6 +3267,48 @@ void listBootstrapCharactersChecksPublicJoinPolicyBeforeReturningJoinRequired() verifyNoInteractions(entityManagementClient); } + @ParameterizedTest + @CsvSource({"active, JOIN_REQUIRED", "grace, PUBLIC_PRODUCTION_ADMISSION_DENIED"}) + void listBootstrapCharactersClassifiesInactivePublicMembershipByJoinPolicy( + String subscriptionStatus, String expectedCode) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AccountTenantMembership inactiveMembership = membership(account, 7L); + inactiveMembership.setLifecycleState("INACTIVE"); + inactiveMembership.setGameplayAdmissionAllowed(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(inactiveMembership)); + Subscription subscription = new Subscription(); + subscription.setId(22L); + subscription.setTenantId(7L); + subscription.setStatus(subscriptionStatus); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(subscription)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + + assertEquals(expectedCode, exception.getCode()); + if ("JOIN_REQUIRED".equals(expectedCode)) { + assertEquals("Join the selected world before discovering characters", exception.getMessage()); + } else { + assertEquals("Public joining is not allowed for the selected game", exception.getMessage()); + } + verifyNoInteractions(entityManagementClient); + } + @Test void listBootstrapCharactersReturnsEntitlementUnavailableBeforeClassifyingMembership() { Account account = new Account(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 1f1f1782f7..5f2bf4e07e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -1,14 +1,17 @@ package net.firedevops.firemud.gamesession.command.text; import java.util.ArrayList; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.function.Supplier; +import java.util.stream.Collectors; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -207,8 +210,8 @@ public List visibleWorlds() { * *

Text discovery intentionally continues to use {@link #visibleWorlds()}, which filters * malformed or ambiguous rows for its existing negative-admission behavior. The gRPC discovery - * boundary instead needs to distinguish an empty authority store from an unavailable authority - * row, so it validates the exact snapshot before projecting it. + * boundary validates completeness and tenant-global public-realm uniqueness on one exact + * snapshot before projecting it. */ public List visibleWorldsFromAuthoritySnapshot() { if (authorityPointerSupplier == null) { @@ -225,9 +228,51 @@ public List visibleWorldsFromAuthoritySnapshot() { "Authoritative gameplay pointer is incomplete"); } } + requireExactlyOneVisiblePublicProductionRealmPerTenant(pointers); return toWorlds(pointers).stream().filter(this::hasVisibleRealmEntries).toList(); } + /** + * Requires a direct public-production admission target to match the sole visible public realm + * in its tenant's current authoritative pointer snapshot. + */ + public void requireUniqueVisiblePublicProductionRealm( + GameplayAdmissionPointerSnapshot expectedPointer) { + if (authorityPointerSupplier == null) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer list is unavailable"); + } + if (expectedPointer == null || expectedPointer.tenantId() <= 0L) { + throw new AuthorityPointerUnavailableException( + "Authoritative public-production realm identity is unavailable"); + } + List pointers = authorityPointerSupplier.get(); + if (pointers == null) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer list is unavailable"); + } + for (GameplayAdmissionPointerSnapshot pointer : pointers) { + if (pointer == null || pointer.tenantId() == expectedPointer.tenantId()) { + if (!hasCompleteAuthorityPointer(pointer)) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer is incomplete"); + } + } + } + + List publicRealms = + pointers.stream() + .filter(pointer -> pointer.tenantId() == expectedPointer.tenantId()) + .filter(GameplayAdmissionPointerSnapshot::visible) + .filter(GameplayAdmissionPointerSnapshot::publicProductionRealm) + .toList(); + if (publicRealms.size() != 1 || !publicRealms.getFirst().equals(expectedPointer)) { + throw new AuthorityPointerUnavailableException( + "Authoritative public-production realm is not unique for tenant " + + expectedPointer.tenantId()); + } + } + private List worldEntries() { List worlds = visibleWorlds(); ArrayList entries = new ArrayList<>(worlds.size()); @@ -317,6 +362,26 @@ private static List toWorlds(List p .toList()); } + private static void requireExactlyOneVisiblePublicProductionRealmPerTenant( + List pointers) { + Set tenantIds = + pointers.stream() + .map(GameplayAdmissionPointerSnapshot::tenantId) + .collect(Collectors.toSet()); + Map publicRealmCounts = new HashMap<>(); + for (GameplayAdmissionPointerSnapshot pointer : pointers) { + if (pointer.visible() && pointer.publicProductionRealm()) { + publicRealmCounts.merge(pointer.tenantId(), 1L, Long::sum); + } + } + for (long tenantId : tenantIds) { + if (publicRealmCounts.getOrDefault(tenantId, 0L) != 1L) { + throw new AuthorityPointerUnavailableException( + "Authoritative public-production realm count is invalid for tenant " + tenantId); + } + } + } + private static boolean hasCompleteAuthorityPointer(GameplayAdmissionPointerSnapshot pointer) { return GameplayAdmissionPointerSnapshots.hasCompleteRoutingBundle(pointer) && pointer.catalogRevision() > 0L diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 26263256ec..58d09fc428 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -604,6 +604,9 @@ public void getAdmissionPointer( gameplayAdmissionPointerAuthorityService .findPointer(tenantId, request.getWorldSlug(), request.getRealmSlug()) .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay realm selection")); + if (realm.publicProductionRealm()) { + gameplayWorldCatalog.requireUniqueVisiblePublicProductionRealm(realm); + } GetAdmissionPointerResponse response = GetAdmissionPointerResponse.newBuilder() .setAdmissionPointer( @@ -638,6 +641,15 @@ public void getAdmissionPointer( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + GetAdmissionPointerResponse response = + GetAdmissionPointerResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (IllegalArgumentException ex) { GetAdmissionPointerResponse response = GetAdmissionPointerResponse.newBuilder() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index d26413a146..39ee2ad5c2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.command.text; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; @@ -82,6 +83,47 @@ void visibleWorldsDropIncompleteAuthorityPointers() { assertThat(catalog.resolveRuntimeTarget(1L, 11L)).isEmpty(); } + @Test + void authoritySnapshotRejectsPublicRealmsAcrossDifferentWorldsForOneTenant() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + publicPointer("alpha", "Alpha World", 1L, 11L), + publicPointer("beta", "Beta World", 1L, 12L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThatThrownBy(catalog::visibleWorldsFromAuthoritySnapshot) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) + .hasMessageContaining("public-production realm count is invalid"); + } + + @Test + void authoritySnapshotRejectsTenantWithoutVisiblePublicRealm() { + when(authorityService.listPointers()) + .thenReturn( + List.of(pointer("demo", "Demo World", "private", "Private Realm", 1L, 11L, 7L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThatThrownBy(catalog::visibleWorldsFromAuthoritySnapshot) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) + .hasMessageContaining("public-production realm count is invalid"); + } + + @Test + void authoritySnapshotKeepsPrivateRealmsWhenTenantHasOneVisiblePublicRealm() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + publicPointer("demo", "Demo World", 1L, 11L), + pointer("private", "Private World", "preview", "Preview", 1L, 12L, 1L), + publicPointer("hidden", "Hidden", 1L, 13L, false))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorldsFromAuthoritySnapshot()) + .extracting(GameplayWorldCatalog.WorldView::slug) + .containsExactly("demo", "private"); + } + @ParameterizedTest(name = "authority projection rejects {0}") @MethodSource("incompleteAuthorityPointers") void visibleWorldsDropPointersWithoutCompleteCatalogIdentity( @@ -289,6 +331,36 @@ private static GameplayAdmissionPointerSnapshot pointer( stableId("namespace/" + realmId)); } + private static GameplayAdmissionPointerSnapshot publicPointer( + String worldSlug, String worldDisplayName, long tenantId, long gameInstanceId) { + return publicPointer(worldSlug, worldDisplayName, tenantId, gameInstanceId, true); + } + + private static GameplayAdmissionPointerSnapshot publicPointer( + String worldSlug, + String worldDisplayName, + long tenantId, + long gameInstanceId, + boolean visible) { + UUID realmId = stableId("realm/" + tenantId + "/" + worldSlug + "/public"); + return new GameplayAdmissionPointerSnapshot( + worldSlug, + worldDisplayName, + "live", + "Live Realm", + tenantId, + gameInstanceId, + 1L, + visible, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + realmId, + stableId("namespace/" + realmId)); + } + private static Stream incompleteAuthorityPointers() { GameplayAdmissionPointerSnapshot complete = new GameplayAdmissionPointerSnapshot( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 1ca9f2af97..0a33e6b2b1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -148,6 +148,51 @@ private static GameSessionGrpcService newService( ipConnectionLimiter); } + private static GameSessionGrpcService catalogService( + GameplayAdmissionPointerAuthorityService pointerAuthorityService) { + return newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + } + + private static GameplayAdmissionPointerSnapshot authorityPointer( + String worldSlug, + String realmSlug, + long tenantId, + long gameInstanceId, + boolean visible, + boolean publicProductionRealm) { + java.util.UUID realmId = + java.util.UUID.nameUUIDFromBytes( + ("realm/" + tenantId + "/" + worldSlug + "/" + realmSlug) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + return new GameplayAdmissionPointerSnapshot( + worldSlug, + worldSlug + " World", + realmSlug, + realmSlug + " Realm", + tenantId, + gameInstanceId, + 1L, + visible, + publicProductionRealm, + false, + "SHARED", + "ALLOW_NEW", + 1L, + realmId, + java.util.UUID.nameUUIDFromBytes( + ("namespace/" + realmId).getBytes(java.nio.charset.StandardCharsets.UTF_8))); + } + @Test void pingReturnsPong() { PingService pingService = Mockito.mock(PingService.class); @@ -562,6 +607,111 @@ void listGameplayWorldsRejectsAnIncompleteAuthorityPointer() { Mockito.verify(pointerAuthorityService).listPointers(); } + @Test + void gameplayDiscoveryRejectsPublicRealmsAcrossDifferentWorldsForOneTenant() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn( + List.of( + authorityPointer("alpha", "live", 7L, 44L, true, true), + authorityPointer("beta", "live", 7L, 55L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + ListGameplayWorldsResponse worlds = listGameplayWorlds(service); + ListGameplayRealmsResponse realms = listGameplayRealms(service, "alpha"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", worlds.getError().getCode()); + assertEquals(0, worlds.getWorldsCount()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", realms.getError().getCode()); + assertEquals(0, realms.getRealmsCount()); + Mockito.verify(pointerAuthorityService, Mockito.times(2)).listPointers(); + } + + @Test + void publicAdmissionRejectsNonUniqueTenantGlobalPublicRealm() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot selectedPublicRealm = + authorityPointer("alpha", "live", 7L, 44L, true, true); + Mockito.when(pointerAuthorityService.findPointer(7L, "alpha", "live")) + .thenReturn(java.util.Optional.of(selectedPublicRealm)); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn( + List.of( + selectedPublicRealm, + authorityPointer("beta", "live", 7L, 55L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + AtomicReference response = new AtomicReference<>(); + + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("alpha") + .setRealmSlug("live") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); + assertFalse(response.get().hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService).listPointers(); + } + + @Test + void privateAdmissionDoesNotRequirePublicRealmCardinalityLookup() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot privateRealm = + authorityPointer("private", "preview", 7L, 66L, true, false); + Mockito.when(pointerAuthorityService.findPointer(7L, "private", "preview")) + .thenReturn(java.util.Optional.of(privateRealm)); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn( + List.of( + authorityPointer("alpha", "live", 7L, 44L, true, true), + authorityPointer("beta", "live", 7L, 55L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + AtomicReference response = new AtomicReference<>(); + + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("private") + .setRealmSlug("preview") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertFalse(response.get().hasError()); + assertEquals("66", response.get().getAdmissionPointer().getGameInstanceId()); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + } + @Test void gameplayCatalogRpcReturnsCanonicalRealmData() { PingService pingService = Mockito.mock(PingService.class); From ac10c4f3f6268576bd4dd0c89b6d6c77a3cdb98b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 21:39:44 +1300 Subject: [PATCH 33/75] Keep public bootstrap JOIN closed at Gateway --- .../PublicInternalRouteBlockFilter.java | 63 ++++++++++++++++++- .../PublicInternalRouteBlockFilterTest.java | 43 +++++++++++++ 2 files changed, 103 insertions(+), 3 deletions(-) diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java index 9efae8cb34..65ff23cb37 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java @@ -1,7 +1,10 @@ package net.firedevops.firemud.springcloudgateway.filter; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.util.Set; import org.springframework.core.Ordered; +import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.server.PathContainer; import org.springframework.stereotype.Component; @@ -23,12 +26,14 @@ public class PublicInternalRouteBlockFilter implements WebFilter, Ordered { private static final PathPatternParser PATH_PATTERN_PARSER = new PathPatternParser(); private static final PathPattern UNAVAILABLE_EXTERNAL_ACCOUNT_ROUTE = PATH_PATTERN_PARSER.parse("/api/account/accounts/{accountId}/external"); + private static final PathPattern UNAVAILABLE_PUBLIC_JOIN_ROUTE = + PATH_PATTERN_PARSER.parse("/api/account/auth/bootstrap/join"); @Override public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { String path = exchange.getRequest().getPath().value(); PathContainer pathWithinApplication = exchange.getRequest().getPath().pathWithinApplication(); - if (!targetsBlockedPath(path, pathWithinApplication)) { + if (!targetsBlockedPath(exchange.getRequest().getMethod(), path, pathWithinApplication)) { return chain.filter(exchange); } exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND); @@ -40,10 +45,62 @@ public int getOrder() { return -2; } - private boolean targetsBlockedPath(String path, PathContainer pathWithinApplication) { + private boolean targetsBlockedPath( + HttpMethod method, String path, PathContainer pathWithinApplication) { String[] segments = path.split("/", -1); return targetsBlockedInternalPath(path, segments) - || targetsUnavailableExternalAccountPath(pathWithinApplication); + || targetsUnavailableExternalAccountPath(pathWithinApplication) + || targetsUnavailablePublicJoinRoute(method, path); + } + + private boolean targetsUnavailablePublicJoinRoute(HttpMethod method, String path) { + if (!HttpMethod.POST.equals(method)) { + return false; + } + String canonicalPath = canonicalizePublicRoutePath(path); + return UNAVAILABLE_PUBLIC_JOIN_ROUTE.matches(PathContainer.parsePath(canonicalPath)); + } + + private String canonicalizePublicRoutePath(String path) { + String decodedPath = decodePath(path); + StringBuilder canonicalPath = new StringBuilder(decodedPath.length()); + String[] rawSegments = decodedPath.replace('\\', '/').split("/", -1); + for (String rawSegment : rawSegments) { + String segment = rawSegment; + int matrixParameterStart = segment.indexOf(';'); + if (matrixParameterStart >= 0) { + segment = segment.substring(0, matrixParameterStart); + } + if (segment.isEmpty() || ".".equals(segment)) { + continue; + } + if ("..".equals(segment)) { + int previousSeparator = canonicalPath.lastIndexOf("/"); + if (previousSeparator >= 0) { + canonicalPath.setLength(previousSeparator); + } + continue; + } + canonicalPath.append('/').append(segment); + } + return canonicalPath.length() == 0 ? "/" : canonicalPath.toString(); + } + + private String decodePath(String path) { + String decodedPath = path; + for (int pass = 0; pass < 8; pass++) { + try { + String nextPath = + URLDecoder.decode(decodedPath.replace("+", "%2B"), StandardCharsets.UTF_8); + if (nextPath.equals(decodedPath)) { + return decodedPath; + } + decodedPath = nextPath; + } catch (IllegalArgumentException exception) { + return path; + } + } + return decodedPath; } private boolean targetsBlockedInternalPath(String path, String[] segments) { diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java index 190b5b1be0..8b2911c920 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java @@ -4,6 +4,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Test; +import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; @@ -287,6 +288,27 @@ void allowsNormalPublicApiRoute() { assertThat(exchange.getResponse().getStatusCode()).isNull(); } + @Test + void blocksPublicBootstrapJoinRoute() { + assertBlockedPost("/api/account/auth/bootstrap/join"); + } + + @Test + void blocksPublicBootstrapJoinRouteAfterPathCanonicalization() { + assertBlockedPost("/api/account//auth/bootstrap/join/"); + assertBlockedPost("/api/account/auth/bootstrap/join;probe=true"); + assertBlockedPost("/api/account/auth/bootstrap/../bootstrap/join"); + assertBlockedPost("/api%252Faccount/auth/bootstrap/join"); + assertBlockedPost("/api/account/auth/bootstrap/%256Aoin"); + } + + @Test + void allowsOtherAccountAuthRoutesAndNonPostJoinPath() { + assertAllowed(HttpMethod.POST, "/api/account/auth/player-bootstrap"); + assertAllowed(HttpMethod.POST, "/api/account/auth/connect-token"); + assertAllowed(HttpMethod.GET, "/api/account/auth/bootstrap/join"); + } + @Test void allowsGameplayWebSocketPath() { MockServerWebExchange exchange = @@ -305,4 +327,25 @@ private WebFilterChain chain(AtomicBoolean chainCalled) { return Mono.empty(); }; } + + private void assertBlockedPost(String path) { + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post(path).build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).as(path).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).as(path).isEqualTo(HttpStatus.NOT_FOUND); + } + + private void assertAllowed(HttpMethod method, String path) { + MockServerWebExchange exchange = + MockServerWebExchange.from(MockServerHttpRequest.method(method, path).build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).as(path).isTrue(); + assertThat(exchange.getResponse().getStatusCode()).as(path).isNull(); + } } From 13cd5f1edf8173f0473bb90a2d275610b21b3454 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 21:42:29 +1300 Subject: [PATCH 34/75] Prove retained pointer audit cannot impersonate current evidence --- ...yAdmissionPointerAuthorityServiceTest.java | 13 ++- ...missionPointerControlPlaneServiceTest.java | 83 +++++++++++++++++++ 2 files changed, 93 insertions(+), 3 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index 35295ccf69..5d2f82aa1d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -365,20 +365,27 @@ void listPointerAuditExposesPersistedCatalogRevision() { } @Test - void listPointerAuditLeavesHistoricalIdentityAbsent() { + void listPointerAuditPreservesPreV7UnknownRevisionAndIdentity() { GameplayAdmissionPointerEvent historicalEvent = new GameplayAdmissionPointerEvent(); historicalEvent.setWorldSlug("demo"); historicalEvent.setRealmSlug("production"); + historicalEvent.setWorldDisplayName("Demo World"); + historicalEvent.setRealmDisplayName("Live Realm"); historicalEvent.setTenantId(1L); historicalEvent.setGameInstanceId(7L); historicalEvent.setPointerVersion(1L); - historicalEvent.setCatalogRevision(1L); + historicalEvent.setStateScope("SHARED"); + historicalEvent.setCharacterCreationPolicy("ALLOW_NEW"); + historicalEvent.setActorPrincipal("legacy-operator"); + historicalEvent.setReason("retained pre-V7 event"); + historicalEvent.setControlPlaneRequestId("legacy-request"); + historicalEvent.setOccurredAt(java.time.Instant.parse("2026-09-29T00:00:00Z")); when(eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( 1L, "demo", "production")) .thenReturn(List.of(historicalEvent)); var auditEntry = service.listPointerAudit(1L, "demo", "production").getFirst(); - assertEquals(1L, auditEntry.catalogRevision()); + assertNull(auditEntry.catalogRevision()); assertNull(auditEntry.realmId()); assertNull(auditEntry.playableStateNamespaceId()); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java new file mode 100644 index 0000000000..6a9f692198 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; +import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.service.VersionUpgradePreparationService; +import org.junit.jupiter.api.Test; + +class GameSessionAdmissionPointerControlPlaneServiceTest { + @Test + void listRejectsRetainedPreV7AuditWithUnknownRevisionAndIdentity() { + GameplayAdmissionPointerRepository pointerRepository = + mock(GameplayAdmissionPointerRepository.class); + GameplayAdmissionPointerEventRepository eventRepository = + mock(GameplayAdmissionPointerEventRepository.class); + + UUID realmId = UUID.fromString("11111111-1111-1111-1111-111111111111"); + UUID namespaceId = UUID.fromString("22222222-2222-2222-2222-222222222222"); + GameplayAdmissionPointer currentPointer = new GameplayAdmissionPointer(); + currentPointer.setWorldSlug("demo"); + currentPointer.setWorldDisplayName("Demo World"); + currentPointer.setRealmSlug("production"); + currentPointer.setRealmDisplayName("Live Realm"); + currentPointer.setTenantId(1L); + currentPointer.setGameInstanceId(7L); + currentPointer.setPointerVersion(1L); + currentPointer.setCatalogRevision(1L); + currentPointer.setRealmId(realmId); + currentPointer.setPlayableStateNamespaceId(namespaceId); + currentPointer.setVisible(true); + currentPointer.setPublicProductionRealm(true); + currentPointer.setRequiresCharacterSelection(false); + currentPointer.setStateScope("SHARED"); + currentPointer.setCharacterCreationPolicy("ALLOW_NEW"); + + GameplayAdmissionPointerEvent retainedPreV7Event = new GameplayAdmissionPointerEvent(); + retainedPreV7Event.setWorldSlug("demo"); + retainedPreV7Event.setWorldDisplayName("Demo World"); + retainedPreV7Event.setRealmSlug("production"); + retainedPreV7Event.setRealmDisplayName("Live Realm"); + retainedPreV7Event.setTenantId(1L); + retainedPreV7Event.setGameInstanceId(7L); + retainedPreV7Event.setPointerVersion(1L); + retainedPreV7Event.setVisible(true); + retainedPreV7Event.setPublicProductionRealm(true); + retainedPreV7Event.setRequiresCharacterSelection(false); + retainedPreV7Event.setStateScope("SHARED"); + retainedPreV7Event.setCharacterCreationPolicy("ALLOW_NEW"); + retainedPreV7Event.setActorPrincipal("legacy-operator"); + retainedPreV7Event.setReason("retained pre-V7 event"); + retainedPreV7Event.setControlPlaneRequestId("legacy-request"); + retainedPreV7Event.setOccurredAt(Instant.parse("2026-09-29T00:00:00Z")); + // Pre-V7 history has no evidence for these fields; it must not be upgraded by inference. + + when(pointerRepository.findAllByOrderByWorldSlugAscRealmSlugAsc()) + .thenReturn(List.of(currentPointer)); + when( + eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( + 1L, "demo", "production")) + .thenReturn(List.of(retainedPreV7Event)); + + DatabaseGameplayAdmissionPointerAuthorityService authorityService = + new DatabaseGameplayAdmissionPointerAuthorityService(pointerRepository, eventRepository); + GameSessionAdmissionPointerControlPlaneService controlPlaneService = + new GameSessionAdmissionPointerControlPlaneService( + mock(GameInstanceRepository.class), + authorityService, + mock(VersionUpgradePreparationService.class)); + + assertThrows( + AdmissionPointerAuditUnavailableException.class, + controlPlaneService::listAdmissionPointers); + } +} From 15d48e065af10133d69c0eac0a1a88e713dead58 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:05:51 +1300 Subject: [PATCH 35/75] fix: validate both hosted workload controller ingress policies --- .../preview/validate-preview-artifact.py | 44 ++++++------- dev-tools/hosted/shared/README.md | 4 +- .../hosted/shared/ensure-grpc-tls-secret.sh | 4 +- .../test_validate_preview_artifact.py | 63 ++++++++++++++----- 4 files changed, 76 insertions(+), 39 deletions(-) diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index 0eddbf3e7d..e983c088a9 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -83,6 +83,7 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: "internal-services", "internal-services-egress", "account-service-controller-ingress", + "game-session-service-controller-ingress", "spring-cloud-gateway-ingress", "spring-cloud-gateway-egress", "tcp-proxy-service-egress", @@ -230,8 +231,11 @@ def _expected_names_for_mode(certificate_identity_mode: str) -> dict[str, set[st kind: set(names) for kind, names in EXPECTED_NAMES.items() } if certificate_identity_mode == "standalone": - expected_names["NetworkPolicy"].discard( - "account-service-controller-ingress" + expected_names["NetworkPolicy"].difference_update( + { + "account-service-controller-ingress", + "game-session-service-controller-ingress", + } ) return expected_names @@ -1826,26 +1830,24 @@ def validate_network_policies( }, } if certificate_identity_mode == "hosted-controller": - controller_policy = policies["account-service-controller-ingress"] - spec = _require_mapping( - controller_policy.get("spec"), - "NetworkPolicy/account-service-controller-ingress.spec", - ) - if spec.get("podSelector") != {"matchLabels": {"app": "account-service"}}: - fail( - "NetworkPolicy/account-service-controller-ingress selects an unsafe workload" - ) - if spec.get("policyTypes") != ["Ingress"]: - fail( - "NetworkPolicy/account-service-controller-ingress must only govern ingress" - ) - expected_ingress = [ - {"from": [expected_from], "ports": [{"protocol": "TCP", "port": 6565}]} - ] - if spec.get("ingress") != expected_ingress: - fail( - "NetworkPolicy/account-service-controller-ingress has an unsafe exception" + for workload in ("account-service", "game-session-service"): + policy_name = f"{workload}-controller-ingress" + spec = _require_mapping( + policies[policy_name].get("spec"), + f"NetworkPolicy/{policy_name}.spec", ) + if spec.get("podSelector") != {"matchLabels": {"app": workload}}: + fail(f"NetworkPolicy/{policy_name} selects an unsafe workload") + if spec.get("policyTypes") != ["Ingress"]: + fail(f"NetworkPolicy/{policy_name} must only govern ingress") + expected_ingress = [ + { + "from": [expected_from], + "ports": [{"protocol": "TCP", "port": 6565}], + } + ] + if spec.get("ingress") != expected_ingress: + fail(f"NetworkPolicy/{policy_name} has an unsafe exception") gateway_ingress = _require_mapping( policies["spring-cloud-gateway-ingress"].get("spec"), diff --git a/dev-tools/hosted/shared/README.md b/dev-tools/hosted/shared/README.md index 7bfbbf389c..79cdf2916e 100644 --- a/dev-tools/hosted/shared/README.md +++ b/dev-tools/hosted/shared/README.md @@ -20,10 +20,10 @@ These scripts are shared because they manage infrastructure or validation behavi - creates or updates the shared GHCR image-pull secret in the target namespace - `ensure-grpc-tls-secret.sh` - - preserves the shared bundle for non-publication workloads; in standalone mode it validates the five issuer-projected publication leaves, adds only their public CA certificate to shared trust, and removes retained runtime-local signing material after replacement is proven + - preserves the shared bundle for the four remaining shared-leaf workloads; in standalone mode it validates seven issuer-projected workload leaves, adds their common public CA certificate to shared trust, and removes retained runtime-local signing material after replacement is proven - `ensure-standalone-grpc-certificates.sh` - - uses the scoped certificate-writer credential to request the five fixed `firemud-ca-issuer` publication Certificates in `dev` or a canonical `pr-N` namespace, then waits for Ready without reading their private keys + - uses the scoped certificate-writer credential to request seven fixed `firemud-ca-issuer` workload Certificates (five publication plus Account and Game Session) in `dev` or a canonical `pr-N` namespace, then waits for Ready without reading their private keys - `wait-for-runtime-images.sh` - for a pull request, waits for a `runtime-images.yml` run whose exact base, head, and test-merge identities match, then waits for the trusted publisher to publish the immutable `pr-merge-` tag diff --git a/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh b/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh index 144e57940d..bd6809d826 100644 --- a/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh +++ b/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh @@ -279,8 +279,8 @@ if ((shared_snapshot_status == 0)); then "${shared_rotation_resources[*]}" || exit 1 assert_key_matches_certificate "$shared_cert" "$shared_key" else - # The legacy shared bundle is still required by the six non-publication - # workloads. Generate it once, then preserve its leaf on every later run. + # The legacy shared bundle is still required by the four remaining + # shared-leaf workloads. Generate it once, then preserve its leaf on every later run. "$legacy_generator" "$cert_dir" for required_file in ca.crt client.crt client.key ca.key; do [[ -s "$cert_dir/$required_file" ]] || { diff --git a/dev-tools/validation/test_validate_preview_artifact.py b/dev-tools/validation/test_validate_preview_artifact.py index 1ba74facfb..b99a956c61 100644 --- a/dev-tools/validation/test_validate_preview_artifact.py +++ b/dev-tools/validation/test_validate_preview_artifact.py @@ -1883,21 +1883,22 @@ def _policy_documents(self, mode): for name, spec in self.validator.EXPECTED_INTERNAL_NETWORK_POLICY_SPECS.items() ] if mode == "hosted-controller": - documents.append( - self._policy_document( - "account-service-controller-ingress", - { - "podSelector": {"matchLabels": {"app": "account-service"}}, - "policyTypes": ["Ingress"], - "ingress": [ - { - "from": [controller_from], - "ports": [{"protocol": "TCP", "port": 6565}], - } - ], - }, + for workload in ("account-service", "game-session-service"): + documents.append( + self._policy_document( + f"{workload}-controller-ingress", + { + "podSelector": {"matchLabels": {"app": workload}}, + "policyTypes": ["Ingress"], + "ingress": [ + { + "from": [controller_from], + "ports": [{"protocol": "TCP", "port": 6565}], + } + ], + }, + ) ) - ) documents.extend( [ self._policy_document( @@ -2066,6 +2067,40 @@ def test_mode_specific_policy_sets_and_rules_are_closed(self): with self.assertRaisesRegex(ValueError, "runtime NetworkPolicy set is not closed"): self.validator.validate_network_policies(missing_account, "hosted-controller") + missing_game_session = [ + document + for document in hosted + if document["metadata"]["name"] + != "game-session-service-controller-ingress" + ] + with self.assertRaisesRegex(ValueError, "runtime NetworkPolicy set is not closed"): + self.validator.validate_network_policies( + missing_game_session, "hosted-controller" + ) + + for field, value, message in ( + ( + "podSelector", + {"matchLabels": {"app": "account-service"}}, + "selects an unsafe workload", + ), + ("policyTypes", ["Ingress", "Egress"], "must only govern ingress"), + ("ingress", [], "has an unsafe exception"), + ): + with self.subTest(mode="hosted-controller", game_session_field=field): + malformed = copy.deepcopy(hosted) + policy = next( + document + for document in malformed + if document["metadata"]["name"] + == "game-session-service-controller-ingress" + ) + policy["spec"][field] = value + with self.assertRaisesRegex(ValueError, message): + self.validator.validate_network_policies( + malformed, "hosted-controller" + ) + for mode in ("standalone", "hosted-controller"): with self.subTest(mode=mode, case="missing gateway egress"): missing_gateway_egress = [ From 01f18517ca17cf8d6f659a9fe65f96c37d8dd298 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:33:37 +1300 Subject: [PATCH 36/75] Issue distinct Social Groups workload identity across hosted delivery --- ...ime-and-certificate-identity-lifecycles.md | 6 +- .../infrastructure/deployment-environments.md | 12 ++-- .../environment-and-secrets-overview.md | 4 +- .../architecture/system-architecture-cicd.md | 2 +- .../system-architecture-deployment-runbook.md | 2 +- .../platform-operations-and-delivery.md | 6 +- dev-tools/deploy/preflight.py | 25 +++++---- .../preview/validate-preview-artifact.py | 6 +- .../preview/wait-for-hosted-identity.sh | 1 + dev-tools/hosted/shared/README.md | 4 +- .../hosted/shared/ensure-grpc-tls-secret.sh | 1 + .../ensure-standalone-grpc-certificates.sh | 1 + dev-tools/tests/dev-demo-workflow-contract.sh | 2 + .../tests/ensure-grpc-tls-secret-contract.sh | 13 +++-- ...d-identity-controller-manifest-contract.sh | 45 ++++++++++----- ...d-identity-controller-workflow-contract.sh | 3 + dev-tools/tests/preflight-contract.sh | 52 ++++++++++++++++- .../standalone-grpc-certificates-contract.sh | 8 ++- .../trust-bootstrap-issuance-contract.sh | 11 +++- k8s/base/social-groups-service.yaml | 24 +++++++- k8s/helm/README.md | 2 +- k8s/helm/firemud/templates/_helpers.tpl | 2 +- k8s/hosted-identity-controller/README.md | 2 +- k8s/hosted-identity-controller/admission.yaml | 56 +++++++++++-------- k8s/hosted-identity-controller/crd.yaml | 1 + k8s/trust-bootstrap/README.md | 2 +- k8s/trust-bootstrap/issuance-admission.yaml | 28 ++++++---- .../contract/HostedIdentityContract.java | 3 + .../CertificateMaterialService.java | 18 ++++++ .../CertificateResourceFactory.java | 12 ++++ .../kubernetes/DeploymentRolloutService.java | 14 +++++ .../HostedIdentityScopeService.java | 5 ++ .../model/EnvironmentIdentityPlan.java | 17 +++++- .../HostedEnvironmentIdentityStatus.java | 9 +++ .../reconcile/HostedIdentityReconciler.java | 17 +++++- .../security/EnvironmentIdentityPlanner.java | 9 +++ .../CertificateMaterialServiceTest.java | 23 +++++++- .../CertificateResourceFactoryTest.java | 32 ++++++++++- .../DeploymentRolloutServiceTest.java | 49 +++++++++++++++- .../HostedIdentityScopeServiceTest.java | 4 +- .../HostedIdentityTestFixtures.java | 20 +++++++ .../SecretProjectionServiceTest.java | 6 +- .../HostedIdentityReconcilerSafetyTest.java | 38 +++++++++++-- .../EnvironmentIdentityPlannerTest.java | 9 +++ 44 files changed, 490 insertions(+), 116 deletions(-) diff --git a/design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md b/design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md index 18a597fc30..c0a4c0110e 100644 --- a/design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md +++ b/design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md @@ -37,9 +37,9 @@ The controller establishes identity scope only through its one-time bootstrap/ad ### Runtime-first activation and explicit retirement -Runtime namespaces remain clean and disposable. A trusted lifecycle may reclaim, redeploy, release, or let a lease expire on the runtime namespace while retaining the active identity namespace. Runtime preparation creates or reuses the exact `pr-` or `dev` namespace, records the requested reviewed head and image, and allocates the bounded Telnet port. The trusted requester then applies `Active`, and the runtime lane waits for all twelve labeled, key-complete Secret projections defined by the [deployment-environment contract](../infrastructure/deployment-environments.md)—five shared-role projections and seven distinct gRPC workload projections—before application preflight, server dry-run, and deploy. Only successful deployment may record the separate deployed-head evidence consumed by readiness. A failed or incomplete identity projection blocks runtime deployment, while a failed deployment cannot make the request appear deployed. +Runtime namespaces remain clean and disposable. A trusted lifecycle may reclaim, redeploy, release, or let a lease expire on the runtime namespace while retaining the active identity namespace. Runtime preparation creates or reuses the exact `pr-` or `dev` namespace, records the requested reviewed head and image, and allocates the bounded Telnet port. The trusted requester then applies `Active`, and the runtime lane waits for all thirteen labeled, key-complete Secret projections defined by the [deployment-environment contract](../infrastructure/deployment-environments.md)—five shared-role projections and eight distinct gRPC workload projections—before application preflight, server dry-run, and deploy. Only successful deployment may record the separate deployed-head evidence consumed by readiness. A failed or incomplete identity projection blocks runtime deployment, while a failed deployment cannot make the request appear deployed. -A PR close or merge follows a runtime-first path: it requests `Retired` only after runtime cleanup has observed the exact runtime Namespace `NotFound` result, so that path gives the controller no live runtime to shut down. A trusted explicit identity-removal request for a live runtime follows a retirement-first path: it may set `Retired` while the runtime still exists, after which the controller must terminate Gateway and TCP Proxy and observe both bridge workloads at zero before the trusted runtime lifecycle deletes the namespace and proves exact `NotFound`. Retained identity deletion remains blocked until that runtime absence proof. Before deleting retained material, the controller accounts for all twelve declared projections: the five shared-role projections for (1) [public ingress TLS](../system-architecture-security.md#tls-termination-for-gateway), (2) [public Telnet TLS](../system-architecture-protocol-bridging.md#public-telnet-tls-modes), (3) the [Gateway internal WebSocket server](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), (4) the [TCP Proxy bridge client](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), and (5) the [shared gRPC transport bundle](./adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md#mtls-identity-and-certificate-lifecycle), plus seven distinct gRPC workload projections for the five publication services, Account, and Game Session. Runtime cleanup and identity retirement remain separate operations. If the provider or lifecycle API cannot reliably establish the requested lifecycle state, the safe result is to retain identity, report the lifecycle as incomplete or uncertain, and fail closed; an uncertain response never triggers broader deletion. +A PR close or merge follows a runtime-first path: it requests `Retired` only after runtime cleanup has observed the exact runtime Namespace `NotFound` result, so that path gives the controller no live runtime to shut down. A trusted explicit identity-removal request for a live runtime follows a retirement-first path: it may set `Retired` while the runtime still exists, after which the controller must terminate Gateway and TCP Proxy and observe both bridge workloads at zero before the trusted runtime lifecycle deletes the namespace and proves exact `NotFound`. Retained identity deletion remains blocked until that runtime absence proof. Before deleting retained material, the controller accounts for all thirteen declared projections: the five shared-role projections for (1) [public ingress TLS](../system-architecture-security.md#tls-termination-for-gateway), (2) [public Telnet TLS](../system-architecture-protocol-bridging.md#public-telnet-tls-modes), (3) the [Gateway internal WebSocket server](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), (4) the [TCP Proxy bridge client](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), and (5) the [shared gRPC transport bundle](./adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md#mtls-identity-and-certificate-lifecycle), plus eight distinct gRPC workload projections for the five publication services, Account, Game Session, and Social Groups. Runtime cleanup and identity retirement remain separate operations. If the provider or lifecycle API cannot reliably establish the requested lifecycle state, the safe result is to retain identity, report the lifecycle as incomplete or uncertain, and fail closed; an uncertain response never triggers broader deletion. If retirement observes a live runtime profile that differs from the profile already recorded in controller status, it reports `RuntimeIdentityChanged`, preserves the previously observed profile, and never refreshes retirement authority from the mismatched live values. Recovery belongs to the trusted lifecycle: it removes the whole disposable runtime namespace and obtains the runtime-first exact `NotFound` proof. A later retirement reconcile can then continue deleting the retained identity through the normal ownership-checked path. This recovery does not permit manual deletion of retained identity material and does not weaken the live-runtime bridge-shutdown or runtime-absence gates. @@ -53,7 +53,7 @@ All controller-owned certificate leaves use RSA-2048 keys. The cert-manager reso ### Generation-bound readiness and certificate convergence -The controller publishes non-secret status only. A `Ready=True` result is valid only when `status.observedGeneration` equals `metadata.generation`, the live runtime namespace UID and requested head SHA match the status profile, a separately recorded post-deployment head equals that request after canonical 40-hex normalization, rollout and served proofs have converged, and non-empty revisions are present for the five shared roles and seven distinct gRPC workload roles. Account and Game Session must additionally serve their current projected leaves at the fixed gRPC endpoints; rollout counters alone are insufficient. PR preview and dev-demo preparation write only their distinct requested-head annotations; only a successful runtime deployment writes the corresponding deployed-head annotation. The workflow treats `Pending`, `Provisioning`, `WaitingForCertificate`, `RuntimeAbsent`, `Syncing`, `Verifying`, `Degraded`, `Blocked`, `Retiring`, and `Retired` as non-ready and uses the Ready condition's reason/message for failure detail. +The controller publishes non-secret status only. A `Ready=True` result is valid only when `status.observedGeneration` equals `metadata.generation`, the live runtime namespace UID and requested head SHA match the status profile, a separately recorded post-deployment head equals that request after canonical 40-hex normalization, rollout and served proofs have converged, and non-empty revisions are present for the five shared roles and eight distinct gRPC workload roles. Account, Game Session, and Social Groups must additionally serve their current projected leaves at the fixed gRPC endpoints; rollout counters alone are insufficient. PR preview and dev-demo preparation write only their distinct requested-head annotations; only a successful runtime deployment writes the corresponding deployed-head annotation. The workflow treats `Pending`, `Provisioning`, `WaitingForCertificate`, `RuntimeAbsent`, `Syncing`, `Verifying`, `Degraded`, `Blocked`, `Retiring`, and `Retired` as non-ready and uses the Ready condition's reason/message for failure detail. Certificate issuance and replacement for one identity proceed through a serialized lifecycle. The controller and issuer path validate actual served certificates and keys, including validity, required SANs, key correspondence without exposing private material, expected issuer and trust chain, monotonic identity generation, and distinct SPKI for intentional replacement. After issuance, affected ingress, Telnet, and, where applicable, gRPC consumers must reload or restart and serve or accept the new identity. A consumer that has not converged leaves the lifecycle failed or pending and does not authorize removal of the prior usable identity solely because a new resource exists. diff --git a/design/architecture/infrastructure/deployment-environments.md b/design/architecture/infrastructure/deployment-environments.md index 8a7dd7352e..b041d00678 100644 --- a/design/architecture/infrastructure/deployment-environments.md +++ b/design/architecture/infrastructure/deployment-environments.md @@ -187,7 +187,7 @@ In production, FireMUD is deployed into Kubernetes (e.g., AWS EKS, Google GKE, o render matching checked-in baseline policies from the Helm chart using chart-specific selectors for the preview stack's labels. - Configuration and secrets are managed through ConfigMaps and Secrets. -- On the explicit `hosted-controller` target path for hosted preview/dev-demo, the in-cluster controller owns the `Certificate` resources for the public ingress, public Telnet, Gateway-internal WebSocket server, and TCP Proxy bridge client leaves, which **cert-manager** issues. The controller separately generates the shared gRPC mTLS bundle from the fixed `firemud-system/firemud-grpc-ca` Secret, then requests seven per-workload gRPC leaves from `firemud-ca-issuer` (five publication workloads, Account, and Game Session) and materializes and reconciles twelve runtime Secret projections (the five shared-role projections plus seven distinct `firemud-grpc-` projections). In the default/current `standalone` path, Helm renders the chart-owned public `-telnet-tls` `Certificate` when Telnet TLS is enabled, plus chart-owned `Certificate` resources for the two internal bridge leaves. The trusted standalone Certificate writer also requests the seven fixed per-workload gRPC leaves for preview and dev-demo; **cert-manager** renews them into the workload Secrets while the runtime workflow retains only the legacy shared bundle and public trust anchors. The hosted identity controller remains dormant. Controller non-secret Ready evidence does not replace served-certificate or player-facing preflight proof. This remains local/static target behavior until live controller activation and consumer-convergence proof exists. +- On the explicit `hosted-controller` target path for hosted preview/dev-demo, the in-cluster controller owns the `Certificate` resources for the public ingress, public Telnet, Gateway-internal WebSocket server, and TCP Proxy bridge client leaves, which **cert-manager** issues. The controller separately generates the shared gRPC mTLS bundle from the fixed `firemud-system/firemud-grpc-ca` Secret, then requests eight per-workload gRPC leaves from `firemud-ca-issuer` (five publication workloads, Account, Game Session, and Social Groups) and materializes and reconciles thirteen runtime Secret projections (the five shared-role projections plus eight distinct `firemud-grpc-` projections). In the default/current `standalone` path, Helm renders the chart-owned public `-telnet-tls` `Certificate` when Telnet TLS is enabled, plus chart-owned `Certificate` resources for the two internal bridge leaves. The trusted standalone Certificate writer also requests the eight fixed per-workload gRPC leaves for preview and dev-demo; **cert-manager** renews them into the workload Secrets while the runtime workflow retains only the legacy shared bundle and public trust anchors. The hosted identity controller remains dormant. Controller non-secret Ready evidence does not replace served-certificate or player-facing preflight proof. This remains local/static target behavior until live controller activation and consumer-convergence proof exists. - The cluster uses **IPVS** (or a similar load-balancing mode) to route service traffic efficiently. - Redis is deployed as **two logical roles** in both Kubernetes and Docker Compose (see [Redis Architecture](../system-architecture-redis.md)): - A **Coordination Redis** deployment runs as a clustered StatefulSet with automatic failover in production and smaller clusters in non-production. It uses AOF, persistent volumes, and `noeviction` in player-facing environments to preserve volatile coordination state across normal rollouts and pod restarts within the documented tail-loss envelope; Redis is not the authoritative recovery or audit log. AOF, persistent volumes, and `noeviction` alone are insufficient for player-facing replay safety: the deployment must also satisfy the [ADR 0029 replay-readiness contract](../decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), including Redis 7.2+, ACL isolation, reserved capacity and an admission-readiness threshold, atomic marker consumption, configured `WAITAOF` local/replica acknowledgement thresholds, and a shared reset/uncertain-durability quarantine fence. A profile that cannot prove those controls is not eligible to admit new player handshakes. @@ -322,11 +322,11 @@ FireMUD's preview environment is a hosted single-node k3s cluster intended for r Hosted Helm values select certificate identity explicitly at `previewStack.certificateIdentity.mode`. A missing mode means `standalone`; the only accepted explicit values are `standalone` and `hosted-controller`. Malformed, duplicate, non-string, or unknown mode configuration is fatal, and selecting `hosted-controller` never falls back to workflow-created certificate identity. This keeps the controller and its authority dormant before activation while preserving existing standalone deployments. -For a standalone PR preview, the credential-free render artifact excludes PR-authored `Certificate` resources. After creating the exact runtime namespace, the trusted default-branch consumer creates fixed cert-manager `Certificate` resources for the public Telnet leaf (`pr-N-telnet-tls`, `letsencrypt-prod`), Gateway-internal WebSocket server (`pr-N-gateway-internal-ws`, `firemud-ca-issuer`), TCP Proxy bridge client (`pr-N-tcp-proxy-bridge`, `firemud-ca-issuer`), and seven workload leaves (`pr-N-grpc-`, `firemud-ca-issuer`): the five publication workloads plus Account and Game Session. It waits for issuance and key-complete Secrets before applying the sanitized runtime artifact. Names, issuers, DNS and URI identities are derived from the validated PR number and fixed trust contract, never from PR-controlled Certificate manifests. The dev-demo standalone writer uses the same fixed workload Certificate contract under namespace `dev`; hosted-controller mode uses only controller projections. +For a standalone PR preview, the credential-free render artifact excludes PR-authored `Certificate` resources. After creating the exact runtime namespace, the trusted default-branch consumer creates fixed cert-manager `Certificate` resources for the public Telnet leaf (`pr-N-telnet-tls`, `letsencrypt-prod`), Gateway-internal WebSocket server (`pr-N-gateway-internal-ws`, `firemud-ca-issuer`), TCP Proxy bridge client (`pr-N-tcp-proxy-bridge`, `firemud-ca-issuer`), and eight workload leaves (`pr-N-grpc-`, `firemud-ca-issuer`): the five publication workloads plus Account, Game Session, and Social Groups. It waits for issuance and key-complete Secrets before applying the sanitized runtime artifact. Names, issuers, DNS and URI identities are derived from the validated PR number and fixed trust contract, never from PR-controlled Certificate manifests. The dev-demo standalone writer uses the same fixed workload Certificate contract under namespace `dev`; hosted-controller mode uses only controller projections. The internal preview CA is not installed while a legacy preview credential can read its private-key Secret or create signing requests or issuer aliases. Its only Kubernetes private-key copies are `firemud-system/firemud-grpc-ca` and `cert-manager/firemud-grpc-ca`; no runtime namespace receives a CA private key. Trusted namespace management, namespace-local runtime deployment, fixed standalone Certificate writing, hosted identity requesting, and recovery use distinct scoped credentials. The runtime and Certificate writers are bound only in the validated runtime namespace. Fail-closed admission binds the canonical internal issuer, its two protected CA Secret copies, exact standalone and retained Certificate shapes (including each gRPC workload SAN and Secret mapping), and cert-manager-generated CertificateRequests; cert-manager's built-in auto-approval is not itself an authorization boundary. Before any CA material is installed, operators prove live denial of direct and alias issuance paths and rotate the former `preview-deployer` credential. The CA recovery copy belongs to a separate `develop`-restricted recovery-only GitHub Environment and is restored only by its scoped trusted procedure. The same procedure can be instantiated with different credentials and trust material for a future production boundary, but this preview preparation does not establish production readiness. See the [preview trust bootstrap sequence](../../../k8s/trust-bootstrap/README.md). -The canonical hosted identity API is `platform.firemud.dev/v1alpha1` `HostedEnvironmentIdentity` in `firemud-system`, named `pr-` or `dev-demo`, with only `spec.desiredState: Active|Retired`. The in-cluster controller owns identity namespaces, derived hosts, certificate resources, Secret projections, and non-secret status. A trusted workflow first validates the PR-produced sanitized render artifact and waits for its exact base/head/merge-bound runtime images without holding the shared preview-allocation lifecycle lock. Under that non-cancelling lock it revalidates the target, allocates capacity and, only for `public` mode, the Telnet port, creates the disposable runtime namespace, and records the requested base SHA, head SHA, merge SHA, and image tag before requesting `Active`. It then waits for all twelve labeled, key-complete runtime Secret projections: five shared-role projections (`pr--tls`, `pr--telnet-tls`, `pr--gateway-internal-ws`, `pr--tcp-proxy-bridge`, and `firemud-grpc-tls`) and seven distinct workload projections (the five publication workloads plus `firemud-grpc-account-service` and `firemud-grpc-game-session-service`). It applies the validated runtime and records the same tuple as deployed evidence. The controller validates and consumes the trusted lifecycle's public Telnet allocation, or the private profile's zero sentinel; it does not derive or overwrite either value. Post-apply identity, rollout, and mode-specific verification runs after the mutation lock is released, revalidating the exact PR source tuple around its waits so stale verification cannot publish success; only after those checks and the exact Namespace UID fence succeed does the workflow annotate the live namespace with the proof-complete tuple and UID. The fixed dev-demo path also requires all twelve labeled, key-complete projections before Helm. Only a successful runtime apply may write the deployed tuple; controller transport readiness still requires the normalized requested and deployed head values to match, while the trusted preview lifecycle and reconciler require the complete namespace tuple, proof annotations, and current Namespace UID to match. Identity provisioning failure therefore blocks deployment without giving PR-controlled rendering any cluster, runtime, or identity credential, while a failed deployment cannot make the requested preview appear deployed. +The canonical hosted identity API is `platform.firemud.dev/v1alpha1` `HostedEnvironmentIdentity` in `firemud-system`, named `pr-` or `dev-demo`, with only `spec.desiredState: Active|Retired`. The in-cluster controller owns identity namespaces, derived hosts, certificate resources, Secret projections, and non-secret status. A trusted workflow first validates the PR-produced sanitized render artifact and waits for its exact base/head/merge-bound runtime images without holding the shared preview-allocation lifecycle lock. Under that non-cancelling lock it revalidates the target, allocates capacity and, only for `public` mode, the Telnet port, creates the disposable runtime namespace, and records the requested base SHA, head SHA, merge SHA, and image tag before requesting `Active`. It then waits for all thirteen labeled, key-complete runtime Secret projections: five shared-role projections (`pr--tls`, `pr--telnet-tls`, `pr--gateway-internal-ws`, `pr--tcp-proxy-bridge`, and `firemud-grpc-tls`) and eight distinct workload projections (the five publication workloads plus `firemud-grpc-account-service`, `firemud-grpc-game-session-service`, and `firemud-grpc-social-groups-service`). It applies the validated runtime and records the same tuple as deployed evidence. The controller validates and consumes the trusted lifecycle's public Telnet allocation, or the private profile's zero sentinel; it does not derive or overwrite either value. Post-apply identity, rollout, and mode-specific verification runs after the mutation lock is released, revalidating the exact PR source tuple around its waits so stale verification cannot publish success; only after those checks and the exact Namespace UID fence succeed does the workflow annotate the live namespace with the proof-complete tuple and UID. The fixed dev-demo path also requires all thirteen labeled, key-complete projections before Helm. Only a successful runtime apply may write the deployed tuple; controller transport readiness still requires the normalized requested and deployed head values to match, while the trusted preview lifecycle and reconciler require the complete namespace tuple, proof annotations, and current Namespace UID to match. Identity provisioning failure therefore blocks deployment without giving PR-controlled rendering any cluster, runtime, or identity credential, while a failed deployment cannot make the requested preview appear deployed. Post-apply identity, rollout, and mode-specific verification runs after `deploy-runtime` releases the `preview-allocation-lifecycle` lock and reacquires that lock for its final mutation/proof fence; another lifecycle job may run between deployment and verification. The reconciler suppresses duplicate repair dispatch while either the exact source `PR Preview Environment` run or its exact trusted `Trusted Hosted Identity Request` consumer is queued, running, or verifying. A Namespace-backed counter permits at most three proof-retry dispatches for one exact base/head/merge/image tuple and resets when that tuple changes; the counter and tuple are read and updated with the Namespace `resourceVersion`, and malformed evidence fails closed. These controls bound retry dispatches without claiming live proof. @@ -334,17 +334,17 @@ Post-apply identity, rollout, and mode-specific verification runs after `deploy- The trusted consumer derives one immutable exposure mode from the validated sanitized artifact before allocation or runtime mutation: `Service/tcp-proxy-service.spec.type: ClusterIP` selects `private`, and `NodePort` selects `public`; any other type, missing service, or later mode mismatch fails closed. The trusted workflow records that mode as the `firemud.dev/preview-exposure-mode` label on the runtime Namespace, not as an annotation; PR-controlled rendering cannot choose a different mode after validation. Requester credentials remain confined to the protected `trusted-hosted-cluster` workflow boundary and are used only for the canonical identity request, never exposed to the PR-controlled source or render jobs. -The bounded #2713 private proof is a parent bridge proof, not transport-complete preview acceptance. A `private` runtime must keep `tcp-proxy-service` as `ClusterIP`, have no public NodePort, and have no `firemud.dev/last-preview-telnet-port` annotation; the internal `telnetPort=0` value is a controller sentinel and is never written as a Service port. The current-head-bound controller may become `Ready` only after all twelve labeled, key-complete projections and required Gateway/TCP Proxy rollouts converge, and after served HTTPS, the private Gateway-to-TCP Proxy mutual-TLS bridge, and gRPC probes succeed. Private success therefore does not claim a public Telnet endpoint or the public gameplay smoke. +The bounded #2713 private proof is a parent bridge proof, not transport-complete preview acceptance. A `private` runtime must keep `tcp-proxy-service` as `ClusterIP`, have no public NodePort, and have no `firemud.dev/last-preview-telnet-port` annotation; the internal `telnetPort=0` value is a controller sentinel and is never written as a Service port. The current-head-bound controller may become `Ready` only after all thirteen labeled, key-complete projections and required Gateway/TCP Proxy rollouts converge, and after served HTTPS, the private Gateway-to-TCP Proxy mutual-TLS bridge, and gRPC probes succeed. Private success therefore does not claim a public Telnet endpoint or the public gameplay smoke. The `public` mode owned by #2795 retains the allocated preview NodePort and its Telnet-port annotation. It requires the same head-bound projections, rollout, HTTPS, bridge, and gRPC readiness plus the served public Telnet check and `LOGIN -> PLAY -> LOOK` smoke; a failed public check is a terminal failure for that mode. The workflow never converts a failed public deployment or smoke into `private`, and private success cannot satisfy the public mode's Telnet or ADR 0178 two-public-path obligations. The private exception is limited to this explicit parent bridge proof and does not amend the accepted public transport-complete target. -The fixed dev-demo lifecycle uses the same authority split only when `hosted-controller` is selected. It recreates and annotates the exact `dev` runtime with the requested head, image, and fixed NodePort `32016`, switches to requester credentials only for the fixed-shape `dev-demo` `Active` request, restores runtime credentials, and requires all twelve labeled, key-complete runtime projections before Helm. A distinct deployed-head annotation is written only after Helm succeeds; controller readiness requires it to match the requested head, so a failed Helm attempt cannot make the runtime look deployed. Success is recorded only after runtime rollout, generation/head-bound controller `Ready`, operator preflight, and the public TCP smoke. Its non-cancelling reconciler lets any in-progress same-head deploy candidate converge, allows at most three completed non-success deploy attempts for that exact head, reports retry exhaustion as a terminal workflow error, and does not reset a runtime already aligned by a successful deploy candidate. It checks nonterminal runs independently before walking completed history only until the latest exact candidate and its bounded retry result are known, so an older-record re-run is not hidden by a newer completed attempt. A workflow-owned run name binds each run to its action and effective target head, keeping explicit destroy and other-target deploy runs outside that deploy retry budget even when a run ends before its jobs materialize or more than one API page behind newer history. A new `develop` head receives a fresh retry budget. Explicit dev-demo destroy observes the runtime namespace as `NotFound` before requesting `Retired`, waiting for terminal retirement, and deleting the request. This does not activate the separate PR-close mutation path. +The fixed dev-demo lifecycle uses the same authority split only when `hosted-controller` is selected. It recreates and annotates the exact `dev` runtime with the requested head, image, and fixed NodePort `32016`, switches to requester credentials only for the fixed-shape `dev-demo` `Active` request, restores runtime credentials, and requires all thirteen labeled, key-complete runtime projections before Helm. A distinct deployed-head annotation is written only after Helm succeeds; controller readiness requires it to match the requested head, so a failed Helm attempt cannot make the runtime look deployed. Success is recorded only after runtime rollout, generation/head-bound controller `Ready`, operator preflight, and the public TCP smoke. Its non-cancelling reconciler lets any in-progress same-head deploy candidate converge, allows at most three completed non-success deploy attempts for that exact head, reports retry exhaustion as a terminal workflow error, and does not reset a runtime already aligned by a successful deploy candidate. It checks nonterminal runs independently before walking completed history only until the latest exact candidate and its bounded retry result are known, so an older-record re-run is not hidden by a newer completed attempt. A workflow-owned run name binds each run to its action and effective target head, keeping explicit destroy and other-target deploy runs outside that deploy retry budget even when a run ends before its jobs materialize or more than one API page behind newer history. A new `develop` head receives a fresh retry budget. Explicit dev-demo destroy observes the runtime namespace as `NotFound` before requesting `Retired`, waiting for terminal retirement, and deleting the request. This does not activate the separate PR-close mutation path. Privileged preview janitor, preview reconciler, dev-demo deploy/destroy, and dev-demo reconciler jobs accept scheduled or typed `repository_dispatch` requests rather than branch-selectable `workflow_dispatch` requests. A repository maintainer can trigger those trusted default-branch operations through `POST /repos///dispatches` with `event_type` set to `preview-janitor`, `preview-reconcile`, `dev-demo`, or `dev-demo-reconcile`; `dev-demo` accepts a validated `client_payload` with optional `action` (`deploy` or `destroy`), `head_sha`, `image_tag`, fixed `hostname`, and fixed `telnet_port`. The reconciler uses the same `dev-demo` event for exact-head retry. Manual per-PR deploy/release requests use the default-branch preview source workflow's typed `preview-deploy` or `preview-destroy` repository dispatch with a validated `client_payload` containing matching `action`, canonical `pr_number`, current `head_sha`, and fixed `preview_domain`; the source resolves the effective head-or-base image tag independently and produces only a sanitized render artifact or destroy intent for the trusted lifecycle. Priority labeling, capacity allocation, and cleanup remain trusted lifecycle decisions. Before a trusted operator activates the hosted identity controller, that operator must provision the fixed `firemud-system/firemud-grpc-ca` `Opaque` Secret with exactly `ca.crt` and `ca.key`. The configured trust-anchor value is the lowercase 64-hex SHA-256 fingerprint of the DER-encoded CA certificate. Bootstrap verifies the key shape and certificate fingerprint without printing either value; the controller independently verifies that the CA certificate and private key correspond before it issues any transport-only leaf. The controller only consumes this prerequisite and is not a CA provisioning authority. Standalone mode uses the same protected issuer for per-workload gRPC leaves: `firemud-grpc-ca` private-key copies stay in `firemud-system` and `cert-manager`, while cert-manager owns only leaf Secrets in `dev` and `pr-N` runtime namespaces. Leaf keys rotate with their Certificates; deleting a runtime namespace removes its leaf Certificates and projections without affecting the shared CA copies. -Runtime reclaim, redeploy, release, and lease expiry delete only the runtime namespace. Close/merge retirement is runtime-first: the trusted lifecycle deletes the exact runtime, requires a successful empty `--ignore-not-found` lookup proving Namespace `NotFound`, and only then requests `Retired`; lookup or deletion uncertainty retains identity and fails closed. Explicit identity removal of a live runtime is retirement-first: the trusted requester sets `Retired`, the controller scales Gateway and TCP Proxy to zero and waits for their observed shutdown, and the trusted runtime lifecycle then deletes the runtime and proves exact Namespace `NotFound`. In both paths, retained identity deletion remains blocked until the runtime is absent. Before deleting retained identity, the controller accounts for all twelve runtime Secret projections: five shared-role projections for (1) [public ingress TLS](../system-architecture-security.md#tls-termination-for-gateway), (2) [public Telnet TLS](../system-architecture-protocol-bridging.md#public-telnet-tls-modes), (3) the [Gateway internal WebSocket server](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), (4) the [TCP Proxy bridge client](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), and (5) the [shared gRPC transport bundle](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md#mtls-identity-and-certificate-lifecycle), plus seven distinct per-workload gRPC projections: the five publication workloads (`firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`), Account (`firemud-grpc-account-service`), and Game Session (`firemud-grpc-game-session-service`). Controller readiness binds the CR generation, live runtime namespace UID, exact requested and deployed head SHA pair, rollout and mode-specific served proof, and non-empty revisions for each of the five shared-role projections and each of the seven workload projections; public mode additionally requires the served Telnet probe. Canonical 40-hex SHA values are normalized before equality comparison. This controller contract is local/static proof only until a live hosted rollout; it does not alter stage or production deployment paths. +Runtime reclaim, redeploy, release, and lease expiry delete only the runtime namespace. Close/merge retirement is runtime-first: the trusted lifecycle deletes the exact runtime, requires a successful empty `--ignore-not-found` lookup proving Namespace `NotFound`, and only then requests `Retired`; lookup or deletion uncertainty retains identity and fails closed. Explicit identity removal of a live runtime is retirement-first: the trusted requester sets `Retired`, the controller scales Gateway and TCP Proxy to zero and waits for their observed shutdown, and the trusted runtime lifecycle then deletes the runtime and proves exact Namespace `NotFound`. In both paths, retained identity deletion remains blocked until the runtime is absent. Before deleting retained identity, the controller accounts for all thirteen runtime Secret projections: five shared-role projections for (1) [public ingress TLS](../system-architecture-security.md#tls-termination-for-gateway), (2) [public Telnet TLS](../system-architecture-protocol-bridging.md#public-telnet-tls-modes), (3) the [Gateway internal WebSocket server](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), (4) the [TCP Proxy bridge client](../system-architecture-security.md#tls-config-matrix-tcp-proxy-spring-cloud-gateway-websocket), and (5) the [shared gRPC transport bundle](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md#mtls-identity-and-certificate-lifecycle), plus eight distinct per-workload gRPC projections: the five publication workloads (`firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`), Account (`firemud-grpc-account-service`), Game Session (`firemud-grpc-game-session-service`), and Social Groups (`firemud-grpc-social-groups-service`). Controller readiness binds the CR generation, live runtime namespace UID, exact requested and deployed head SHA pair, rollout and mode-specific served proof, and non-empty revisions for each of the five shared-role projections and each of the eight workload projections; public mode additionally requires the served Telnet probe. Canonical 40-hex SHA values are normalized before equality comparison. This controller contract is local/static proof only until a live hosted rollout; it does not alter stage or production deployment paths. The hosted identity controller's egress boundary is exact-destination and operator-rendered. Its checked-in NetworkPolicy contains no `0.0.0.0/0` or `::/0`; trusted bootstrap substitutes validated `/32` IPv4 CIDRs for the observed `kubernetes.default` Service ClusterIP on TCP/443, the single API endpoint on TCP/6443, and the fixed public preview probe on TCP/443 plus NodePorts 32000-32016. Gateway access is separately limited to `spring-cloud-gateway` pods in the canonical preview and dev-demo namespaces on TCP/443 and TCP/8443. The observed k3s LoadBalancer path additionally requires the exact kube-system Traefik pod selector on TCP/8443 after public HTTPS DNAT, and the public TCP Proxy NodePort path requires the exact `tcp-proxy-service` selectors in those canonical namespaces on TCP/2323 after NodePort DNAT. DNS and the Account and Game Session TCP/6565 selectors remain explicit and label-scoped. `observe` and `active` bootstrap require all three addresses, require exactly one matching fixed public DNS A record, and verify the API Service and single-endpoint readback before any write; paused mode without addresses renders loopback-only deny markers. Standard NetworkPolicy may exempt traffic to the local node, and CNI post-DNAT behavior must be proven live for the public Traefik HTTPS and NodePort paths; the private proof separately needs live allow/deny evidence for its ClusterIP bridge path. This static boundary does not complete PO-3.2: live allow/deny and served Gateway↔TCP Proxy bridge proof remain required. diff --git a/design/architecture/infrastructure/environment-and-secrets-overview.md b/design/architecture/infrastructure/environment-and-secrets-overview.md index f35c83fa97..c824b0d341 100644 --- a/design/architecture/infrastructure/environment-and-secrets-overview.md +++ b/design/architecture/infrastructure/environment-and-secrets-overview.md @@ -135,7 +135,7 @@ This section describes the Kubernetes-backed environments that use the canonical - Kubernetes `ConfigMap` objects store non‑secret configuration values like host names or feature flags. - Sensitive values (database passwords, TLS private keys, and interim JWT signing bundles) are delivered through Kubernetes `Secret` objects. The public `jwt-jwks` projection is delivered separately as read-only public material; hosted preview materializes it as a `ConfigMap`. -- TLS certificates are issued by **cert-manager** and rotated automatically. The seven gRPC workload consumers (the five publication services plus Account and Game Session) use distinct leaf certificate/private-key Secrets; other gRPC workloads still use the shared leaf identity. Publication Pods use their own Secret for the leaf and key and project only `ca.crt` from the shared `firemud-grpc-tls` bundle for peer trust. The checked-in Kustomize Account and Game Session Pods use `/tls/ca.crt` from their respective leaf Secret for peer trust, while hosted Helm projects `ca.crt` from the shared bundle for these workloads too. Hosted rendering remains incomplete evidence for the full target identity boundary and is not player-facing equivalence. Services reload updated certificates using `TlsCertificateWatcher` / `GrpcServerTlsReloader`. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). +- TLS certificates are issued by **cert-manager** and rotated automatically. The eight gRPC workload consumers (the five publication services plus Account, Game Session, and Social Groups) use distinct leaf certificate/private-key Secrets; other gRPC workloads still use the shared leaf identity. Publication and Social Groups Pods use their own Secret for the leaf and key and project only `ca.crt` from the shared `firemud-grpc-tls` bundle for peer trust. The checked-in Kustomize Account and Game Session Pods use `/tls/ca.crt` from their respective leaf Secret for peer trust, while hosted Helm projects `ca.crt` from the shared bundle for these workloads too. Hosted rendering remains incomplete evidence for the full target identity boundary and is not player-facing equivalence. Services reload updated certificates using `TlsCertificateWatcher` / `GrpcServerTlsReloader`. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). - JWT authority and lifecycle are defined by [JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md). This overview records only the interim Account private-bundle mount, public JWKS mounts, and watcher delivery. - In player-facing environments (`hobby-self-hosted`, staging, production), the selected `INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK` mode allows only Account Service to consume JWT private signing material from a mounted file via `FIREMUD_AUTH_JWT_SECRET_PATH`, and only Account uses `JwtSecretWatcher` on that path; Account and every validator must consume the public JWKS projection. The selected `TARGET_NON_EXPORTABLE_SIGNER` mode has no private path or application private material and uses the same public-JWKS consumer boundary. The current `LEGACY_SECRET_DIAGNOSTIC` mode is shared-HMAC Secret/path wiring evidence only and is never player-facing authorization; inline-only or HMAC-only configuration and private-key mounts in validators are non-compliant for accepted modes. Current hosted preview is a separate HMAC/test wiring path and its hosted validation does not prove validator consumption. - Database credentials are stored in Secrets and rotated via explicit operational Jobs and runbooks (for example `db-credential-rotation` in `system-architecture-backup-recovery.md#post-restore-secret-hardening`); there is no fully automatic cadence today. @@ -446,7 +446,7 @@ The catalog document groups these variables by subsystem (PostgreSQL, Redis, TLS ## Certificate Management and Watchers -Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; see [Security Architecture](../system-architecture-security.md#cross-service-trust). Explicit local-development and throwaway-test profiles may use the documented plaintext internal transports and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. In hosted `pr-preview` and `dev-demo-cluster`, trusted certificate workflows provision distinct cert-manager-issued leaves for the five publication services, Account, and Game Session. The checked-in `k8s/base/` Pod manifests bind and mount each workload's corresponding `firemud-grpc-` Secret; they do not issue those certificates. Live leaf issuance and consumer readiness must be proven before hosted identity activation. Staging and production operators must provision all seven namespace-scoped workload Secrets and the shared `firemud-grpc-tls` trust bundle through the environment bootstrap process in the [deployment runbook](../system-architecture-deployment-runbook.md#environment-bootstrap). Other gRPC workloads continue to use the legacy shared leaf. Publication Pods read peer trust from only the public `ca.crt` key projected from `firemud-grpc-tls`, while their private identities remain in their service-specific Secrets. The checked-in Kustomize Account and Game Session Pods read peer trust from `/tls/ca.crt` in their respective leaf Secrets; hosted Helm instead uses the shared bundle's `ca.crt` projection for those workloads. The shared CA bundle must validate each of the seven distinct workload leaves as well as the shared leaf, so workloads using the shared trust projection can verify either leaf generation. Hosted rendering remains non-player-facing/non-promotion evidence. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). These certificates secure: +Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; see [Security Architecture](../system-architecture-security.md#cross-service-trust). Explicit local-development and throwaway-test profiles may use the documented plaintext internal transports and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. In hosted `pr-preview` and `dev-demo-cluster`, trusted certificate workflows provision distinct cert-manager-issued leaves for the five publication services, Account, Game Session, and Social Groups. The checked-in `k8s/base/` Pod manifests bind and mount each workload's corresponding `firemud-grpc-` Secret; they do not issue those certificates. Live leaf issuance and consumer readiness must be proven before hosted identity activation. Staging and production operators must provision all eight namespace-scoped workload Secrets and the shared `firemud-grpc-tls` trust bundle through the environment bootstrap process in the [deployment runbook](../system-architecture-deployment-runbook.md#environment-bootstrap). Other gRPC workloads continue to use the legacy shared leaf. Publication and Social Groups Pods read peer trust from only the public `ca.crt` key projected from `firemud-grpc-tls`, while their private identities remain in their service-specific Secrets. The checked-in Kustomize Account and Game Session Pods read peer trust from `/tls/ca.crt` in their respective leaf Secrets; hosted Helm instead uses the shared bundle's `ca.crt` projection for these workloads. The shared CA bundle must validate each of the eight distinct workload leaves as well as the shared leaf, so workloads using the shared trust projection can verify either leaf generation. Hosted rendering remains non-player-facing/non-promotion evidence. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). These certificates secure: - All mTLS-protected gRPC calls between services - Any internal WebSocket bridges that require mTLS (for example, the TCP Proxy Service connecting to Spring Cloud Gateway over `wss://`) diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index f432df99fa..515e0e3d9b 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -187,7 +187,7 @@ For both `standalone` and explicit `hosted-controller` preview modes, the previe On the explicit `hosted-controller` target path, that lifecycle prepares the runtime namespace, capacity allocation, bounded allocated preview Telnet NodePort (or fixed dev-demo NodePort `32016`), and requested base/head/merge/image tuple annotations with the runtime credential before a requester-only credential applies `HostedEnvironmentIdentity` `Active`. The controller materializes the retained identity namespace and cert-manager Certificate resources; it does not create disposable runtime namespaces. Only successful runtime deployment writes the distinct deployed-head annotation consumed by controller readiness; the trusted workflow writes the separate proof-complete tuple and Namespace UID only after all verification checks and the exact Namespace UID fence succeed. Close/merge cleanup deletes runtime and waits for exact `NotFound` before requesting `Retired`. All uncertain lifecycle/API results fail closed and retain identity. -Hosted verification waits for the complete readiness tuple defined by the owning [deployment-environments contract](./infrastructure/deployment-environments.md) before running the existing gameplay smoke; this CI/CD overview does not duplicate that tuple. In `hosted-controller` mode, preparation creates the runtime Namespace, records its requested base/head/merge/image tuple and port annotations, submits the active identity request, and waits for the complete labeled, key-complete controller-projected Secret set—including the distinct Account and Game Session workload leaves—before Helm installs or upgrades the runtime workloads. A deployed tuple alone is not reconciled health: after the verification checks and exact Namespace UID fence, the workflow records proof annotations containing the exact base/head/merge/image tuple and live Namespace UID, and the reconciler requires those annotations to match before it treats the preview as aligned. This ordering rule does not relax the separate bootstrap prerequisite: the fixed `firemud-system/firemud-grpc-ca` Secret must already exist before controller activation so the gRPC projection can be issued. `standalone` remains the default/current certificate-identity path until live controller activation and consumer-convergence proof exists; the `hosted-controller` target does not change stage or production deployment. +Hosted verification waits for the complete readiness tuple defined by the owning [deployment-environments contract](./infrastructure/deployment-environments.md) before running the existing gameplay smoke; this CI/CD overview does not duplicate that tuple. In `hosted-controller` mode, preparation creates the runtime Namespace, records its requested base/head/merge/image tuple and port annotations, submits the active identity request, and waits for the complete labeled, key-complete controller-projected Secret set—including the distinct Account, Game Session, and Social Groups workload leaves—before Helm installs or upgrades the runtime workloads. A deployed tuple alone is not reconciled health: after the verification checks and exact Namespace UID fence, the workflow records proof annotations containing the exact base/head/merge/image tuple and live Namespace UID, and the reconciler requires those annotations to match before it treats the preview as aligned. This ordering rule does not relax the separate bootstrap prerequisite: the fixed `firemud-system/firemud-grpc-ca` Secret must already exist before controller activation so the gRPC projection can be issued. `standalone` remains the default/current certificate-identity path until live controller activation and consumer-convergence proof exists; the `hosted-controller` target does not change stage or production deployment. Main CI remains responsible for stack startup, smoke, and cross-service verification. Preview deployment is intentionally a separate concern focused on reviewer-accessible environments. Capacity exhaustion or infrastructure failure reports preview proof as unavailable; it never records a pass, and any claimed hosted proof is bound to the current pull-request base/head/merge/image tuple. diff --git a/design/architecture/system-architecture-deployment-runbook.md b/design/architecture/system-architecture-deployment-runbook.md index 0eb513c08d..5f249c5371 100644 --- a/design/architecture/system-architecture-deployment-runbook.md +++ b/design/architecture/system-architecture-deployment-runbook.md @@ -38,7 +38,7 @@ Before the first player-facing deployment into `hobby-self-hosted`, `staging`, o 1. Provision the target namespace and registry pull credentials used by workloads. 2. Provision per-environment PostgreSQL credentials (`postgres-credentials`) and, when rotation Jobs are used, `postgres-admin-credentials`. 3. Select and record the custody state before applying workloads. The checked-in player-facing Kustomize mode is legacy Secret-backed signing plus public Secret JWKS wiring (`jwt-signing-keys` Secret and `jwt-jwks` Secret); it may appear in pre-apply diagnostics but is non-authorizing and is not an accepted player-facing custody state. Hosted preview Helm remains a separate diagnostic ConfigMap-backed path. For `INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK`, establish trusted pre-apply evidence for the pre-created interim `jwt-signing-keys` Secret, the separate interim Account-owned public `jwt-jwks` ConfigMap, and the materialization controller's name-scoped RBAC. Account has exclusive mounted/signing use of the private bundle; the materialization controller has only bounded, Account-authorized byte handling needed to materialize it and no competing signing authority. The [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md#signing-key-rotation-contract-normative) define custody and operation authority; this runbook requires every private-slot `generate`, `materialize`, `resourceVersion`-CAS, and `prune` action to use a persisted Account-authorized operation, with the controller executing only that operation and unable to choose slots or mutate desired key-ring state independently. For target non-exportable signer mode, establish trusted pre-apply evidence for the approved signer reference, target Account-owned public `jwt-jwks` ConfigMap, Account publication/CAS authority, and no private-material mount or distribution. In both accepted modes, `FIREMUD_AUTH_JWKS_PATH` is mandatory for Account and every validator; only the interim mode sets `FIREMUD_AUTH_JWT_SECRET_PATH`, while target non-exportable signer mode leaves it unset. These bootstrap records prove intended bindings and custody boundaries only; post-apply live signer, public-JWKS, and validator convergence is a separate owner-produced gate. -4. Provision cert-manager issuer bindings and certificate resources required for workload gRPC mTLS, Gateway internal mTLS WebSocket listener, TCP Proxy bridge mTLS client identity, and operator-only client identities where applicable. Also provision the five distinct publication-reader workload certificates as namespace-scoped Secrets named `firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`, plus the distinct Account and Game Session workload Secrets `firemud-grpc-account-service` and `firemud-grpc-game-session-service`. Each of these seven leaf Secrets must contain non-empty `ca.crt`, `tls.crt`, and `tls.key` entries; its `ca.crt` must establish trust for that Secret's own leaf certificate. The `firemud-grpc-tls` shared bundle must contain the shared client leaf and a `ca.crt` trust bundle that validates the shared leaf and all seven distinct workload leaves. Runtime publication-reader Pods mount their own publication Secret for the client leaf and key, and use only the shared `firemud-grpc-tls` CA bundle for trust. The checked-in Kustomize Account and Game Session Pods mount their respective full leaf Secret and use its `/tls/ca.crt` for peer trust; each of those Secrets' `ca.crt` must include the issuer trust needed for the gRPC peers those Pods call. Hosted Helm workloads use their own Secret for the leaf certificate and key and only the shared bundle's `ca.crt` for peer trust. This bootstrap requirement describes Secret contents and manifest bindings; it does not claim that issued Secrets, mounted certificates, or live workload readiness have been verified. Each workload leaf must be non-CA and use exactly the `digital signature` and `key encipherment` key usages and exactly the `server auth` and `client auth` extended key usages. For each workload, set exactly the service URI SAN `spiffe://firemud/ns//sa/` and DNS SANs ``, `.`, `..svc`, and `..svc.cluster.local`; replace `` and `` with the target namespace and that Secret's service name. In this SPIFFE URI, `` names the service workload; it is not a value derived from the Pod's Kubernetes ServiceAccount name. Keep every workload leaf and private key distinct. Use the established issuance and trust process for the environment. The [deployment-environment contract](./infrastructure/deployment-environments.md) and [ADR 0038](./decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md) own the canonical identity boundary. `dev-tools/certs/generate-dev-certs.sh --workload` documents the canonical leaf profile, while `dev-tools/hosted/shared/ensure-grpc-tls-secret.sh` shows how hosted setup validates projected cert-manager leaf files and adds their issuer CA to the shared trust bundle. These development/hosted helpers are references for certificate contents and validation; they do not replace production CA custody, issuer authorization, or the environment's approved certificate-issuance procedure. +4. Provision cert-manager issuer bindings and certificate resources required for workload gRPC mTLS, Gateway internal mTLS WebSocket listener, TCP Proxy bridge mTLS client identity, and operator-only client identities where applicable. Also provision the five distinct publication-reader workload certificates as namespace-scoped Secrets named `firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`, plus the distinct Account, Game Session, and Social Groups workload Secrets `firemud-grpc-account-service`, `firemud-grpc-game-session-service`, and `firemud-grpc-social-groups-service`. Each of these eight leaf Secrets must contain non-empty `ca.crt`, `tls.crt`, and `tls.key` entries; its `ca.crt` must establish trust for that Secret's own leaf certificate. The `firemud-grpc-tls` shared bundle must contain the shared client leaf and a `ca.crt` trust bundle that validates the shared leaf and all eight distinct workload leaves. Runtime publication-reader and Social Groups Pods mount their own workload Secret for the client leaf and key, and use only the shared `firemud-grpc-tls` CA bundle for trust. The checked-in Kustomize Account and Game Session Pods mount their respective full leaf Secret and use its `/tls/ca.crt` for peer trust; each of those Secrets' `ca.crt` must include the issuer trust needed for the gRPC peers those Pods call. Hosted Helm workloads use their own Secret for the leaf certificate and key and only the shared bundle's `ca.crt` for peer trust. This bootstrap requirement describes Secret contents and manifest bindings; it does not claim that issued Secrets, mounted certificates, or live workload readiness have been verified. Each workload leaf must be non-CA and use exactly the `digital signature` and `key encipherment` key usages and exactly the `server auth` and `client auth` extended key usages. For each workload, set exactly the service URI SAN `spiffe://firemud/ns//sa/` and DNS SANs ``, `.`, `..svc`, and `..svc.cluster.local`; replace `` and `` with the target namespace and that Secret's service name. In this SPIFFE URI, `` names the service workload; it is not a value derived from the Pod's Kubernetes ServiceAccount name. Keep every workload leaf and private key distinct. Use the established issuance and trust process for the environment. The [deployment-environment contract](./infrastructure/deployment-environments.md) and [ADR 0038](./decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md) own the canonical identity boundary. `dev-tools/certs/generate-dev-certs.sh --workload` documents the canonical leaf profile, while `dev-tools/hosted/shared/ensure-grpc-tls-secret.sh` shows how hosted setup validates projected cert-manager leaf files and adds their issuer CA to the shared trust bundle. These development/hosted helpers are references for certificate contents and validation; they do not replace production CA custody, issuer authorization, or the environment's approved certificate-issuance procedure. 5. Provision per-environment external integration credentials: backup/object-store, asset-store, outbound-communications, and operator-control-plane credentials as needed for that environment class. 6. Run `./dev-tools/deploy/preflight.py ` and require the common checks `PREFLIGHT-BOOTSTRAP-001`, `PREFLIGHT-SECRETS-001`, `PREFLIGHT-SECRETS-002`, `PREFLIGHT-BRIDGE-001`, `PREFLIGHT-REDIS-001`, `PREFLIGHT-EXTERNAL-001`, and `PREFLIGHT-SERVICES-001`, plus exactly one authenticated custody proof whose `proofId`, `custodyMode`, and `contractVersion` exactly match the selected mode: `PREFLIGHT-JWT-INTERIM-001` for `INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK` or `PREFLIGHT-JWT-002` for `TARGET_NON_EXPORTABLE_SIGNER`. Preserve that exact tuple in the deployment record for retry/replay. An unknown, unsupported, or not-yet-implemented state fails closed. `PREFLIGHT-JWT-001` and `PREFLIGHT-JWKS-001` may be emitted as legacy diagnostic wiring results, but they are never custody proof or player-facing readiness evidence and cannot substitute for the selected custody proof. 7. Record trusted pre-apply bootstrap secret-compliance evidence for each Tier A credential class. First deployment may use immutable initial-provisioning evidence (`lastProvisionedAt`) instead of rotation evidence, but the record must still satisfy the canonical secret-compliance schema before the environment is considered promotable or traffic-open. This evidence proves provisioning and binding only; it does not prove live signer or validator convergence. diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index 241d57dc6a..a998941ac4 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -122,7 +122,7 @@ World Management runtime-target seeding is isolated behind `SmokeDemoRuntimeSeed ### Hosted Preview, Dev-Demo, and Deployment Delivery -Hosted preview deploys real Helm releases into a prod-like stack, exposes a deliberately small preview-only TCP port range alongside HTTPS when public mode is selected, and seeds the minimum state for `LOGIN -> PLAY -> LOOK`. The explicit private mode supplied by #2821 and consumed by #2713 is a bounded bridge proof: a validated ClusterIP runtime has no public NodePort or Telnet smoke requirement, and its controller readiness must prove current-head-bound HTTPS, the private Gateway↔TCP Proxy mTLS bridge, gRPC, all twelve runtime Secret projections (five shared-role projections and seven workload-specific projections), and rollout convergence. Public preview acceptance remains the #2795 child path and requires its allocated NodePort, served public Telnet, and the accepted deployed first-party browser path; a public failure cannot fall back to private mode. Preview is not a separate gameplay architecture and should not put product-specific browser helpers into Gateway. The preview workflow and enabled service/Helm seeders establish the tenant/game/runtime records used by the smoke target, while preview-only TCP Proxy defaults apply routing metadata (`tenantId`, `gameInstanceId`, world/realm, and pointer) to the connection before forwarding the client’s `LOGIN`. This internal metadata and seed state are not a pre-existing player gameplay session and add no client bootstrap command; supported public smoke acceptance remains `LOGIN -> PLAY -> LOOK`. The arrangement is temporary operational glue, not the long-term TCP admission model. These boundaries are defined in [Deployment Environments](../../architecture/infrastructure/deployment-environments.md) and [ADR 0178](../../architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md); no live controller rollout or private bridge proof is claimed yet. +Hosted preview deploys real Helm releases into a prod-like stack, exposes a deliberately small preview-only TCP port range alongside HTTPS when public mode is selected, and seeds the minimum state for `LOGIN -> PLAY -> LOOK`. The explicit private mode supplied by #2821 and consumed by #2713 is a bounded bridge proof: a validated ClusterIP runtime has no public NodePort or Telnet smoke requirement, and its controller readiness must prove current-head-bound HTTPS, the private Gateway↔TCP Proxy mTLS bridge, gRPC, all thirteen runtime Secret projections (five shared-role projections and eight workload-specific projections), and rollout convergence. Public preview acceptance remains the #2795 child path and requires its allocated NodePort, served public Telnet, and the accepted deployed first-party browser path; a public failure cannot fall back to private mode. Preview is not a separate gameplay architecture and should not put product-specific browser helpers into Gateway. The preview workflow and enabled service/Helm seeders establish the tenant/game/runtime records used by the smoke target, while preview-only TCP Proxy defaults apply routing metadata (`tenantId`, `gameInstanceId`, world/realm, and pointer) to the connection before forwarding the client’s `LOGIN`. This internal metadata and seed state are not a pre-existing player gameplay session and add no client bootstrap command; supported public smoke acceptance remains `LOGIN -> PLAY -> LOOK`. The arrangement is temporary operational glue, not the long-term TCP admission model. These boundaries are defined in [Deployment Environments](../../architecture/infrastructure/deployment-environments.md) and [ADR 0178](../../architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md); no live controller rollout or private bridge proof is claimed yet. Preview allocation and reconciliation status: automatic eligibility, bounded two-slot first-come allocation, the maintainer-controlled priority exception, lifecycle serialization, cleanup, and bounded proof-retry controls have focused local/static contract evidence. Live hosted allocation, Actions-run query behavior, Namespace lifecycle, and proof-dispatch behavior remain unverified; normative behavior and the remaining proof boundary are owned by [Deployment Environments](../../architecture/infrastructure/deployment-environments.md#pr-preview-environment). @@ -142,11 +142,11 @@ The hosted credential boundary is now explicit: every secret-consuming preview, The recovery path is separate from routine hosted delivery: `.github/workflows/preview-ca-recovery.yml` runs only from `develop` in the protected GitHub Environment `trusted-preview-ca-recovery`, using `TRUSTED_PREVIEW_CA_RECOVERY_KUBECONFIG` and the protected `FIREMUD_PREVIEW_CA_RECOVERY_BUNDLE` secret. Its fingerprint and context are non-secret Environment variables. This recovery-only workflow and credential bundle are distinct from the `trusted-hosted-cluster` deployment credentials and are not selected by PR-controlled or routine deployment jobs. -The standalone PR-preview consumer owns fixed Telnet and Gateway bridge Certificate requests because PR-authored Certificate resources are stripped from the render artifact. The scoped standalone Certificate writer owns seven fixed gRPC workload Certificates in both preview and dev-demo: the five publication workloads plus Account and Game Session. The runtime workflow validates their leaf Secrets, adds only the public CA projection to its shared trust bundle, then deletes any legacy runtime-local CA signing key and static leaf-source Secrets. Focused contract proof covers fixed specs, namespace/name/SAN/issuer admission, and key-complete Secret waits; live cert-manager issuance, CA-bootstrap denial proof, served-certificate identity, and the eventual player smoke remain unproved. Hosted-controller runtime projections comprise those seven workload leaves plus the five shared-role Secrets for ingress, Telnet, Gateway WebSocket, TCP Proxy bridge, and the shared gRPC bundle, for twelve total. +The standalone PR-preview consumer owns fixed Telnet and Gateway bridge Certificate requests because PR-authored Certificate resources are stripped from the render artifact. The scoped standalone Certificate writer owns eight fixed gRPC workload Certificates in both preview and dev-demo: the five publication workloads plus Account, Game Session, and Social Groups. The runtime workflow validates their leaf Secrets, adds only the public CA projection to its shared trust bundle, then deletes any legacy runtime-local CA signing key and static leaf-source Secrets. Focused contract proof covers fixed specs, namespace/name/SAN/issuer admission, and key-complete Secret waits; live cert-manager issuance, CA-bootstrap denial proof, served-certificate identity, and the eventual player smoke remain unproved. Hosted-controller runtime projections comprise those eight workload leaves plus the five shared-role Secrets for ingress, Telnet, Gateway WebSocket, TCP Proxy bridge, and the shared gRPC bundle, for thirteen total. Static/live boundary: `hosted-identity-controller-manifest-contract.sh`, `hosted-identity-controller-workflow-contract.sh`, `dev-demo-workflow-contract.sh`, and architecture-document checks are static or local prerequisite proof only. They do not establish a live controller deployment, exact NetworkPolicy allow/deny behavior, CNI post-DNAT behavior, issued certificate, runtime Namespace binding, Helm consumer activation, served-certificate probe, or consumer rollout. PO-3.2 remains incomplete until live allow/deny and served Gateway↔TCP Proxy bridge proof are available. -Exact remaining live-proof prerequisites for the #2713 private parent are: (1) populate and verify the protected `trusted-hosted-cluster` Environment with the distinct runtime, preview, GHCR, and requester credential bindings while keeping requester credentials inside the trusted workflow boundary; it currently has zero secrets; (2) prepare the live cluster, which currently has no hosted-identity controller CRD or Deployment, controller CA Secret, or requester credential, by provisioning the fixed CA and pull Secret, installing the attested digest-pinned controller and fail-closed policies, and proving the configured API/probe address readback; (3) publish the stable #2713 head and run the trusted workflow against a sanitized private artifact whose runtime Namespace has the exact mode label, ClusterIP Service, no NodePort, and no Telnet-port annotation; (4) observe all twelve key-complete runtime projections (five shared-role projections and seven workload-specific projections, including Account and Game Session) and Gateway/TCP Proxy rollouts, current-head/Namespace-UID/generation-bound controller `Ready`, served HTTPS, the private mutual-TLS Gateway↔TCP Proxy bridge, gRPC, and the live controller NetworkPolicy allow/deny boundary; and (5) retain non-secret, head-bound evidence for each result. None of these live prerequisites is currently satisfied, so PO-3.2 and private hosted proof remain open. The public NodePort/Telnet smoke and later deployed-browser proof remain separate #2795 obligations. +Exact remaining live-proof prerequisites for the #2713 private parent are: (1) populate and verify the protected `trusted-hosted-cluster` Environment with the distinct runtime, preview, GHCR, and requester credential bindings while keeping requester credentials inside the trusted workflow boundary; it currently has zero secrets; (2) prepare the live cluster, which currently has no hosted-identity controller CRD or Deployment, controller CA Secret, or requester credential, by provisioning the fixed CA and pull Secret, installing the attested digest-pinned controller and fail-closed policies, and proving the configured API/probe address readback; (3) publish the stable #2713 head and run the trusted workflow against a sanitized private artifact whose runtime Namespace has the exact mode label, ClusterIP Service, no NodePort, and no Telnet-port annotation; (4) observe all thirteen key-complete runtime projections (five shared-role projections and eight workload-specific projections, including Account, Game Session, and Social Groups) and Gateway/TCP Proxy rollouts, current-head/Namespace-UID/generation-bound controller `Ready`, served HTTPS, the private mutual-TLS Gateway↔TCP Proxy bridge, gRPC, and the live controller NetworkPolicy allow/deny boundary; and (5) retain non-secret, head-bound evidence for each result. None of these live prerequisites is currently satisfied, so PO-3.2 and private hosted proof remain open. The public NodePort/Telnet smoke and later deployed-browser proof remain separate #2795 obligations. The fixed `develop` environment is a separate `dev-demo-cluster`, not a PR preview: namespace `dev`, release `dev`, hostname `dev.preview.firedevops.net`, and TCP port `32016`. Its workflow and scheduled reconciler deploy the current `develop` head, reset the namespace for reproducibility, and prove `LOGIN -> PLAY -> LOOK`; it is not a promotion source, rollback-evidence source, or DR-attestation source. PR janitor/capacity logic applies only to `pr-*` namespaces. Player-facing staging and production use the canonical Kustomize overlays, while hosted Helm retains preview/dev-demo ownership. diff --git a/dev-tools/deploy/preflight.py b/dev-tools/deploy/preflight.py index d114be2bf8..9b51da90a0 100644 --- a/dev-tools/deploy/preflight.py +++ b/dev-tools/deploy/preflight.py @@ -150,8 +150,12 @@ def _hosted_bridge_secret_ready_attempts_for_timeout(timeout_seconds: int) -> in "account-service", "game-session-service", ) -GRPC_WORKLOAD_SECRET_CONSUMERS = ( +SHARED_TRUST_GRPC_WORKLOADS = ( *PUBLICATION_GRPC_WORKLOADS, + "social-groups-service", +) +GRPC_WORKLOAD_SECRET_CONSUMERS = ( + *SHARED_TRUST_GRPC_WORKLOADS, *ACCOUNT_GAME_SESSION_GRPC_WORKLOADS, ) GRPC_WORKLOAD_LEAF_SECRET_KEYS = {"tls.crt", "tls.key", "ca.crt"} @@ -973,6 +977,7 @@ def publication_workload_secret_requirements( leaf_secret_names: list[str] = [] for workload in GRPC_WORKLOAD_SECRET_CONSUMERS: is_publication_workload = workload in PUBLICATION_GRPC_WORKLOADS + uses_shared_trust = workload in SHARED_TRUST_GRPC_WORKLOADS workload_label = ( "publication workload" if is_publication_workload else "gRPC workload" ) @@ -1019,11 +1024,11 @@ def publication_workload_secret_requirements( raise ValueError( f"Expected exactly one grpc-tls volume for {workload_label} {workload}; found {len(grpc_volumes)}" ) - if is_publication_workload and len(trust_volumes) != 1: + if uses_shared_trust and len(trust_volumes) != 1: raise ValueError( f"Expected exactly one grpc-trust volume for {workload_label} {workload}; found {len(trust_volumes)}" ) - if not is_publication_workload and trust_volumes: + if not uses_shared_trust and trust_volumes: raise ValueError( f"Rendered {workload_label} {workload} must mount its CA from the leaf Secret, not grpc-trust" ) @@ -1032,7 +1037,7 @@ def publication_workload_secret_requirements( secret_name = secret.get("secretName") if isinstance(secret, dict) else None expected_leaf_items = {("tls.crt", "tls.crt"), ("tls.key", "tls.key")} leaf_items = secret.get("items") if isinstance(secret, dict) else None - if is_publication_workload: + if uses_shared_trust: leaf_projection_is_valid = ( isinstance(leaf_items, list) and len(leaf_items) == len(expected_leaf_items) @@ -1061,7 +1066,7 @@ def publication_workload_secret_requirements( or secret_name != secret_name.strip() or not set(secret).issubset( {"secretName", "defaultMode", "items"} - if is_publication_workload + if uses_shared_trust else {"secretName", "defaultMode"} ) or set(grpc_volume) != {"name", "secret"} @@ -1087,7 +1092,7 @@ def publication_workload_secret_requirements( f"{expected_leaf_secret_name}; found {secret_name}" ) - if is_publication_workload: + if uses_shared_trust: trust_volume = trust_volumes[0] trust_secret = trust_volume.get("secret") trust_secret_name = ( @@ -1192,7 +1197,7 @@ def publication_workload_secret_requirements( "FIREMUD_GRPC_CERT_CHAIN_PATH": "/tls/tls.crt", "FIREMUD_GRPC_PRIVATE_KEY_PATH": "/tls/tls.key", "FIREMUD_GRPC_CA_CERT_PATH": ( - "/grpc-trust/ca.crt" if is_publication_workload else "/tls/ca.crt" + "/grpc-trust/ca.crt" if uses_shared_trust else "/tls/ca.crt" ), } grpc_paths: dict[str, str] = {} @@ -1237,7 +1242,7 @@ def publication_workload_secret_requirements( expected_mounts = { "grpc-tls": "/tls", } - if is_publication_workload: + if uses_shared_trust: expected_mounts["grpc-trust"] = "/grpc-trust" validated_mounts: dict[str, dict[str, Any]] = {} for volume_name, mount_path in expected_mounts.items(): @@ -1258,7 +1263,7 @@ def publication_workload_secret_requirements( ) validated_mounts[volume_name] = mount - ca_trust_mount = "/grpc-trust" if is_publication_workload else "/tls" + ca_trust_mount = "/grpc-trust" if uses_shared_trust else "/tls" if any( not path_is_under_mount(path, "/tls") for path in ( @@ -1290,7 +1295,7 @@ def publication_workload_secret_requirements( leaf_secret_names.append(secret_name) if len(set(leaf_secret_names)) != len(leaf_secret_names): raise ValueError( - "Rendered gRPC workload consumers must mount seven distinct grpc-tls Secrets" + "Rendered gRPC workload consumers must mount eight distinct grpc-tls Secrets" ) requirements.append( ( diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index e983c088a9..1ae42f4502 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -68,8 +68,12 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: } ACCOUNT_GRPC_WORKLOADS = {"account-service"} GAME_SESSION_GRPC_WORKLOADS = {"game-session-service"} +SOCIAL_GROUPS_GRPC_WORKLOADS = {"social-groups-service"} DISTINCT_GRPC_WORKLOADS = ( - PUBLICATION_GRPC_WORKLOADS | ACCOUNT_GRPC_WORKLOADS | GAME_SESSION_GRPC_WORKLOADS + PUBLICATION_GRPC_WORKLOADS + | ACCOUNT_GRPC_WORKLOADS + | GAME_SESSION_GRPC_WORKLOADS + | SOCIAL_GROUPS_GRPC_WORKLOADS ) EXPECTED_NAMES = { "Deployment": SERVICE_IMAGES | {"postgres", "redis-coord", "redis-cache", "minio"}, diff --git a/dev-tools/hosted/preview/wait-for-hosted-identity.sh b/dev-tools/hosted/preview/wait-for-hosted-identity.sh index 5b6ff40401..268f892dd2 100644 --- a/dev-tools/hosted/preview/wait-for-hosted-identity.sh +++ b/dev-tools/hosted/preview/wait-for-hosted-identity.sh @@ -153,6 +153,7 @@ if [[ "${1:-}" == "--projections" ]]; then projections+=( "firemud-grpc-account-service|grpc-account-service|tls.crt,tls.key,ca.crt" "firemud-grpc-game-session-service|grpc-game-session-service|tls.crt,tls.key,ca.crt" + "firemud-grpc-social-groups-service|grpc-social-groups-service|tls.crt,tls.key,ca.crt" ) initialize_wait_state "$timeout_seconds" all_projections_ready=true diff --git a/dev-tools/hosted/shared/README.md b/dev-tools/hosted/shared/README.md index 79cdf2916e..9871933959 100644 --- a/dev-tools/hosted/shared/README.md +++ b/dev-tools/hosted/shared/README.md @@ -20,10 +20,10 @@ These scripts are shared because they manage infrastructure or validation behavi - creates or updates the shared GHCR image-pull secret in the target namespace - `ensure-grpc-tls-secret.sh` - - preserves the shared bundle for the four remaining shared-leaf workloads; in standalone mode it validates seven issuer-projected workload leaves, adds their common public CA certificate to shared trust, and removes retained runtime-local signing material after replacement is proven + - preserves the shared bundle for the three remaining shared-leaf workloads; in standalone mode it validates eight issuer-projected workload leaves, adds their common public CA certificate to shared trust, and removes retained runtime-local signing material after replacement is proven - `ensure-standalone-grpc-certificates.sh` - - uses the scoped certificate-writer credential to request seven fixed `firemud-ca-issuer` workload Certificates (five publication plus Account and Game Session) in `dev` or a canonical `pr-N` namespace, then waits for Ready without reading their private keys + - uses the scoped certificate-writer credential to request eight fixed `firemud-ca-issuer` workload Certificates (five publication plus Account, Game Session, and Social Groups) in `dev` or a canonical `pr-N` namespace, then waits for Ready without reading their private keys - `wait-for-runtime-images.sh` - for a pull request, waits for a `runtime-images.yml` run whose exact base, head, and test-merge identities match, then waits for the trusted publisher to publish the immutable `pr-merge-` tag diff --git a/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh b/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh index bd6809d826..71eacf60e1 100644 --- a/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh +++ b/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh @@ -50,6 +50,7 @@ workloads=( automation-scripting-service account-service game-session-service + social-groups-service ) secret_exists() { diff --git a/dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh b/dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh index aea9f97518..dc56d74a5c 100644 --- a/dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh +++ b/dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh @@ -30,6 +30,7 @@ workloads=( automation-scripting-service account-service game-session-service + social-groups-service ) write_certificates() { diff --git a/dev-tools/tests/dev-demo-workflow-contract.sh b/dev-tools/tests/dev-demo-workflow-contract.sh index 35a0322b86..1acef64858 100644 --- a/dev-tools/tests/dev-demo-workflow-contract.sh +++ b/dev-tools/tests/dev-demo-workflow-contract.sh @@ -84,6 +84,7 @@ for required in \ ' game-logic-service' \ ' account-service' \ ' game-session-service' \ + ' social-groups-service' \ ' automation-scripting-service'; do contains_literal "$standalone_grpc_tls" "$required" done @@ -1721,6 +1722,7 @@ for required in ( 'firemud-grpc-${workload}|grpc-publication-${workload}|tls.crt,tls.key,ca.crt', 'firemud-grpc-account-service|grpc-account-service|tls.crt,tls.key,ca.crt', 'firemud-grpc-game-session-service|grpc-game-session-service|tls.crt,tls.key,ca.crt', + 'firemud-grpc-social-groups-service|grpc-social-groups-service|tls.crt,tls.key,ca.crt', ' game-design-service', ' world-management-service', ' entity-management-service', diff --git a/dev-tools/tests/ensure-grpc-tls-secret-contract.sh b/dev-tools/tests/ensure-grpc-tls-secret-contract.sh index 9989fd6c23..5d868772e2 100644 --- a/dev-tools/tests/ensure-grpc-tls-secret-contract.sh +++ b/dev-tools/tests/ensure-grpc-tls-secret-contract.sh @@ -23,12 +23,13 @@ workloads=( automation-scripting-service account-service game-session-service + social-groups-service ) data_dir="$fixture_dir/data" mock_bin="$fixture_dir/bin" mkdir -p "$data_dir" "$mock_bin" -# Build one shared issuer and seven distinct workload identities. The helper +# Build one shared issuer and eight distinct workload identities. The helper # validates the real X.509 extensions, SANs, key pairs, and issuer chains. openssl ecparam -genkey -name prime256v1 -noout -out "$fixture_dir/shared-issuer.key" openssl req -x509 -new -key "$fixture_dir/shared-issuer.key" -sha256 -days 30 \ @@ -289,8 +290,8 @@ if ! run_helper complete "$success_log" "$fixture_dir/success-state" "" 30 \ cat "$fixture_dir/success.out" "$fixture_dir/success.err" >&2 exit 1 fi -grep -Fq '7 distinct workload leaves' "$fixture_dir/success.out" || { - echo "the helper did not accept seven valid cert-manager projections" >&2 +grep -Fq '8 distinct workload leaves' "$fixture_dir/success.out" || { + echo "the helper did not accept eight valid cert-manager projections" >&2 exit 1 } large_constraints_log="$fixture_dir/large-constraints.log" @@ -301,7 +302,7 @@ if ! FORCE_LARGE_BASIC_CONSTRAINTS_OUTPUT=true run_helper complete "$large_const echo "the helper failed to validate a CA extension after capturing its complete output" >&2 exit 1 fi -grep -Fq '7 distinct workload leaves' "$fixture_dir/large-constraints.out" || { +grep -Fq '8 distinct workload leaves' "$fixture_dir/large-constraints.out" || { echo "the helper did not accept valid CA constraints with large extension output" >&2 exit 1 } @@ -340,7 +341,7 @@ if ! run_helper complete "$warning_lookup_log" "$fixture_dir/warning-lookup-stat cat "$fixture_dir/warning-lookup.out" "$fixture_dir/warning-lookup.err" >&2 exit 1 fi -grep -Fq '7 distinct workload leaves' "$fixture_dir/warning-lookup.out" || { +grep -Fq '8 distinct workload leaves' "$fixture_dir/warning-lookup.out" || { echo "a warning on an absent Secret was treated as an existing Secret" >&2 exit 1 } @@ -478,7 +479,7 @@ if grep -q '^delete ' "$incomplete_log"; then fi # Each workload projection becomes ready on its second read, one simulated -# second later. The helper must apply one timeout to all seven workloads rather +# second later. The helper must apply one timeout to all eight workloads rather # than resetting a fresh timeout for every workload. aggregate_timeout_log="$fixture_dir/aggregate-timeout.log" if run_helper delayed-each-workload "$aggregate_timeout_log" \ diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index be4d6e9e94..e9436c0f4a 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -377,7 +377,7 @@ require_literal "$CRD" "self.desiredState == oldSelf.desiredState || (oldSelf.de forbid_literal "$CRD" "self.metadata.namespace == 'firemud-system'" forbid_literal "$CRD" "x-kubernetes-preserve-unknown-fields" require_literal "$CRD" "self.metadata.name.matches('^(dev-demo|pr-[1-9][0-9]{0,50})$')" -for field in observedGeneration phase conditions profile runtimeNamespaceUid requestedHeadSha deployedHeadSha ingress telnet gatewayInternalWs tcpProxyBridge grpc grpcAccountService grpcGameSessionService grpcPublication; do +for field in observedGeneration phase conditions profile runtimeNamespaceUid requestedHeadSha deployedHeadSha ingress telnet gatewayInternalWs tcpProxyBridge grpc grpcAccountService grpcGameSessionService grpcSocialGroupsService grpcPublication; do require_literal "$CRD" "$field" done require_literal "$APPLICATION_CONFIG" "dev-demo-requested-head-annotation: firemud.dev/requested-dev-demo-head-sha" @@ -396,7 +396,7 @@ import yaml source = Path(os.environ["CRD"]).read_text(encoding="utf-8") assert source.count("&consumer_status_schema") == 1 -assert source.count("*consumer_status_schema") == 7 +assert source.count("*consumer_status_schema") == 8 crd = yaml.safe_load(source) schema = crd["spec"]["versions"][0]["schema"]["openAPIV3Schema"] assert crd["spec"].get("preserveUnknownFields", False) is False @@ -460,6 +460,7 @@ consumer_schemas = [ assert all(value == consumer_schemas[0] for value in consumer_schemas[1:]) assert consumer_properties["grpcAccountService"] == consumer_schemas[0] assert consumer_properties["grpcGameSessionService"] == consumer_schemas[0] +assert consumer_properties["grpcSocialGroupsService"] == consumer_schemas[0] publication_roles = consumer_properties["grpcPublication"] assert publication_roles["type"] == "object" assert publication_roles["maxProperties"] == 5 @@ -645,7 +646,7 @@ assert set(binding_policy_names) == policy_names identity_namespace_fragment = "pr-[1-9][0-9]{0,50}-identity" grpc_workload_service_regex_group = ( "(game-design-service|world-management-service|entity-management-service|" - "game-logic-service|automation-scripting-service|account-service|game-session-service)" + "game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)" ) admission_variable_contracts = { "firemud-hosted-identity-secret-boundary": { @@ -1373,10 +1374,10 @@ assert "request.operation != 'DELETE'" in secret_match assert "request.name == 'firemud-grpc-tls'" in secret_match assert "object.metadata.name == 'firemud-grpc-tls'" in secret_match for publication_secret_pattern in ( - "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)$')", - "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)$')", - "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))$')", - "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))$')", + "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|social-groups-service)$')", + "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|social-groups-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|social-groups-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|social-groups-service))$')", ): assert publication_secret_pattern in normalized_secret_match @@ -1402,6 +1403,7 @@ assert "request.name.matches('^firemud-grpc-' + variables.grpcWorkloadServiceReg assert "object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')" in controller_secret_expression assert "'grpc-account-service'" in controller_secret_expression assert "'grpc-game-session-service'" in controller_secret_expression +assert "'grpc-social-groups-service'" in controller_secret_expression assert "object.metadata.name == 'firemud-grpc-tls'" in controller_secret_expression assert "object.metadata.name == 'firemud-grpc-account-service'" in controller_secret_expression assert "object.metadata.name == 'firemud-grpc-game-session-service'" in controller_secret_expression @@ -1432,6 +1434,7 @@ def canonical_primary_name(namespace, name): "grpc-automation-scripting-service", "grpc-account-service", "grpc-game-session-service", + "grpc-social-groups-service", } @@ -1443,7 +1446,7 @@ def namespace_controller_secret_delete_is_allowed(namespace, name): if name in {"firemud-grpc-tls", "firemud-grpc-tls-previous"}: return True fixed_workload_secret = re.fullmatch( - r"firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)(-previous)?", + r"firemud-grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)(-previous)?", name, ) return bool(fixed_workload_secret) or canonical_primary_name(namespace, name.removesuffix("-previous")) @@ -1550,8 +1553,10 @@ assert "object.metadata.name == 'dev-tcp-proxy-bridge'" in cert_manager_expressi assert "object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')" in cert_manager_expression assert "object.metadata.labels['firemud.dev/role'] == 'grpc-account-service'" in cert_manager_expression assert "object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service'" in cert_manager_expression +assert "object.metadata.labels['firemud.dev/role'] == 'grpc-social-groups-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 "object.metadata.name == 'dev-grpc-social-groups-service'" in cert_manager_expression 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 @@ -1603,10 +1608,11 @@ assert "firemud-grpc-tls" not in controller_delete_expression assert "request.name.startsWith(" in controller_delete_expression assert "(request.operation != 'DELETE' && has(object.metadata.labels)" in certificate_match assert "object.metadata.labels['firemud.dev/identity-name'] == ((request.namespace == 'dev-identity') ? 'dev-demo' : request.namespace.substring(0, request.namespace.size() - 9))" in certificate_match -assert "object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service']" in certificate_match +assert "object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service']" in certificate_match assert "grpc-publication-" in certificate_match assert "grpc-account-service" in certificate_match assert "grpc-game-session-service" in certificate_match +assert "grpc-social-groups-service" in certificate_match assert "object.metadata.name == 'firemud-grpc-tls'" not in certificate_match certificate_expressions = [ @@ -1669,7 +1675,7 @@ assert "object.spec.issuerRef.group == 'cert-manager.io'" in profile_expression internal_issuer_profile = ( "((object.metadata.labels['firemud.dev/role'] in " "['gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', " - "'grpc-game-session-service'] || " + "'grpc-game-session-service', 'grpc-social-groups-service'] || " "object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && " "object.spec.issuerRef.name == 'firemud-ca-issuer')" ) @@ -1689,12 +1695,17 @@ publication_secret_name_guards = ( "object.metadata.name == 'dev-grpc-account-service'", "object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service' && " "object.metadata.name == 'dev-grpc-game-session-service'", + "object.metadata.labels['firemud.dev/role'] == 'grpc-social-groups-service' && " + "object.metadata.name == 'dev-grpc-social-groups-service'", "object.metadata.labels['firemud.dev/role'] == 'grpc-account-service' && " "object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + " "'-grpc-account-service'", "object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service' && " "object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + " "'-grpc-game-session-service'", + "object.metadata.labels['firemud.dev/role'] == 'grpc-social-groups-service' && " + "object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + " + "'-grpc-social-groups-service'", ) for publication_secret_name_guard in publication_secret_name_guards: assert publication_secret_name_guard in normalized_controller_secret_expression @@ -1702,6 +1713,7 @@ namespace_service = "((request.namespace == 'dev-identity') ? 'dev' : request.na for role, service in ( ("grpc-account-service", "account-service"), ("grpc-game-session-service", "game-session-service"), + ("grpc-social-groups-service", "social-groups-service"), ): service_profile = ( f"(object.metadata.labels['firemud.dev/role'] != '{role}' || " @@ -2184,8 +2196,10 @@ done require_literal "$ADMISSION" "'firemud-grpc-tls-previous', " require_literal "$ADMISSION" "'firemud-grpc-account-service'" require_literal "$ADMISSION" "'firemud-grpc-game-session-service'" +require_literal "$ADMISSION" "'firemud-grpc-social-groups-service'" require_literal "$ADMISSION" "'-grpc-account-service-previous'), " -require_literal "$ADMISSION" "'-grpc-game-session-service-previous')] &&" +require_literal "$ADMISSION" "'-grpc-game-session-service-previous'), " +require_literal "$ADMISSION" "'-grpc-social-groups-service-previous')] &&" require_literal "$ADMISSION" "request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' ||" require_literal "$BOOTSTRAP" "crd_deadline=\$((SECONDS + WAIT_SECONDS))" # shellcheck disable=SC2016 # Match the literal bootstrap default. @@ -4565,10 +4579,13 @@ publication_services = ( "game-logic-service", "automation-scripting-service", ) -distinct_workload_services = publication_services + ("account-service", "game-session-service") +distinct_workload_services = publication_services + ( + "account-service", + "game-session-service", + "social-groups-service", +) shared_services = ( "logging-admin-service", - "social-groups-service", "spring-cloud-gateway", "tcp-proxy-service", ) @@ -4763,7 +4780,7 @@ for service in ( ).get("spec", {}).get("strategy", {}) if base_strategy.get("type") != "Recreate": fail(f"Kustomize base Deployment/{service} must use non-rolling Recreate strategy") -for service in publication_services: +for service in publication_services + ("social-groups-service",): assert_distinct_workload_service(service, base_deployments, "Kustomize base") PY diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index 5dfd9634ac..1ec634ad33 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -5838,6 +5838,9 @@ if [[ "$1" == -n && "$2" == pr-42 && "$3" == get && "$4" == secret ]]; then firemud-grpc-game-session-service) printf '%s' '{"metadata":{"name":"firemud-grpc-game-session-service","labels":{"firemud.dev/managed-by":"hosted-identity-controller","firemud.dev/identity-name":"pr-42","firemud.dev/role":"grpc-game-session-service","firemud.dev/retention":"retained"}},"data":{"tls.crt":"cert","tls.key":"key","ca.crt":"ca"}}' ;; + firemud-grpc-social-groups-service) + printf '%s' '{"metadata":{"name":"firemud-grpc-social-groups-service","labels":{"firemud.dev/managed-by":"hosted-identity-controller","firemud.dev/identity-name":"pr-42","firemud.dev/role":"grpc-social-groups-service","firemud.dev/retention":"retained"}},"data":{"tls.crt":"cert","tls.key":"key","ca.crt":"ca"}}' + ;; *) printf 'unexpected projection Secret: %s\n' "$secret_name" >&2 exit 2 diff --git a/dev-tools/tests/preflight-contract.sh b/dev-tools/tests/preflight-contract.sh index c93d74aec5..f453a3c447 100644 --- a/dev-tools/tests/preflight-contract.sh +++ b/dev-tools/tests/preflight-contract.sh @@ -1252,6 +1252,7 @@ spec: YAML python3 - <<'PY' "$RENDERED_MANIFEST" +import copy import pathlib import sys @@ -1265,6 +1266,18 @@ documents = [ ] for document in documents: document.setdefault("metadata", {})["namespace"] = "firemud" +game_design = next( + document + for document in documents + if document.get("kind") == "Deployment" + and document.get("metadata", {}).get("name") == "game-design-service" +) +social_groups = copy.deepcopy(game_design) +social_groups["metadata"]["name"] = "social-groups-service" +social_spec = social_groups["spec"]["template"]["spec"] +social_spec["containers"][0]["name"] = "social-groups-service" +social_spec["volumes"][0]["secret"]["secretName"] = "firemud-grpc-social-groups-service" +documents.append(social_groups) path.write_text(yaml.safe_dump_all(documents, sort_keys=False), encoding="utf-8") PY @@ -9928,7 +9941,7 @@ publication_documents = [ } }, } - for workload in module.PUBLICATION_GRPC_WORKLOADS + for workload in module.SHARED_TRUST_GRPC_WORKLOADS ] for workload in module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS: publication_documents.append( @@ -9985,6 +9998,11 @@ if module.PUBLICATION_GRPC_WORKLOADS != ( "automation-scripting-service", ): raise SystemExit("Account and Game Session changed the five publication-only workload set") +if module.SHARED_TRUST_GRPC_WORKLOADS != ( + *module.PUBLICATION_GRPC_WORKLOADS, + "social-groups-service", +): + raise SystemExit("Social Groups must have a distinct leaf and the shared CA-only trust projection") publication_requirements = module.publication_workload_secret_requirements( publication_expected, publication_documents ) @@ -9996,7 +10014,7 @@ if {name for name, _, _ in publication_requirements} != ( expected_workload_secret_names | {module.PUBLICATION_GRPC_TRUST_SECRET_NAME} ): raise SystemExit( - "workload Secret requirements do not follow the seven leaf bindings and shared trust binding" + "workload Secret requirements do not follow the eight leaf bindings and shared trust binding" ) publication_keys = {name: keys for name, _, keys in publication_requirements} if any(namespace != "firemud" for _, namespace, _ in publication_requirements): @@ -10029,8 +10047,36 @@ def expect_publication_static_failure(description, documents, expected_fragment= ) +social_groups_index = module.SHARED_TRUST_GRPC_WORKLOADS.index("social-groups-service") +missing_social_groups_documents = copy.deepcopy(publication_documents) +missing_social_groups_documents.pop(social_groups_index) +expect_publication_static_failure( + "a missing Social Groups workload identity", + missing_social_groups_documents, + "Expected exactly one rendered Deployment for gRPC workload social-groups-service", +) +wrong_social_groups_leaf_documents = copy.deepcopy(publication_documents) +wrong_social_groups_leaf_documents[social_groups_index]["spec"]["template"]["spec"]["volumes"][0][ + "secret" +]["secretName"] = "firemud-grpc-game-session-service" +expect_publication_static_failure( + "a reused Social Groups leaf Secret", + wrong_social_groups_leaf_documents, + "grpc-tls Secret must be firemud-grpc-social-groups-service", +) +missing_social_groups_trust_documents = copy.deepcopy(publication_documents) +missing_social_groups_trust_documents[social_groups_index]["spec"]["template"]["spec"][ + "volumes" +].pop() +expect_publication_static_failure( + "a missing Social Groups shared trust projection", + missing_social_groups_trust_documents, + "Expected exactly one grpc-trust volume", +) + + for workload in module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS: - workload_index = len(module.PUBLICATION_GRPC_WORKLOADS) + ( + workload_index = len(module.SHARED_TRUST_GRPC_WORKLOADS) + ( module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS.index(workload) ) wrong_leaf_documents = copy.deepcopy(publication_documents) diff --git a/dev-tools/tests/standalone-grpc-certificates-contract.sh b/dev-tools/tests/standalone-grpc-certificates-contract.sh index 3c850ddbfe..233bf697fc 100644 --- a/dev-tools/tests/standalone-grpc-certificates-contract.sh +++ b/dev-tools/tests/standalone-grpc-certificates-contract.sh @@ -73,9 +73,10 @@ workloads = ( "automation-scripting-service", "account-service", "game-session-service", + "social-groups-service", ) if len(documents) != len(workloads): - raise SystemExit(f"expected seven Certificate documents, got {len(documents)}") + raise SystemExit(f"expected eight Certificate documents, got {len(documents)}") for workload, document in zip(workloads, documents, strict=True): expected_name = f"{namespace}-grpc-{workload}" if document.get("apiVersion") != "cert-manager.io/v1" or document.get("kind") != "Certificate": @@ -123,8 +124,8 @@ for workload, document in zip(workloads, documents, strict=True): PY actual_wait_count="$(grep -c ' wait ' "$STATE_DIR/calls")" - [[ "$actual_wait_count" -eq 7 ]] || { - echo "expected seven Certificate readiness waits for $namespace, got $actual_wait_count" >&2 + [[ "$actual_wait_count" -eq 8 ]] || { + echo "expected eight Certificate readiness waits for $namespace, got $actual_wait_count" >&2 exit 1 } if grep -E 'get secret|create secret|apply.*secret' "$STATE_DIR/calls" >/dev/null; then @@ -166,6 +167,7 @@ for workload in ( "automation-scripting-service", "account-service", "game-session-service", + "social-groups-service", ): assert workload in request_text, workload assert f"firemud-grpc-{workload}" in certificate_text, workload diff --git a/dev-tools/tests/trust-bootstrap-issuance-contract.sh b/dev-tools/tests/trust-bootstrap-issuance-contract.sh index a7f989a065..b1c4ae7e2c 100755 --- a/dev-tools/tests/trust-bootstrap-issuance-contract.sh +++ b/dev-tools/tests/trust-bootstrap-issuance-contract.sh @@ -177,7 +177,7 @@ def check_contract(items: list[dict]) -> None: "object.spec.usages == ['digital signature', 'key encipherment', 'client auth']", "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))$')", + "object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$')", ): require(certificate, needle, "Certificate boundary") status_rules = certificate_status["matchConstraints"]["resourceRules"] @@ -205,7 +205,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|social-groups-service))$", "standalone Certificate validation", ) for needle in ( @@ -219,10 +219,15 @@ def check_contract(items: list[dict]) -> None: "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.metadata.name.endsWith('-grpc-social-groups-service')", + "object.spec.secretName == 'firemud-grpc-social-groups-service'", + "object.spec.issuerRef.name == 'firemud-ca-issuer'", + "object.spec.dnsNames == ['social-groups-service', 'social-groups-service.' + request.namespace, 'social-groups-service.' + request.namespace + '.svc', 'social-groups-service.' + request.namespace + '.svc.cluster.local']", + "object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/social-groups-service']", ): require(certificate_validation, needle, "standalone workload identity") normalized_certificate_validation = " ".join(certificate_validation.split()) - for workload in ("account-service", "game-session-service"): + for workload in ("account-service", "game-session-service", "social-groups-service"): expected_branch = ( f"(object.metadata.name.endsWith('-grpc-{workload}') && " f"object.spec.secretName == 'firemud-grpc-{workload}' && " diff --git a/k8s/base/social-groups-service.yaml b/k8s/base/social-groups-service.yaml index b2a1763a3a..a22114d4b3 100644 --- a/k8s/base/social-groups-service.yaml +++ b/k8s/base/social-groups-service.yaml @@ -24,12 +24,16 @@ spec: env: - name: SPRING_PROFILES_ACTIVE value: "prod" + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace - name: FIREMUD_GRPC_CERT_CHAIN_PATH - value: /tls/client.crt + value: /tls/tls.crt - name: FIREMUD_GRPC_PRIVATE_KEY_PATH - value: /tls/client.key + value: /tls/tls.key - name: FIREMUD_GRPC_CA_CERT_PATH - value: /tls/ca.crt + value: /grpc-trust/ca.crt envFrom: - configMapRef: name: firemud-config @@ -39,6 +43,9 @@ spec: - name: grpc-tls mountPath: /tls readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true - name: jwt-signing-keys mountPath: /var/run/secrets/firemud/jwt readOnly: true @@ -105,8 +112,19 @@ spec: readOnlyRootFilesystem: true volumes: - name: grpc-tls + secret: + secretName: firemud-grpc-social-groups-service + 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: jwt-signing-keys secret: secretName: jwt-signing-keys diff --git a/k8s/helm/README.md b/k8s/helm/README.md index cea4942839..ffd8aeb535 100644 --- a/k8s/helm/README.md +++ b/k8s/helm/README.md @@ -48,7 +48,7 @@ helm upgrade --install pr-123 ./firemud \ --create-namespace ``` -Before applying the full-stack chart, trusted environment setup must provision these seven namespace-scoped workload leaf Secrets: `firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, `firemud-grpc-automation-scripting-service`, `firemud-grpc-account-service`, and `firemud-grpc-game-session-service`. It must also provision the shared `firemud-grpc-tls` trust bundle with issuer CA trust for all seven leaves. Standalone hosted setup uses the trusted [`ensure-standalone-grpc-certificates.sh`](../../dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh) Certificate writer for all seven leaves; hosted-controller setup must wait for all seven workload Secret projections before applying the chart. Hosted Helm workloads use their own Secret for the leaf certificate and key and the shared bundle's `ca.crt` projection for peer trust. Other environments must follow the approved issuance and bootstrap process in the [deployment runbook](../../design/architecture/system-architecture-deployment-runbook.md), under the canonical [deployment-environment contract](../../design/architecture/infrastructure/deployment-environments.md) and [ADR 0038](../../design/architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). Direct `helm template` only renders Secret references; it does not prove that the Secrets exist or are ready. Keep certificate material and secret credentials out of PR-controlled values and workflows. +Before applying the full-stack chart, trusted environment setup must provision these eight namespace-scoped workload leaf Secrets: `firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, `firemud-grpc-automation-scripting-service`, `firemud-grpc-account-service`, `firemud-grpc-game-session-service`, and `firemud-grpc-social-groups-service`. It must also provision the shared `firemud-grpc-tls` trust bundle with issuer CA trust for all eight leaves. Standalone hosted setup uses the trusted [`ensure-standalone-grpc-certificates.sh`](../../dev-tools/hosted/shared/ensure-standalone-grpc-certificates.sh) Certificate writer for all eight leaves; hosted-controller setup must wait for all eight workload Secret projections before applying the chart. Hosted Helm workloads use their own Secret for the leaf certificate and key and the shared bundle's `ca.crt` projection for peer trust. Other environments must follow the approved issuance and bootstrap process in the [deployment runbook](../../design/architecture/system-architecture-deployment-runbook.md), under the canonical [deployment-environment contract](../../design/architecture/infrastructure/deployment-environments.md) and [ADR 0038](../../design/architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). Direct `helm template` only renders Secret references; it does not prove that the Secrets exist or are ready. Keep certificate material and secret credentials out of PR-controlled values and workflows. The hosted chart owns public `jwt-jwks` as a `ConfigMap`. Helm treats a same-name legacy Secret and the target ConfigMap as distinct resource identities, so the upgrade creates the ConfigMap and removes the obsolete Secret without a manual pre-delete. The `dev-tools/tests/helm-jwks-contract.sh` test proves the target rendered resource and workload wiring; it is not a live-cluster upgrade or downtime proof. diff --git a/k8s/helm/firemud/templates/_helpers.tpl b/k8s/helm/firemud/templates/_helpers.tpl index 488f4af532..db8901e051 100644 --- a/k8s/helm/firemud/templates/_helpers.tpl +++ b/k8s/helm/firemud/templates/_helpers.tpl @@ -32,7 +32,7 @@ helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }} {{- end -}} {{- define "firemud.grpcWorkloadNames" -}} -{{- list "account-service" "game-session-service" "game-design-service" "world-management-service" "entity-management-service" "game-logic-service" "automation-scripting-service" | toJson -}} +{{- list "account-service" "game-session-service" "social-groups-service" "game-design-service" "world-management-service" "entity-management-service" "game-logic-service" "automation-scripting-service" | toJson -}} {{- end -}} {{- define "firemud.grpcSecretName" -}} diff --git a/k8s/hosted-identity-controller/README.md b/k8s/hosted-identity-controller/README.md index 5a9d597215..50a87fde00 100644 --- a/k8s/hosted-identity-controller/README.md +++ b/k8s/hosted-identity-controller/README.md @@ -34,7 +34,7 @@ Controller-managed resources carry these stable labels: Existing runtime namespaces retain their workflow labels. PR namespaces must have `firemud.dev/preview=true` and a matching `firemud.dev/pr-number`; the demo namespace must have `firemud.dev/dev-demo=true` and `firemud.dev/environment-class=dev-demo-cluster`. -Status contains only non-secret evidence: `observedGeneration`, phase, conditions, a derived `profile` (including `runtimeNamespaceUid`, `requestedHeadSha`, `deployedHeadSha`, `exposureMode`, and `telnetPort`), and role evidence for ingress, Telnet, Gateway-internal WebSocket, TCP Proxy bridge, and the shared gRPC transport bundle. The `grpcPublication` map remains exactly the five fixed publication roles; `grpcAccountService` and `grpcGameSessionService` separately retain each workload's `RoleStatus` high-water evidence. Readiness therefore covers seven gRPC workload identities: the five publication roles plus Account and Game Session. Each role status records only non-secret revision, source and source-object generations, SPKI fingerprint, provenance, and state. `Ready` is true only when the current runtime Namespace UID and requested 40-character head SHA match the observed profile, the separately recorded post-Helm deployed head matches that request, all seven gRPC workload identities and other consumers have converged, and the mode-specific served probes pass. Public mode includes the served Telnet probe; private mode deliberately omits it and requires served HTTPS, the private bridge, and gRPC instead. A runtime UID, request, deployed-head, exposure-mode, or port change clears `Ready`; pre-Helm namespace preparation cannot claim deployment success. +Status contains only non-secret evidence: `observedGeneration`, phase, conditions, a derived `profile` (including `runtimeNamespaceUid`, `requestedHeadSha`, `deployedHeadSha`, `exposureMode`, and `telnetPort`), and role evidence for ingress, Telnet, Gateway-internal WebSocket, TCP Proxy bridge, and the shared gRPC transport bundle. The `grpcPublication` map remains exactly the five fixed publication roles; `grpcAccountService`, `grpcGameSessionService`, and `grpcSocialGroupsService` separately retain each workload's `RoleStatus` high-water evidence. Readiness therefore covers eight gRPC workload identities: the five publication roles plus Account, Game Session, and Social Groups. Each role status records only non-secret revision, source and source-object generations, SPKI fingerprint, provenance, and state. `Ready` is true only when the current runtime Namespace UID and requested 40-character head SHA match the observed profile, the separately recorded post-Helm deployed head matches that request, all eight gRPC workload identities and other consumers have converged, and the mode-specific served probes pass. Public mode includes the served Telnet probe; private mode deliberately omits it and requires served HTTPS, the private bridge, and gRPC instead. A runtime UID, request, deployed-head, exposure-mode, or port change clears `Ready`; pre-Helm namespace preparation cannot claim deployment success. The phases are `Pending`, `Provisioning`, `WaitingForCertificate`, `RuntimeAbsent`, `Syncing`, `Verifying`, `Ready`, `Degraded`, `Blocked`, `Retiring`, and `Retired`. diff --git a/k8s/hosted-identity-controller/admission.yaml b/k8s/hosted-identity-controller/admission.yaml index 9376e2c9d4..8f4b0d28b5 100644 --- a/k8s/hosted-identity-controller/admission.yaml +++ b/k8s/hosted-identity-controller/admission.yaml @@ -136,7 +136,7 @@ spec: - name: hostedPreviewIdentityNamespacePattern expression: "'pr-[1-9][0-9]{0,50}-identity'" - name: grpcWorkloadServiceRegexGroup - expression: "'(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)'" + expression: "'(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)'" matchConstraints: matchPolicy: Equivalent resourceRules: @@ -162,17 +162,17 @@ spec: 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.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' || request.name == 'firemud-grpc-account-service' || request.name == 'firemud-grpc-game-session-service' || request.name == 'firemud-grpc-social-groups-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|social-groups-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|social-groups-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.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))-previous$'))) || (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.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' || object.metadata.name == 'firemud-grpc-account-service' || object.metadata.name == 'firemud-grpc-game-session-service' || object.metadata.name == 'firemud-grpc-social-groups-service' || + 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|social-groups-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|social-groups-service))$') || object.metadata.name == 'firemud-grpc-tls-previous' || - object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service))-previous$'))))) + object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))-previous$'))))) validations: # Namespace deletion also deletes the exact retained material. Allow # only the built-in kube-system namespace controller, DELETE, managed @@ -206,7 +206,8 @@ spec: (object.metadata.name == 'firemud-grpc-game-logic-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-publication-game-logic-service') || (object.metadata.name == 'firemud-grpc-automation-scripting-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-publication-automation-scripting-service') || (object.metadata.name == 'firemud-grpc-account-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-account-service') || - (object.metadata.name == 'firemud-grpc-game-session-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service'))))) || + (object.metadata.name == 'firemud-grpc-game-session-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service') || + (object.metadata.name == 'firemud-grpc-social-groups-service' && object.metadata.labels['firemud.dev/role'] == 'grpc-social-groups-service'))))) || (request.userInfo.username == 'system:serviceaccount:firemud-system:firemud-hosted-identity-controller' && ((request.operation == 'DELETE' && (request.name == 'firemud-grpc-tls' || @@ -227,9 +228,9 @@ spec: (request.operation != 'DELETE' && has(object.metadata.labels) && object.metadata.labels['firemud.dev/managed-by'] == 'hosted-identity-controller' && - (object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc', 'grpc-account-service', 'grpc-game-session-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && + (object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && object.metadata.labels['firemud.dev/retention'] == 'retained' && - (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-social-groups-service' || (object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.grpcWorkloadServiceRegexGroup + ')$') && object.metadata.name.startsWith( ((request.namespace == 'dev' || request.namespace == 'dev-identity') ? 'dev' : @@ -257,7 +258,7 @@ spec: object.metadata.annotations['cert-manager.io/certificate-name'] == object.metadata.name && ((object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet'] && object.metadata.annotations['cert-manager.io/issuer-name'] == 'letsencrypt-prod') || - ((object.metadata.labels['firemud.dev/role'] in ['gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && + ((object.metadata.labels['firemud.dev/role'] in ['gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && 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' && @@ -275,7 +276,8 @@ spec: ((object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') && object.metadata.name == 'dev-grpc-' + object.metadata.labels['firemud.dev/role'].substring(17)) || (object.metadata.labels['firemud.dev/role'] == 'grpc-account-service' && object.metadata.name == 'dev-grpc-account-service') || - (object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service' && object.metadata.name == 'dev-grpc-game-session-service'))) || + (object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service' && object.metadata.name == 'dev-grpc-game-session-service') || + (object.metadata.labels['firemud.dev/role'] == 'grpc-social-groups-service' && object.metadata.name == 'dev-grpc-social-groups-service'))) || (request.namespace.matches('^' + variables.hostedPreviewIdentityNamespacePattern + '$') && object.metadata.labels['firemud.dev/identity-name'] == request.namespace.substring(0, request.namespace.size() - 9) && ((object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-tls' && @@ -289,7 +291,8 @@ spec: ((object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-') && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-' + object.metadata.labels['firemud.dev/role'].substring(17)) || (object.metadata.labels['firemud.dev/role'] == 'grpc-account-service' && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-account-service') || - (object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service' && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-game-session-service'))))))) + (object.metadata.labels['firemud.dev/role'] == 'grpc-game-session-service' && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-game-session-service') || + (object.metadata.labels['firemud.dev/role'] == 'grpc-social-groups-service' && object.metadata.name == request.namespace.substring(0, request.namespace.size() - 9) + '-grpc-social-groups-service'))))))) message: managed identity and runtime TLS Secrets are writable only by the controller or cert-manager for its owned identity Secret reason: Forbidden - expression: >- @@ -319,7 +322,7 @@ spec: - name: hostedPreviewIdentityNamespacePattern expression: "'pr-[1-9][0-9]{0,50}-identity'" - name: grpcWorkloadServiceRegexGroup - expression: "'(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service)'" + expression: "'(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service)'" matchConstraints: matchPolicy: Equivalent resourceRules: @@ -345,12 +348,12 @@ spec: (request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$'))) || ((request.namespace == 'dev-identity' || request.namespace.matches('^pr-[1-9][0-9]{0,50}-identity$')) && ((request.operation == 'DELETE' && - 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|social-groups-service))$') && request.name.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-')) || (request.operation != 'DELETE' && - 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.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$') && object.metadata.name.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '-')))) @@ -383,7 +386,7 @@ spec: has(object.metadata.labels) && object.metadata.labels['firemud.dev/managed-by'] == 'hosted-identity-controller' && object.metadata.labels['firemud.dev/identity-name'] == ((request.namespace == 'dev-identity') ? 'dev-demo' : request.namespace.substring(0, request.namespace.size() - 9)) && - (object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && + (object.metadata.labels['firemud.dev/role'] in ['ingress', 'telnet', 'gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-' + variables.grpcWorkloadServiceRegexGroup + ')$') && object.metadata.name.startsWith( ((request.namespace == 'dev-identity') ? 'dev' : @@ -398,7 +401,7 @@ spec: object.spec.dnsNames == [((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.preview.firedevops.net'] && (!has(object.spec.uris) || object.spec.uris.size() == 0) && object.spec.issuerRef.name == 'letsencrypt-prod') || - ((object.metadata.labels['firemud.dev/role'] in ['gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && + ((object.metadata.labels['firemud.dev/role'] in ['gateway-internal-ws', 'tcp-proxy-bridge', 'grpc-account-service', 'grpc-game-session-service', 'grpc-social-groups-service'] || object.metadata.labels['firemud.dev/role'].startsWith('grpc-publication-')) && object.spec.issuerRef.name == 'firemud-ca-issuer')) && object.spec.issuerRef.kind == 'ClusterIssuer' && object.spec.issuerRef.group == 'cert-manager.io' && @@ -437,6 +440,11 @@ spec: (object.spec.secretName == object.metadata.name && object.spec.dnsNames == ['game-session-service', 'game-session-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)), 'game-session-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc', 'game-session-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc.cluster.local'] && object.spec.uris == ['spiffe://firemud/ns/' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '/sa/game-session-service'] && + object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth'])) && + (object.metadata.labels['firemud.dev/role'] != 'grpc-social-groups-service' || + (object.spec.secretName == object.metadata.name && + object.spec.dnsNames == ['social-groups-service', 'social-groups-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)), 'social-groups-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc', 'social-groups-service.' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '.svc.cluster.local'] && + object.spec.uris == ['spiffe://firemud/ns/' + ((request.namespace == 'dev-identity') ? 'dev' : request.namespace.substring(0, request.namespace.size() - 9)) + '/sa/social-groups-service'] && object.spec.usages == ['digital signature', 'key encipherment', 'server auth', 'client auth']))))) || (request.userInfo.username == 'system:serviceaccount:cert-manager:cert-manager' && request.subResource == 'status' && @@ -553,7 +561,7 @@ spec: object.rules.exists(r, r.apiGroups == ['cert-manager.io'] && r.resources == ['certificates'] && - r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service')] && + r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service')] && r.verbs == ['get', 'update', 'patch', 'delete']) && object.rules.exists(r, r.apiGroups == ['cert-manager.io'] && @@ -563,12 +571,12 @@ spec: object.rules.exists(r, r.apiGroups == [''] && r.resources == ['secrets'] && - r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge-previous'), 'firemud-grpc-tls-previous', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service-previous')] && + r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge-previous'), 'firemud-grpc-tls-previous', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service-previous')] && r.verbs == ['get']) && object.rules.exists(r, r.apiGroups == [''] && r.resources == ['secrets'] && - r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge-previous'), 'firemud-grpc-tls-previous', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service-previous')] && + r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge-previous'), 'firemud-grpc-tls-previous', (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-design-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-world-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-entity-management-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-logic-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-automation-scripting-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-account-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-game-session-service-previous'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-grpc-social-groups-service-previous')] && r.verbs == ['update', 'patch', 'delete']) && object.rules.exists(r, r.apiGroups == [''] && @@ -581,7 +589,7 @@ spec: object.rules.exists(r, r.apiGroups == [''] && r.resources == ['secrets'] && - r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', 'firemud-grpc-game-design-service', 'firemud-grpc-world-management-service', 'firemud-grpc-entity-management-service', 'firemud-grpc-game-logic-service', 'firemud-grpc-automation-scripting-service', 'firemud-grpc-account-service', 'firemud-grpc-game-session-service'] && + r.resourceNames == [(((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-telnet-tls'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-gateway-internal-ws'), (((object.metadata.namespace == 'dev' || object.metadata.namespace == 'dev-identity') ? 'dev' : object.metadata.labels['firemud.dev/identity-name']) + '-tcp-proxy-bridge'), 'firemud-grpc-tls', 'firemud-grpc-game-design-service', 'firemud-grpc-world-management-service', 'firemud-grpc-entity-management-service', 'firemud-grpc-game-logic-service', 'firemud-grpc-automation-scripting-service', 'firemud-grpc-account-service', 'firemud-grpc-game-session-service', 'firemud-grpc-social-groups-service'] && r.verbs == ['get', 'update', 'patch', 'delete']) && object.rules.exists(r, r.apiGroups == [''] && diff --git a/k8s/hosted-identity-controller/crd.yaml b/k8s/hosted-identity-controller/crd.yaml index fbf0eef2a6..f1a0a7e594 100644 --- a/k8s/hosted-identity-controller/crd.yaml +++ b/k8s/hosted-identity-controller/crd.yaml @@ -205,6 +205,7 @@ spec: grpc: *consumer_status_schema grpcAccountService: *consumer_status_schema grpcGameSessionService: *consumer_status_schema + grpcSocialGroupsService: *consumer_status_schema grpcPublication: type: object description: Per-publication workload certificate projection and rollout evidence only; this does not prove receiver-method authorization or authorize publication identity activation. diff --git a/k8s/trust-bootstrap/README.md b/k8s/trust-bootstrap/README.md index bc8019d624..f55bf45103 100644 --- a/k8s/trust-bootstrap/README.md +++ b/k8s/trust-bootstrap/README.md @@ -10,7 +10,7 @@ This is a prerequisite for the private Gateway–TCP Proxy bridge in #2713. It m 4. Prepare the separate recovery-only GitHub Environment `trusted-preview-ca-recovery`. It is restricted to `develop` and is never selected by a PR-controlled or routine deployment job. Provision its dedicated recovery kubeconfig, `FIREMUD_PREVIEW_CA_RECOVERY_BUNDLE` secret, and non-secret fingerprint/context variables. Test the recovery script's bundle validation, exact two-Secret reconstruction, refusal on a missing admission binding or surviving legacy credential, and the trusted `verify` workflow. Before the canonical CA exists, use disposable test material for this procedure; no test key may be installed as `firemud-grpc-ca` in the shared cluster. 5. Only after steps 1–4 have live evidence, generate a new preview-only RSA-4096 CA in a private, ephemeral operator directory. Use an unencrypted PKCS8 private key, critical `BasicConstraints CA:TRUE,pathlen:0`, critical `KeyUsage keyCertSign`, SHA-256, and 730-day validity. Do not use a cert-manager self-signed issuer to create the root. Compute the lowercase SHA-256 fingerprint of the DER certificate. Pipe `recover-firemud-ca.py pack` directly to `gh secret set FIREMUD_PREVIEW_CA_RECOVERY_BUNDLE -e trusted-preview-ca-recovery` without printing or retaining the bundle; set the fingerprint as a protected Environment variable. The GitHub Environment secret is the encrypted out-of-cluster recovery copy. Verify that copy through the trusted workflow before removing the ephemeral operator files. Do not put the key, bundle, or kubeconfig in a PR, Actions artifact, log, issue, chat, user PC, or password manager. 6. Run the reviewed recovery workflow's `restore` operation on `develop`. It accepts only the dedicated recovery ServiceAccount, the explicitly selected Kubernetes context, all eight live fail-closed admission bindings, and a revoked legacy ServiceAccount/ClusterRoleBinding. It writes only `firemud-system/firemud-grpc-ca` (`Opaque`, `ca.crt`/`ca.key`) and `cert-manager/firemud-grpc-ca` (`kubernetes.io/tls`, `tls.crt`/`tls.key`), then compares exact bytes through private readback. The copy is never printed. Install the fixed `firemud-ca-issuer` only after this recovery and readback pass. -7. With the controller still inactive, request the fixed standalone internal Gateway and TCP Proxy Certificates through the scoped writer, then request the seven standalone per-workload gRPC Certificates (five publication workloads, Account, and Game Session) for `dev` and a disposable `pr-N` namespace through that same writer. Observe `Ready`, key-complete output Secrets, and served transport identities/chains. The runtime workflow consumes only the projected leaf keys and public `ca.crt`; after validating every gRPC leaf it deletes the legacy runtime `firemud-grpc-ca` signing-key Secret and old static leaf-source Secrets. Repeat unauthorized direct CertificateRequest and Certificate tests after the issuer becomes Ready; an admission-only dry-run before issuance is not proof that unauthorized signing cannot occur. Retain only non-secret evidence. Controller bootstrap and the #2713 private-bridge rollout are later gates. The standalone preview/dev-demo gRPC paths fail closed until this issuer bootstrap and live denial proof are complete. +7. With the controller still inactive, request the fixed standalone internal Gateway and TCP Proxy Certificates through the scoped writer, then request the eight standalone per-workload gRPC Certificates (five publication workloads, Account, Game Session, and Social Groups) for `dev` and a disposable `pr-N` namespace through that same writer. Observe `Ready`, key-complete output Secrets, and served transport identities/chains. The runtime workflow consumes only the projected leaf keys and public `ca.crt`; after validating every gRPC leaf it deletes the legacy runtime `firemud-grpc-ca` signing-key Secret and old static leaf-source Secrets. Repeat unauthorized direct CertificateRequest and Certificate tests after the issuer becomes Ready; an admission-only dry-run before issuance is not proof that unauthorized signing cannot occur. Retain only non-secret evidence. Controller bootstrap and the #2713 private-bridge rollout are later gates. The standalone preview/dev-demo gRPC paths fail closed until this issuer bootstrap and live denial proof are complete. ## Recovery copy and rotation diff --git a/k8s/trust-bootstrap/issuance-admission.yaml b/k8s/trust-bootstrap/issuance-admission.yaml index a831a48a98..c0f954dabf 100644 --- a/k8s/trust-bootstrap/issuance-admission.yaml +++ b/k8s/trust-bootstrap/issuance-admission.yaml @@ -57,7 +57,7 @@ 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|social-groups-service))$'))) message: internal CertificateRequests must use the canonical ClusterIssuer and be owned by a canonical Certificate reason: Forbidden - expression: >- @@ -112,7 +112,7 @@ 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|social-groups-service))$'))) message: internal CertificateRequest approval and status may not alter its canonical spec or ownership reason: Forbidden @@ -149,24 +149,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|social-groups-service)$') && 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|social-groups-service)$') && 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|social-groups-service)$') && 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|social-groups-service)$') && request.namespace.matches('^(dev|pr-[1-9][0-9]{0,50})$'))))) validations: - expression: >- @@ -174,21 +174,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|social-groups-service))$')) || (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|social-groups-service))$')) || (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|social-groups-service))$') && 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|social-groups-service)$')) || (!object.metadata.name.contains('-grpc-') && object.spec.secretName == object.metadata.name)) && has(object.spec.isCA) && @@ -264,10 +264,16 @@ 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.metadata.name.endsWith('-grpc-social-groups-service') && + object.spec.secretName == 'firemud-grpc-social-groups-service' && + object.spec.issuerRef.name == 'firemud-ca-issuer' && + object.spec.dnsNames == ['social-groups-service', 'social-groups-service.' + request.namespace, 'social-groups-service.' + request.namespace + '.svc', 'social-groups-service.' + request.namespace + '.svc.cluster.local'] && + object.spec.uris == ['spiffe://firemud/ns/' + request.namespace + '/sa/social-groups-service'] && object.spec.usages == ['digital signature', 'key encipherment', 'server auth', '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))$') && + object.metadata.name.matches('^(dev|pr-[1-9][0-9]{0,50})-(tls|telnet-tls|gateway-internal-ws|tcp-proxy-bridge|grpc-(game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service|social-groups-service))$') && has(object.spec.issuerRef) && object.spec.issuerRef.name == 'firemud-ca-issuer' && object.spec.issuerRef.kind == 'ClusterIssuer' && diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java index f2bb0be542..c2775dd835 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java @@ -67,6 +67,8 @@ public final class HostedIdentityContract { public static final String GRPC_ACCOUNT_ROLE = "grpc-account-service"; public static final String GRPC_GAME_SESSION_WORKLOAD = "game-session-service"; public static final String GRPC_GAME_SESSION_ROLE = "grpc-game-session-service"; + public static final String GRPC_SOCIAL_GROUPS_WORKLOAD = "social-groups-service"; + public static final String GRPC_SOCIAL_GROUPS_ROLE = "grpc-social-groups-service"; public static final List GRPC_PUBLICATION_WORKLOADS = List.of( "game-design-service", @@ -104,6 +106,7 @@ public static String grpcPublicationRole(String workload) { public static boolean isGrpcWorkloadIdentityRole(String role) { return GRPC_ACCOUNT_ROLE.equals(role) || GRPC_GAME_SESSION_ROLE.equals(role) + || GRPC_SOCIAL_GROUPS_ROLE.equals(role) || isGrpcPublicationRole(role); } diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java index 08ca23e0ef..7ca52f52a8 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java @@ -220,6 +220,17 @@ private RoleMaterial grpcGameSession( batch); } + private RoleMaterial grpcSocialGroups( + KubernetesClient client, EnvironmentIdentityPlan plan, MaterializationBatch batch) { + return grpcWorkloadIdentity( + client, + plan, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD, + plan.grpcSocialGroupsCertificateName(), + batch); + } + private RoleMaterial grpcWorkloadIdentity( KubernetesClient client, EnvironmentIdentityPlan plan, @@ -392,6 +403,9 @@ private RotationSnapshot rotationSnapshot(KubernetesClient client, EnvironmentId observations.put( HostedIdentityContract.GRPC_GAME_SESSION_ROLE, rotationObservation(client, plan, HostedIdentityContract.GRPC_GAME_SESSION_ROLE)); + observations.put( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + rotationObservation(client, plan, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)); String selectedRole = selectSerializedRole( observations.values().stream().map(RotationObservation::state).toList()); @@ -1275,6 +1289,10 @@ public RoleMaterial grpcGameSession() { return CertificateMaterialService.this.grpcGameSession(client, plan, this); } + public RoleMaterial grpcSocialGroups() { + return CertificateMaterialService.this.grpcSocialGroups(client, plan, this); + } + private List certificateRequests() { if (certificateRequests == null) { certificateRequests = diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java index 928ea36bcd..de8f25897c 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java @@ -111,6 +111,18 @@ public GenericKubernetesResource grpcGameSession( renewBefore); } + /** Builds the retained Social Groups workload identity used by protected profile/presence calls. */ + public GenericKubernetesResource grpcSocialGroups( + EnvironmentIdentityPlan plan, Duration renewBefore) { + return grpcWorkloadIdentity( + plan, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD, + plan.grpcSocialGroupsCertificateName(), + plan.grpcSocialGroupsSourceSecretName(), + renewBefore); + } + GenericKubernetesResource grpcWorkloadIdentity( EnvironmentIdentityPlan plan, String role, diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutService.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutService.java index 4f28af76e0..46749f4706 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutService.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutService.java @@ -122,6 +122,19 @@ public RolloutResult sync( .put( HostedIdentityContract.GRPC_REVISION_ANNOTATION, combinedGrpcWorkloadRevision(grpcRevision, gameSessionRevision, "game-session-leaf")); + String socialGroupsRevision = + grpcWorkloadIdentityRevisions.get(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); + if (socialGroupsRevision == null) { + throw new IllegalArgumentException( + "Social Groups gRPC workload identity revision is required"); + } + revisionsByDeployment + .computeIfAbsent( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD, ignored -> new LinkedHashMap<>()) + .put( + HostedIdentityContract.GRPC_REVISION_ANNOTATION, + combinedGrpcWorkloadRevision( + grpcRevision, socialGroupsRevision, "social-groups-leaf")); } Map readinessByDeployment = new LinkedHashMap<>(); for (Map.Entry> entry : revisionsByDeployment.entrySet()) { @@ -140,6 +153,7 @@ public RolloutResult sync( requiredGrpcConsumers.addAll(HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS); requiredGrpcConsumers.add(HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD); requiredGrpcConsumers.add(HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); + requiredGrpcConsumers.add(HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD); } boolean grpcReady = requiredGrpcConsumers.stream() diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java index ab13f2963c..f6da572281 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java @@ -182,6 +182,8 @@ public static List identitySecretNames(EnvironmentIdentityPlan plan) { names.add(plan.grpcAccountSourceSecretName() + "-previous"); names.add(plan.grpcGameSessionSourceSecretName()); names.add(plan.grpcGameSessionSourceSecretName() + "-previous"); + names.add(plan.grpcSocialGroupsSourceSecretName()); + names.add(plan.grpcSocialGroupsSourceSecretName() + "-previous"); return List.copyOf(names); } @@ -222,6 +224,7 @@ static List requiredDeploymentNames(EnvironmentIdentityPlan plan) { names.addAll(HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS); names.add(HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD); names.add(HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); + names.add(HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD); names.addAll(DeploymentRolloutService.BRIDGE_DEPLOYMENTS); return List.copyOf(names); } @@ -240,6 +243,7 @@ public static List requiredCertificateNames(EnvironmentIdentityPlan plan .toList()); names.add(plan.grpcAccountCertificateName()); names.add(plan.grpcGameSessionCertificateName()); + names.add(plan.grpcSocialGroupsCertificateName()); return List.copyOf(names); } @@ -258,6 +262,7 @@ static List runtimeSecretNames(EnvironmentIdentityPlan plan) { .toList()); names.add(plan.grpcAccountSecretName()); names.add(plan.grpcGameSessionSecretName()); + names.add(plan.grpcSocialGroupsSecretName()); return List.copyOf(names); } diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java index e59c2fbb77..d53f0c2b61 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java @@ -45,7 +45,8 @@ public record EnvironmentIdentityPlan( .map(HostedIdentityContract::grpcPublicationRole), Stream.of( HostedIdentityContract.GRPC_ACCOUNT_ROLE, - HostedIdentityContract.GRPC_GAME_SESSION_ROLE)) + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)) .collect(Collectors.toUnmodifiableSet()); if (!grpcWorkloadIdentityCertificateNames.keySet().equals(expectedGrpcWorkloadIdentityRoles) || !grpcWorkloadIdentitySecretNames.keySet().equals(expectedGrpcWorkloadIdentityRoles) @@ -127,6 +128,20 @@ public String grpcGameSessionSourceSecretName() { return grpcWorkloadIdentitySourceSecretNames.get(HostedIdentityContract.GRPC_GAME_SESSION_ROLE); } + public String grpcSocialGroupsCertificateName() { + return grpcWorkloadIdentityCertificateNames.get( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); + } + + public String grpcSocialGroupsSecretName() { + return grpcWorkloadIdentitySecretNames.get(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); + } + + public String grpcSocialGroupsSourceSecretName() { + return grpcWorkloadIdentitySourceSecretNames.get( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); + } + public String grpcPublicationUriSan(String workload) { return grpcWorkloadIdentityUriSan(workload); } diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/HostedEnvironmentIdentityStatus.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/HostedEnvironmentIdentityStatus.java index 2ff7020ea8..745e77d546 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/HostedEnvironmentIdentityStatus.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/HostedEnvironmentIdentityStatus.java @@ -16,6 +16,7 @@ public class HostedEnvironmentIdentityStatus { private RoleStatus grpc; private RoleStatus grpcAccountService; private RoleStatus grpcGameSessionService; + private RoleStatus grpcSocialGroupsService; private Map grpcPublication; private RuntimeProfile profile; @@ -104,6 +105,14 @@ public void setGrpcGameSessionService(RoleStatus grpcGameSessionService) { this.grpcGameSessionService = copyRole(grpcGameSessionService); } + public RoleStatus getGrpcSocialGroupsService() { + return copyRole(grpcSocialGroupsService); + } + + public void setGrpcSocialGroupsService(RoleStatus grpcSocialGroupsService) { + this.grpcSocialGroupsService = copyRole(grpcSocialGroupsService); + } + public Map getGrpcPublication() { if (grpcPublication == null) { return null; diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java index 80db24cee7..ec6f67cecd 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java @@ -172,6 +172,9 @@ public UpdateControl reconcile( materialRequests.add( new RoleMaterialRequest( HostedIdentityContract.GRPC_GAME_SESSION_ROLE, materialization::grpcGameSession)); + materialRequests.add( + new RoleMaterialRequest( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, materialization::grpcSocialGroups)); List rolePipeline = new ArrayList<>(); for (RoleMaterialRequest request : materialRequests) { CertificateMaterialService.RoleMaterial material = request.material().get(); @@ -247,6 +250,9 @@ public UpdateControl reconcile( workloadIdentityRevisions.put( HostedIdentityContract.GRPC_GAME_SESSION_ROLE, projections.get(HostedIdentityContract.GRPC_GAME_SESSION_ROLE).revision()); + workloadIdentityRevisions.put( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + projections.get(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE).revision()); DeploymentRolloutService.RolloutResult rollout = deploymentRolloutService.sync( client, @@ -546,7 +552,8 @@ private boolean workloadIdentityEvidenceComplete() { return material != null && material.ready(); }) && roleReady(HostedIdentityContract.GRPC_ACCOUNT_ROLE) - && roleReady(HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + && roleReady(HostedIdentityContract.GRPC_GAME_SESSION_ROLE) + && roleReady(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); } private boolean roleReady(String role) { @@ -1053,7 +1060,7 @@ private UpdateControl status( phase = HostedEnvironmentIdentityStatus.Phase.Verifying; reason = "WorkloadIdentityEvidenceIncomplete"; message = - "all five protected publication projections and the exact Account and Game Session workload identities are required for readiness; readiness does not authorize publication methods"; + "all five protected publication projections and the exact Account, Game Session, and Social Groups workload identities are required for readiness; readiness does not authorize publication methods"; } HostedEnvironmentIdentityStatus updatedStatus = statusService.status( @@ -1086,6 +1093,10 @@ private UpdateControl status( roleStatus( materials.material(HostedIdentityContract.GRPC_GAME_SESSION_ROLE), previousRole(resource, HostedIdentityContract.GRPC_GAME_SESSION_ROLE))); + updatedStatus.setGrpcSocialGroupsService( + roleStatus( + materials.material(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE), + previousRole(resource, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE))); updatedStatus.setGrpcPublication(publicationRoleStatus(resource, materials)); resource.setStatus(updatedStatus); return UpdateControl.patchStatus(resource).rescheduleAfter(properties.getReconcileInterval()); @@ -1150,6 +1161,8 @@ static HostedEnvironmentIdentityStatus.RoleStatus previousRole( case HostedIdentityContract.GRPC_ACCOUNT_ROLE -> resource.getStatus().getGrpcAccountService(); case HostedIdentityContract.GRPC_GAME_SESSION_ROLE -> resource.getStatus().getGrpcGameSessionService(); + case HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE -> + resource.getStatus().getGrpcSocialGroupsService(); default -> throw new IllegalArgumentException("unsupported identity role: " + role); }; } diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlanner.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlanner.java index d8b62306d7..d79146903d 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlanner.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlanner.java @@ -84,6 +84,15 @@ public EnvironmentIdentityPlan plan(String name) { publicationSecrets.put( HostedIdentityContract.GRPC_GAME_SESSION_ROLE, "firemud-grpc-" + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); + publicationCertificates.put( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + materialPrefix + "-grpc-" + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD); + publicationSourceSecrets.put( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + materialPrefix + "-grpc-" + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD); + publicationSecrets.put( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + "firemud-grpc-" + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD); return new EnvironmentIdentityPlan( name, properties.getControlNamespace(), diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java index 45ab300641..39ae3f8dd2 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java @@ -456,7 +456,8 @@ void materializationBatchReusesOneRotationSelectionSnapshot() { plan.grpcPublicationSecretName("game-logic-service"), plan.grpcPublicationSecretName("automation-scripting-service"), plan.grpcAccountSecretName(), - plan.grpcGameSessionSecretName()), + plan.grpcGameSessionSecretName(), + plan.grpcSocialGroupsSecretName()), java.util.Set.copyOf(read.getAllValues())); clearInvocations(runtimeSecrets); @@ -1990,6 +1991,26 @@ void grpcUsesTheAcceptedProjectionWithoutRereadingTheDeferredSource() { .thenReturn(gameSessionSourceResource); when(gameSessionSourceResource.get()) .thenReturn(certManagerSource(plan, gameSessionRole, gameSessionSourceName, data)); + String socialGroupsRole = HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE; + String socialGroupsName = plan.grpcSocialGroupsSecretName(); + String socialGroupsSourceName = plan.grpcSocialGroupsSourceSecretName(); + String socialGroupsRevision = SecretProjectionService.revisionForRole(socialGroupsRole, data); + Resource socialGroupsProjectionResource = mock(Resource.class); + when(secretClient.runtimeSecrets().withName(socialGroupsName)) + .thenReturn(socialGroupsProjectionResource); + when(socialGroupsProjectionResource.get()) + .thenReturn( + ownedSecret( + plan, + socialGroupsRole, + socialGroupsName, + data, + acceptedAnnotations(socialGroupsRevision, "1".repeat(64)))); + Resource socialGroupsSourceResource = mock(Resource.class); + when(secretClient.identitySecrets().withName(socialGroupsSourceName)) + .thenReturn(socialGroupsSourceResource); + when(socialGroupsSourceResource.get()) + .thenReturn(certManagerSource(plan, socialGroupsRole, socialGroupsSourceName, data)); Secret ownedGrpc = ownedSecret(plan, HostedIdentityContract.GRPC_ROLE, plan.grpcSecretName(), data, Map.of()); Resource grpcSourceResource = mock(Resource.class); diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java index 2bbe10e1f8..9a3fed3895 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java @@ -189,6 +189,33 @@ void gameSessionCertificateUsesExactStableWorkloadIdentity() { assertSecretTemplate(certificateSpec, plan, HostedIdentityContract.GRPC_GAME_SESSION_ROLE); } + @Test + void socialGroupsCertificateUsesExactStableWorkloadIdentity() { + var properties = propertiesWithRenewBefore(); + var plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); + var certificate = + new CertificateResourceFactory().grpcSocialGroups(plan, properties.getGrpcRenewBefore()); + var certificateSpec = spec(certificate); + + assertEquals("pr-42-grpc-social-groups-service", certificate.getMetadata().getName()); + assertEquals("pr-42-grpc-social-groups-service", certificateSpec.get("secretName")); + assertEquals("firemud-ca-issuer", issuerName(certificateSpec)); + assertEquals( + java.util.List.of("spiffe://firemud/ns/pr-42/sa/social-groups-service"), + certificateSpec.get("uris")); + assertEquals( + java.util.List.of( + "social-groups-service", + "social-groups-service.pr-42", + "social-groups-service.pr-42.svc", + "social-groups-service.pr-42.svc.cluster.local"), + certificateSpec.get("dnsNames")); + assertEquals( + java.util.List.of("digital signature", "key encipherment", "server auth", "client auth"), + certificateSpec.get("usages")); + assertSecretTemplate(certificateSpec, plan, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); + } + @Test void certificateFactoryPublicSurfaceContainsOnlyMaterialFactories() { var declaredMethods = @@ -200,7 +227,7 @@ void certificateFactoryPublicSurfaceContainsOnlyMaterialFactories() { .filter(method -> java.lang.reflect.Modifier.isPublic(method.getModifiers())) .toList(); - assertEquals(7, publicMethods.size()); + assertEquals(8, publicMethods.size()); assertEquals( java.util.Set.of( "ingress", @@ -209,7 +236,8 @@ void certificateFactoryPublicSurfaceContainsOnlyMaterialFactories() { "tcpProxyBridge", "grpcPublication", "grpcAccount", - "grpcGameSession"), + "grpcGameSession", + "grpcSocialGroups"), publicMethods.stream() .map(java.lang.reflect.Method::getName) .collect(java.util.stream.Collectors.toUnmodifiableSet())); diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java index 22cceb3790..41b56b51d0 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java @@ -70,6 +70,7 @@ void workloadIdentityRevisionRollsAccountAndPublicationDeploymentsUntilAllReady( "tcp-proxy-service", "account-service", "game-session-service", + "social-groups-service", "game-design-service", "world-management-service", "entity-management-service", @@ -83,6 +84,7 @@ void workloadIdentityRevisionRollsAccountAndPublicationDeploymentsUntilAllReady( 3L)); ArgumentCaptor accountReplacement = ArgumentCaptor.forClass(Deployment.class); ArgumentCaptor gameSessionReplacement = ArgumentCaptor.forClass(Deployment.class); + ArgumentCaptor socialGroupsReplacement = ArgumentCaptor.forClass(Deployment.class); when(graph.resources().get("account-service").get()) .thenReturn( readyDeployment( @@ -102,12 +104,25 @@ void workloadIdentityRevisionRollsAccountAndPublicationDeploymentsUntilAllReady( "grpc-current", "game-session-old", "game-session-leaf")), 3L)) .thenAnswer(invocation -> gameSessionReplacement.getValue()); + when(graph.resources().get("social-groups-service").get()) + .thenReturn( + readyDeployment( + "social-groups-service", + Map.of( + HostedIdentityContract.GRPC_REVISION_ANNOTATION, + expectedWorkloadRevision( + "grpc-current", "social-groups-old", "social-groups-leaf")), + 3L)) + .thenAnswer(invocation -> socialGroupsReplacement.getValue()); ReplaceDeletable lockedAccount = mock(ReplaceDeletable.class); when(graph.resources().get("account-service").lockResourceVersion("rv-3")) .thenReturn(lockedAccount); ReplaceDeletable lockedGameSession = mock(ReplaceDeletable.class); when(graph.resources().get("game-session-service").lockResourceVersion("rv-3")) .thenReturn(lockedGameSession); + ReplaceDeletable lockedSocialGroups = mock(ReplaceDeletable.class); + when(graph.resources().get("social-groups-service").lockResourceVersion("rv-3")) + .thenReturn(lockedSocialGroups); for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { String role = HostedIdentityContract.grpcPublicationRole(workload); String publicationRevision = @@ -143,6 +158,8 @@ void workloadIdentityRevisionRollsAccountAndPublicationDeploymentsUntilAllReady( workloadIdentityRevisions.put(HostedIdentityContract.GRPC_ACCOUNT_ROLE, "account-current"); workloadIdentityRevisions.put( HostedIdentityContract.GRPC_GAME_SESSION_ROLE, "game-session-current"); + workloadIdentityRevisions.put( + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, "social-groups-current"); DeploymentRolloutService.RolloutResult result = new DeploymentRolloutService() .sync( @@ -187,6 +204,17 @@ void workloadIdentityRevisionRollsAccountAndPublicationDeploymentsUntilAllReady( .getMetadata() .getAnnotations() .get(HostedIdentityContract.GRPC_REVISION_ANNOTATION)); + verify(lockedSocialGroups).replace(socialGroupsReplacement.capture()); + assertEquals( + expectedWorkloadRevision( + "grpc-current", "social-groups-current", "social-groups-leaf"), + socialGroupsReplacement + .getValue() + .getSpec() + .getTemplate() + .getMetadata() + .getAnnotations() + .get(HostedIdentityContract.GRPC_REVISION_ANNOTATION)); Deployment converged = replacement.getValue(); converged.getMetadata().setGeneration(4L); @@ -197,6 +225,9 @@ void workloadIdentityRevisionRollsAccountAndPublicationDeploymentsUntilAllReady( Deployment convergedGameSession = gameSessionReplacement.getValue(); convergedGameSession.getMetadata().setGeneration(4L); convergedGameSession.getStatus().setObservedGeneration(4L); + Deployment convergedSocialGroups = socialGroupsReplacement.getValue(); + convergedSocialGroups.getMetadata().setGeneration(4L); + convergedSocialGroups.getStatus().setObservedGeneration(4L); DeploymentRolloutService.RolloutResult secondResult = new DeploymentRolloutService() .sync( @@ -225,15 +256,19 @@ void workloadIdentityRevisionRollsAccountAndPublicationDeploymentsUntilAllReady( verify(lockedAccount, times(1)).replace(org.mockito.ArgumentMatchers.any(Deployment.class)); verify(graph.resources().get("game-session-service")).lockResourceVersion("rv-3"); verify(lockedGameSession, times(1)).replace(org.mockito.ArgumentMatchers.any(Deployment.class)); + verify(graph.resources().get("social-groups-service")).lockResourceVersion("rv-3"); + verify(lockedSocialGroups, times(1)) + .replace(org.mockito.ArgumentMatchers.any(Deployment.class)); } @Test - void sharedGrpcRevisionRollsAllSevenDistinctConsumersAndLeavesUnrelatedWorkloadUntouched() { + void sharedGrpcRevisionRollsAllEightDistinctConsumersAndLeavesUnrelatedWorkloadUntouched() { EnvironmentIdentityPlan plan = planWithConsumers(); List grpcWorkloads = new java.util.ArrayList<>(HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS); grpcWorkloads.add(HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD); grpcWorkloads.add(HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); + grpcWorkloads.add(HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD); String[] deploymentNames = java.util.stream.Stream.concat( java.util.stream.Stream.of("tcp-proxy-service", "logging-admin-service"), @@ -304,18 +339,20 @@ void sharedGrpcRevisionRollsAllSevenDistinctConsumersAndLeavesUnrelatedWorkloadU } @Test - void accountAndGameSessionLeafRolloutsGateReadinessOutsideThePlanConsumerList() { + void dedicatedLeafRolloutsGateReadinessOutsideThePlanConsumerList() { List grpcWorkloads = new java.util.ArrayList<>(HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS); grpcWorkloads.add(HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD); grpcWorkloads.add(HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD); + grpcWorkloads.add(HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD); Map> pendingReplacements = new LinkedHashMap<>(); Map> pendingLocks = new LinkedHashMap<>(); for (String pendingWorkload : List.of( HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD, - HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD)) { + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD)) { EnvironmentIdentityPlan plan = planWithConsumers(); String[] deploymentNames = java.util.stream.Stream.concat( @@ -1140,6 +1177,9 @@ private static String grpcRoleForWorkload(String workload) { if (HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD.equals(workload)) { return HostedIdentityContract.GRPC_GAME_SESSION_ROLE; } + if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD.equals(workload)) { + return HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE; + } return HostedIdentityContract.grpcPublicationRole(workload); } @@ -1150,6 +1190,9 @@ private static String leafKindForRole(String role) { if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { return "game-session-leaf"; } + if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { + return "social-groups-leaf"; + } return "publication-leaf"; } } diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java index 7b5cbc6985..ff8128ad4e 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java @@ -236,7 +236,8 @@ void identityRoleNamesOnlyCoverCertManagerCertificates() { "pr-42-grpc-game-logic-service", "pr-42-grpc-automation-scripting-service", "pr-42-grpc-account-service", - "pr-42-grpc-game-session-service"), + "pr-42-grpc-game-session-service", + "pr-42-grpc-social-groups-service"), HostedIdentityScopeService.requiredCertificateNames(plan)); } @@ -254,6 +255,7 @@ void runtimeRoleCoversBothBridgeDeploymentsAndEveryGrpcConsumer() { "automation-scripting-service", "account-service", "game-session-service", + "social-groups-service", "spring-cloud-gateway", "tcp-proxy-service"), HostedIdentityScopeService.requiredDeploymentNames(plan)); diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityTestFixtures.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityTestFixtures.java index f741a12127..47b6195d43 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityTestFixtures.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityTestFixtures.java @@ -399,6 +399,20 @@ static StableBatchFixture stableBatchFixture() { .getMetadata() .getAnnotations() .put(HostedIdentityContract.PROVENANCE_ANNOTATION, "cert-manager"); + stubProjectionAndSource( + secretClient, + plan, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + acceptedData, + acceptedData, + acceptedData); + secretClient + .runtimeSecrets() + .withName(secretName(plan, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)) + .get() + .getMetadata() + .getAnnotations() + .put(HostedIdentityContract.PROVENANCE_ANNOTATION, "cert-manager"); SecretMaterialValidator validator = mock(SecretMaterialValidator.class); SecretMaterialValidator.MaterialSummary summary = new SecretMaterialValidator.MaterialSummary( @@ -515,6 +529,9 @@ static String secretName(EnvironmentIdentityPlan plan, String role) { if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { yield plan.grpcGameSessionSecretName(); } + if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { + yield plan.grpcSocialGroupsSecretName(); + } if (HostedIdentityContract.isGrpcPublicationRole(role)) { yield plan.grpcPublicationSecretName( role.substring(HostedIdentityContract.GRPC_PUBLICATION_ROLE_PREFIX.length())); @@ -531,6 +548,9 @@ static String sourceSecretName(EnvironmentIdentityPlan plan, String role) { if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { return plan.grpcGameSessionSourceSecretName(); } + if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { + return plan.grpcSocialGroupsSourceSecretName(); + } if (HostedIdentityContract.isGrpcPublicationRole(role)) { return plan.grpcPublicationSourceSecretName(grpcPublicationWorkload(role)); } diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java index 62eafd9fe7..928da2e43a 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java @@ -1406,7 +1406,8 @@ void caRotationValidatesOnlyTheSelectedNewSourceAndPinsOtherSharedRoles() { for (String role : List.of( HostedIdentityContract.GRPC_ACCOUNT_ROLE, - HostedIdentityContract.GRPC_GAME_SESSION_ROLE)) { + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)) { stubProjectionAndSource(secretClient, plan, role, acceptedData, acceptedData, acceptedData); } stubCertificate( @@ -1587,7 +1588,8 @@ private static DriftSelectionFixture driftSelectionFixture(boolean sourceAdvance for (String role : List.of( HostedIdentityContract.GRPC_ACCOUNT_ROLE, - HostedIdentityContract.GRPC_GAME_SESSION_ROLE)) { + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)) { stubProjectionAndSource(secretClient, plan, role, acceptedData, acceptedData, acceptedData); } stubCertificate( diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java index d9e7c3e015..b204f4d53e 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java @@ -243,7 +243,7 @@ void workloadIdentityProjectionMustBeAcceptedBeforeReadiness() { status.getGrpcPublication().keySet()); assertTrue(status.getGrpcPublication().values().stream().allMatch(java.util.Objects::nonNull)); assertEquals( - HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.size() + 7, + HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS.size() + 8, acknowledgedProjections.size()); assertEquals( "awaiting-acceptance", @@ -1641,7 +1641,8 @@ record SourceProgressCase( for (String role : List.of( HostedIdentityContract.GRPC_ACCOUNT_ROLE, - HostedIdentityContract.GRPC_GAME_SESSION_ROLE)) { + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)) { for (SourceProgressCase rollbackCase : rollbackCases) { DeploymentHeadGateFixture fixture = new DeploymentHeadGateFixture( @@ -1677,8 +1678,10 @@ record SourceProgressCase( "replacement-" + role + "-" + rollbackCase.failure()); if (HostedIdentityContract.GRPC_ACCOUNT_ROLE.equals(role)) { when(fixture.batch.grpcAccount()).thenReturn(olderSource); - } else { + } else if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { when(fixture.batch.grpcGameSession()).thenReturn(olderSource); + } else { + when(fixture.batch.grpcSocialGroups()).thenReturn(olderSource); } UpdateControl result = fixture.reconcile(); @@ -1719,13 +1722,19 @@ void grpcWorkloadIdentityStatusReadbackAllowsLegacyAbsence() { assertNull( HostedIdentityReconciler.previousRole( resource, HostedIdentityContract.GRPC_GAME_SESSION_ROLE)); + assertNull( + HostedIdentityReconciler.previousRole( + resource, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)); HostedEnvironmentIdentityStatus.RoleStatus account = roleStatus("account-revision", 4L, 2L, "a".repeat(64)); HostedEnvironmentIdentityStatus.RoleStatus gameSession = roleStatus("game-session-revision", 5L, 3L, "b".repeat(64)); + HostedEnvironmentIdentityStatus.RoleStatus socialGroups = + roleStatus("social-groups-revision", 6L, 4L, "c".repeat(64)); status.setGrpcAccountService(account); status.setGrpcGameSessionService(gameSession); + status.setGrpcSocialGroupsService(socialGroups); resource.setStatus(status); HostedEnvironmentIdentityStatus.RoleStatus accountReadback = @@ -1733,6 +1742,9 @@ void grpcWorkloadIdentityStatusReadbackAllowsLegacyAbsence() { HostedEnvironmentIdentityStatus.RoleStatus gameSessionReadback = HostedIdentityReconciler.previousRole( resource, HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + HostedEnvironmentIdentityStatus.RoleStatus socialGroupsReadback = + HostedIdentityReconciler.previousRole( + resource, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); assertNotSame(account, accountReadback); assertNotSame(gameSession, gameSessionReadback); assertEquals(account.getRevision(), accountReadback.getRevision()); @@ -1744,6 +1756,12 @@ void grpcWorkloadIdentityStatusReadbackAllowsLegacyAbsence() { assertEquals( gameSession.getSourceObjectGeneration(), gameSessionReadback.getSourceObjectGeneration()); assertEquals(gameSession.getSpkiSha256(), gameSessionReadback.getSpkiSha256()); + assertNotSame(socialGroups, socialGroupsReadback); + assertEquals(socialGroups.getRevision(), socialGroupsReadback.getRevision()); + assertEquals(socialGroups.getSourceGeneration(), socialGroupsReadback.getSourceGeneration()); + assertEquals( + socialGroups.getSourceObjectGeneration(), socialGroupsReadback.getSourceObjectGeneration()); + assertEquals(socialGroups.getSpkiSha256(), socialGroupsReadback.getSpkiSha256()); } @Test @@ -1948,6 +1966,7 @@ private static boolean crdSchemaAccepts(Map propertySchema, Object value) Map publicationSchema = schemaMap(statusProperties.get("grpcPublication")); assertEquals(consumerSchema, statusProperties.get("grpcAccountService")); assertEquals(consumerSchema, statusProperties.get("grpcGameSessionService")); + assertEquals(consumerSchema, statusProperties.get("grpcSocialGroupsService")); assertEquals( consumerSchema, publicationSchema.get("additionalProperties"), @@ -2330,8 +2349,10 @@ void statusMaterialIsMappedByRoleRatherThanCallPosition() { assertEquals("5".repeat(64), status.getGrpc().getSpkiSha256()); assertEquals("b".repeat(64), status.getGrpcAccountService().getSpkiSha256()); assertEquals("c".repeat(64), status.getGrpcGameSessionService().getSpkiSha256()); + assertEquals("d".repeat(64), status.getGrpcSocialGroupsService().getSpkiSha256()); assertEquals(1L, status.getGrpcAccountService().getSourceGeneration()); assertEquals(1L, status.getGrpcGameSessionService().getSourceGeneration()); + assertEquals(1L, status.getGrpcSocialGroupsService().getSourceGeneration()); ArgumentCaptor gatewayRevision = ArgumentCaptor.forClass(String.class); ArgumentCaptor> workloadIdentityRevisions = ArgumentCaptor.forClass(Map.class); @@ -2361,7 +2382,9 @@ void statusMaterialIsMappedByRoleRatherThanCallPosition() { HostedIdentityContract.GRPC_ACCOUNT_ROLE, "revision-" + HostedIdentityContract.GRPC_ACCOUNT_ROLE, HostedIdentityContract.GRPC_GAME_SESSION_ROLE, - "revision-" + HostedIdentityContract.GRPC_GAME_SESSION_ROLE), + "revision-" + HostedIdentityContract.GRPC_GAME_SESSION_ROLE, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, + "revision-" + HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE), workloadIdentityRevisions.getValue()); verify(fixture.runtime, times(2)) .validateTcpProxyService(fixture.client, fixture.plan, expected); @@ -2457,6 +2480,8 @@ private static void setGrpcWorkloadRoleStatus( status.setGrpcAccountService(roleStatus); } else if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { status.setGrpcGameSessionService(roleStatus); + } else if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { + status.setGrpcSocialGroupsService(roleStatus); } else { throw new IllegalArgumentException("unsupported workload identity role: " + role); } @@ -2470,6 +2495,9 @@ private static HostedEnvironmentIdentityStatus.RoleStatus grpcWorkloadRoleStatus if (HostedIdentityContract.GRPC_GAME_SESSION_ROLE.equals(role)) { return status.getGrpcGameSessionService(); } + if (HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE.equals(role)) { + return status.getGrpcSocialGroupsService(); + } throw new IllegalArgumentException("unsupported workload identity role: " + role); } @@ -2557,6 +2585,8 @@ private DeploymentHeadGateFixture(RuntimeProfileService.RuntimeProfile runtimePr .thenReturn(material(plan, HostedIdentityContract.GRPC_ACCOUNT_ROLE, "b")); when(batch.grpcGameSession()) .thenReturn(material(plan, HostedIdentityContract.GRPC_GAME_SESSION_ROLE, "c")); + when(batch.grpcSocialGroups()) + .thenReturn(material(plan, HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE, "d")); when(batch.grpcPublication(anyString())) .thenAnswer( invocation -> { diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java index f304c67c7d..827dca47cc 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java @@ -73,6 +73,15 @@ void derivesPreviewTargetsFromOnlyTheClosedNameContract() { assertEquals( plan.grpcGameSessionSecretName(), plan.secretName(HostedIdentityContract.GRPC_GAME_SESSION_ROLE)); + assertEquals("pr-42-grpc-social-groups-service", plan.grpcSocialGroupsCertificateName()); + assertEquals("pr-42-grpc-social-groups-service", plan.grpcSocialGroupsSourceSecretName()); + assertEquals("firemud-grpc-social-groups-service", plan.grpcSocialGroupsSecretName()); + assertEquals( + "spiffe://firemud/ns/pr-42/sa/social-groups-service", + plan.grpcWorkloadIdentityUriSan(HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD)); + assertEquals( + plan.grpcSocialGroupsSecretName(), + plan.secretName(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE)); for (String workload : HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS) { assertEquals("pr-42-grpc-" + workload, plan.grpcPublicationSourceSecretName(workload)); assertEquals("firemud-grpc-" + workload, plan.grpcPublicationSecretName(workload)); From 3574e6b2b9beb0069c0a008382094b5a87ca4dd8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:46:00 +1300 Subject: [PATCH 37/75] Revalidate JOIN retries and recover trusted demo membership --- .../account-service/runtime-and-data.md | 2 +- .../accountservice/data/TestDataSeeder.java | 62 +++-- .../service/impl/AccountServiceImpl.java | 54 ++++- .../data/TestDataSeederTest.java | 129 +++++++++- .../service/impl/AccountServiceImplTest.java | 222 +++++++++++++++++- 5 files changed, 441 insertions(+), 28 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index f421afdae9..0f9f6a205c 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -18,7 +18,7 @@ Account implements bounded owner-local cleanup of expired password-reset, email- Account also performs a bounded sweep of public connect-scope evidence after its configured scope expiry. It deletes only rows with a valid parsed expiry at or before the captured UTC time and no `account_join_operations` reference of any status; malformed expiry rows remain untouched without blocking valid rows. V27 adds a restrictive foreign key from each JOIN operation to its exact scope row, fencing concurrent intent insertion against deletion. The sweep does not expire JOIN operation receipts or change account-deletion retention. -The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback returns a stored terminal outcome when present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. Successful repeated JOINs replay the stored operation result; `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. +The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback applies the terminal retry checks when a terminal row is present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. An exact retry of a terminal JOIN replays its stored result only after the retained scope is still unexpired and current target/entitlement authority is available and matches the stored policy digest; expiry, unavailable authority, or changed policy fails closed without rewriting the terminal operation or membership. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java index a520d8ce5e..de5bde5a35 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java @@ -2,6 +2,8 @@ import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; +import java.util.Objects; +import java.util.Optional; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; @@ -36,16 +38,19 @@ public class TestDataSeeder implements ApplicationRunner { @Override @Transactional public void run(ApplicationArguments args) { + Optional existingDemoAccount = accountRepository.findByEmail(DEMO_EMAIL); + if (existingDemoAccount.isPresent() + && !DEMO_EMAIL.equals(existingDemoAccount.orElseThrow().getEmail())) { + throw new IllegalStateException("Demo account identity does not match configured email"); + } Account account = - accountRepository - .findByEmail(DEMO_EMAIL) - .orElseGet( - () -> { - Account seeded = new Account(); - seeded.setUsername(DEMO_USERNAME); - seeded.setEmail(DEMO_EMAIL); - return seeded; - }); + existingDemoAccount.orElseGet( + () -> { + Account seeded = new Account(); + seeded.setUsername(DEMO_USERNAME); + seeded.setEmail(DEMO_EMAIL); + return seeded; + }); account.setUsername(DEMO_USERNAME); account.setEmail(DEMO_EMAIL); @@ -54,15 +59,26 @@ public void run(ApplicationArguments args) { account.setEmailVerified(true); account = accountRepository.save(account); - if (!accountTenantMembershipRepository.existsByAccountIdAndTenantId( - account.getId(), DEMO_TENANT_ID)) { - AccountTenantMembership membership = new AccountTenantMembership(); - membership.setAccount(account); - membership.setTenantId(DEMO_TENANT_ID); + AccountTenantMembership membership = + accountTenantMembershipRepository + .findByAccountIdAndTenantId(account.getId(), DEMO_TENANT_ID) + .orElse(null); + if (membership == null) { + AccountTenantMembership seededMembership = new AccountTenantMembership(); + seededMembership.setAccount(account); + seededMembership.setTenantId(DEMO_TENANT_ID); + seededMembership.setGameplayAdmissionAllowed(true); + seededMembership.setLifecycleState("ACTIVE"); + seededMembership.setMembershipVersion(1); + seededMembership.setMembershipAuthorityGeneration(1); + seededMembership.setAuthorityProvenance("SEEDED_DEMO"); + accountTenantMembershipRepository.save(seededMembership); + } else if (isQuarantinedDemoMembership(account, membership)) { membership.setGameplayAdmissionAllowed(true); membership.setLifecycleState("ACTIVE"); - membership.setMembershipVersion(1); - membership.setMembershipAuthorityGeneration(1); + membership.setMembershipVersion(Math.addExact(membership.getMembershipVersion(), 1L)); + membership.setMembershipAuthorityGeneration( + Math.addExact(membership.getMembershipAuthorityGeneration(), 1L)); membership.setAuthorityProvenance("SEEDED_DEMO"); accountTenantMembershipRepository.save(membership); } @@ -78,6 +94,20 @@ public void run(ApplicationArguments args) { } } + private static boolean isQuarantinedDemoMembership( + Account account, AccountTenantMembership membership) { + return membership.getId() != null + && membership.getAccount() != null + && membership.getAccount().getId() != null + && Objects.equals(membership.getAccount().getId(), account.getId()) + && Objects.equals(membership.getTenantId(), DEMO_TENANT_ID) + && "LEGACY_UNVERIFIED".equals(membership.getLifecycleState()) + && "LEGACY_UNVERIFIED".equals(membership.getAuthorityProvenance()) + && !membership.isGameplayAdmissionAllowed() + && membership.getMembershipVersion() > 0L + && membership.getMembershipAuthorityGeneration() > 0L; + } + private String hashPassword(String password) { Argon2 argon2 = Argon2Factory.create(); char[] chars = password.toCharArray(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index b222af32d6..7057f9db5a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -611,7 +611,12 @@ private JoinPublicProductionResult joinPublicProductionForTrustedCaller( JoinOperation operation = outcomeReadback.orElseThrow(); requireMatchingJoinIntent(operation, requestId, callerBinding, retained); if (!"PENDING".equals(operation.status())) { - return resultFromJoinOperation(operation, true); + try { + return joinTransactionTemplate.execute( + transactionStatus -> replayTerminalJoin(operation, callerBinding, retained)); + } catch (RuntimeException policyCheckFailure) { + return joinRetryFailure(retained, "AUTH_UNAVAILABLE"); + } } recordJoinAttemptFailureAfterRollback(requestId, "AUTH_UNAVAILABLE"); } @@ -630,7 +635,7 @@ private JoinPublicProductionResult executeJoinAttempt( requireMatchingJoinIntent(operation, requestId, callerBinding, scope); if (!"PENDING".equals(operation.status())) { - return resultFromJoinOperation(operation, true); + return replayTerminalJoin(operation, callerBinding, scope); } if (isConnectScopeExpired(scope)) { @@ -774,6 +779,51 @@ private JoinPublicProductionResult failedJoin( private JoinPublicProductionResult pendingJoinFailure( VerifiedJoinScope scope, String outcomeCode) { + return joinRetryFailure(scope, outcomeCode); + } + + private JoinPublicProductionResult replayTerminalJoin( + JoinOperation operation, String callerBinding, VerifiedJoinScope scope) { + if (isConnectScopeExpired(scope)) { + return joinRetryFailure(scope, "CONNECT_SCOPE_INVALID"); + } + + JoinEvaluation evaluation; + try { + evaluation = evaluateJoin(scope); + } catch (RuntimeException ex) { + return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); + } + if (evaluation.failureCode() != null) { + if (isRetryableJoinAuthorityFailure(evaluation)) { + return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); + } + return joinRetryFailure(scope, evaluation.failureCode()); + } + if (!"AVAILABLE".equals(evaluation.authorityAvailability()) + || evaluation.allowPublicJoin() == null + || evaluation.entitlementVersion() == null) { + return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); + } + + String currentRequestDigest = + AccountJoinDigest.request( + scope, callerBinding, evaluation.allowPublicJoin(), evaluation.entitlementVersion()); + if (!Integer.valueOf(1).equals(operation.requestDigestVersion()) + || operation.requestDigest() == null + || operation.allowPublicJoin() == null + || !operation.allowPublicJoin().equals(evaluation.allowPublicJoin()) + || operation.entitlementVersion() == null + || !operation.entitlementVersion().equals(evaluation.entitlementVersion()) + || !operation.requestDigest().equals(currentRequestDigest) + || ("COMMITTED".equals(operation.status()) + && (!evaluation.gameplayAvailable() || !evaluation.allowPublicJoin()))) { + return joinRetryFailure(scope, "IDEMPOTENCY_CONFLICT"); + } + return resultFromJoinOperation(operation, true); + } + + private JoinPublicProductionResult joinRetryFailure(VerifiedJoinScope scope, String outcomeCode) { return new JoinPublicProductionResult( false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java index ded35b8f18..f7976e9d08 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java @@ -41,7 +41,8 @@ void runSeedsDemoAccountMembershipAndProfileWhenMissing() throws Exception { when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.empty()); when(accountRepository.save(any(Account.class))).thenReturn(account); - when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(1L, 1L)).thenReturn(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.empty()); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)).thenReturn(Optional.empty()); seeder.run(new DefaultApplicationArguments(new String[] {})); @@ -52,14 +53,18 @@ void runSeedsDemoAccountMembershipAndProfileWhenMissing() throws Exception { } @Test - void runReassertsExistingDemoBootstrapAccountState() throws Exception { + void runReassertsExistingDemoAccountWithoutOverwritingExplicitJoin() throws Exception { Account account = new Account(); account.setId(1L); account.setEmail("demo@example.com"); + AccountTenantMembership explicitJoin = membership(account, 1L, "ACTIVE", "EXPLICIT_JOIN", true); + explicitJoin.setMembershipVersion(4L); + explicitJoin.setMembershipAuthorityGeneration(8L); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); when(accountRepository.save(any(Account.class))).thenReturn(account); - when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(1L, 1L)).thenReturn(true); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(explicitJoin)); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.of(new Profile())); @@ -76,6 +81,124 @@ void runReassertsExistingDemoBootstrapAccountState() throws Exception { () -> org.junit.jupiter.api.Assertions.assertNotNull(saved.getPasswordHash()), () -> org.junit.jupiter.api.Assertions.assertFalse(saved.getPasswordHash().isBlank())); verify(accountTenantMembershipRepository, never()).save(any(AccountTenantMembership.class)); + org.junit.jupiter.api.Assertions.assertAll( + () -> + org.junit.jupiter.api.Assertions.assertEquals( + "ACTIVE", explicitJoin.getLifecycleState()), + () -> + org.junit.jupiter.api.Assertions.assertTrue(explicitJoin.isGameplayAdmissionAllowed()), + () -> + org.junit.jupiter.api.Assertions.assertEquals(4L, explicitJoin.getMembershipVersion()), + () -> + org.junit.jupiter.api.Assertions.assertEquals( + 8L, explicitJoin.getMembershipAuthorityGeneration()), + () -> + org.junit.jupiter.api.Assertions.assertEquals( + "EXPLICIT_JOIN", explicitJoin.getAuthorityProvenance())); verify(profileRepository, never()).save(any(Profile.class)); } + + @Test + void runReconcilesOnlyTheExactQuarantinedDemoMembership() throws Exception { + Account account = new Account(); + account.setId(1L); + account.setEmail("demo@example.com"); + AccountTenantMembership quarantined = + membership(account, 1L, "LEGACY_UNVERIFIED", "LEGACY_UNVERIFIED", false); + quarantined.setId(42L); + quarantined.setMembershipVersion(1L); + quarantined.setMembershipAuthorityGeneration(1L); + + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountRepository.save(any(Account.class))).thenReturn(account); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(quarantined)); + when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(new Profile())); + + seeder.run(new DefaultApplicationArguments(new String[] {})); + seeder.run(new DefaultApplicationArguments(new String[] {})); + + verify(accountTenantMembershipRepository).save(quarantined); + org.junit.jupiter.api.Assertions.assertAll( + () -> org.junit.jupiter.api.Assertions.assertEquals(42L, quarantined.getId()), + () -> org.junit.jupiter.api.Assertions.assertEquals(1L, quarantined.getTenantId()), + () -> + org.junit.jupiter.api.Assertions.assertEquals( + "ACTIVE", quarantined.getLifecycleState()), + () -> org.junit.jupiter.api.Assertions.assertTrue(quarantined.isGameplayAdmissionAllowed()), + () -> org.junit.jupiter.api.Assertions.assertEquals(2L, quarantined.getMembershipVersion()), + () -> + org.junit.jupiter.api.Assertions.assertEquals( + 2L, quarantined.getMembershipAuthorityGeneration()), + () -> + org.junit.jupiter.api.Assertions.assertEquals( + "SEEDED_DEMO", quarantined.getAuthorityProvenance())); + } + + @Test + void runDoesNotPromoteLegacyMembershipOutsideTheDemoIdentity() throws Exception { + Account account = new Account(); + account.setId(1L); + account.setEmail("demo@example.com"); + Account otherAccount = new Account(); + otherAccount.setId(2L); + AccountTenantMembership unrelatedLegacyMembership = + membership(otherAccount, 7L, "LEGACY_UNVERIFIED", "LEGACY_UNVERIFIED", false); + unrelatedLegacyMembership.setId(93L); + unrelatedLegacyMembership.setMembershipVersion(1L); + unrelatedLegacyMembership.setMembershipAuthorityGeneration(1L); + + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountRepository.save(any(Account.class))).thenReturn(account); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(unrelatedLegacyMembership)); + when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(new Profile())); + + seeder.run(new DefaultApplicationArguments(new String[] {})); + + verify(accountTenantMembershipRepository, never()).save(any(AccountTenantMembership.class)); + org.junit.jupiter.api.Assertions.assertAll( + () -> + org.junit.jupiter.api.Assertions.assertEquals( + "LEGACY_UNVERIFIED", unrelatedLegacyMembership.getLifecycleState()), + () -> + org.junit.jupiter.api.Assertions.assertFalse( + unrelatedLegacyMembership.isGameplayAdmissionAllowed()), + () -> + org.junit.jupiter.api.Assertions.assertEquals( + "LEGACY_UNVERIFIED", unrelatedLegacyMembership.getAuthorityProvenance())); + } + + @Test + void runFailsClosedBeforeRewritingMismatchedAccountReturnedForDemoEmail() throws Exception { + Account mismatchedAccount = new Account(); + mismatchedAccount.setId(1L); + mismatchedAccount.setEmail("real-player@example.com"); + when(accountRepository.findByEmail("demo@example.com")) + .thenReturn(Optional.of(mismatchedAccount)); + + org.junit.jupiter.api.Assertions.assertThrows( + IllegalStateException.class, + () -> seeder.run(new DefaultApplicationArguments(new String[] {}))); + + verify(accountRepository, never()).save(any(Account.class)); + org.mockito.Mockito.verifyNoInteractions(accountTenantMembershipRepository, profileRepository); + } + + private static AccountTenantMembership membership( + Account account, + long tenantId, + String lifecycleState, + String authorityProvenance, + boolean gameplayAdmissionAllowed) { + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setAccount(account); + membership.setTenantId(tenantId); + membership.setLifecycleState(lifecycleState); + membership.setAuthorityProvenance(authorityProvenance); + membership.setGameplayAdmissionAllowed(gameplayAdmissionAllowed); + return membership; + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 1cb4d6e11b..fa1d9ab279 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -347,6 +347,8 @@ void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { false)); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) + .findByTenantIdForUpdate(7L); org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) .append( org.mockito.ArgumentMatchers.any(java.util.UUID.class), @@ -442,18 +444,106 @@ void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { assertTrue(retry.replayed()); assertEquals(denied.outcomeCode(), retry.outcomeCode()); assertEquals("FAILED", retainedOperation.get().status()); - grace.setStatus("active"); - grace.setEntitlementVersion(2L); + var storedDeniedOperation = retainedOperation.get(); when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); JoinPublicProductionResult unavailableAuthorityReplay = service.joinPublicProduction(bootstrap.bootstrapToken(), request); assertFalse(unavailableAuthorityReplay.success()); - assertTrue(unavailableAuthorityReplay.replayed()); - assertEquals(denied.outcomeCode(), unavailableAuthorityReplay.outcomeCode()); + assertFalse(unavailableAuthorityReplay.replayed()); + assertEquals("AUTH_UNAVAILABLE", unavailableAuthorityReplay.outcomeCode()); + assertEquals(storedDeniedOperation, retainedOperation.get()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) + .findByTenantIdForUpdate(7L); + } + + @Test + void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembership() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + AtomicReference joinedMembership = new AtomicReference<>(); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenAnswer(invocation -> Optional.ofNullable(joinedMembership.get())); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + joinedMembership.set(membership); + return membership; + }); + Subscription originalPolicy = new Subscription(); + originalPolicy.setId(22L); + originalPolicy.setTenantId(7L); + originalPolicy.setStatus("active"); + originalPolicy.setEntitlementVersion(5L); + Subscription changedPolicy = new Subscription(); + changedPolicy.setId(22L); + changedPolicy.setTenantId(7L); + changedPolicy.setStatus("active"); + changedPolicy.setEntitlementVersion(6L); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenReturn( + java.util.List.of(originalPolicy), + java.util.List.of(originalPolicy), + java.util.List.of(changedPolicy)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-terminal-policy-change-1"); + + JoinPublicProductionResult joined = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + var committedOperation = retainedOperation.get(); + AccountTenantMembership membership = joinedMembership.get(); + JoinPublicProductionResult retry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertTrue(joined.success()); + assertFalse(retry.success()); + assertFalse(retry.replayed()); + assertEquals("IDEMPOTENCY_CONFLICT", retry.outcomeCode()); + assertEquals(committedOperation, retainedOperation.get()); + assertEquals("COMMITTED", retainedOperation.get().status()); + assertEquals("JOINED", retainedOperation.get().outcome()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals(membership, joinedMembership.get()); + assertEquals("ACTIVE", membership.getLifecycleState()); + assertEquals(1L, membership.getMembershipVersion()); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); + JoinPublicProductionResult unavailableAuthorityRetry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertFalse(unavailableAuthorityRetry.success()); + assertFalse(unavailableAuthorityRetry.replayed()); + assertEquals("AUTH_UNAVAILABLE", unavailableAuthorityRetry.outcomeCode()); + assertEquals(committedOperation, retainedOperation.get()); + assertEquals(membership, joinedMembership.get()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) + .append( + org.mockito.ArgumentMatchers.any(java.util.UUID.class), + org.mockito.ArgumentMatchers.eq("tenant"), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), + org.mockito.ArgumentMatchers.contains("join-terminal-policy-change-1")); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(4)) .findByTenantIdForUpdate(7L); } @@ -796,20 +886,140 @@ void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTrans JoinPublicProductionResult expiredRetry = service.joinPublicProduction(bootstrap.bootstrapToken(), request); + var expiredTerminalOperation = retainedOperation.get(); JoinPublicProductionResult terminalReadback = service.joinPublicProduction(bootstrap.bootstrapToken(), request); assertFalse(expiredRetry.success()); assertEquals("CONNECT_SCOPE_INVALID", expiredRetry.outcomeCode()); assertFalse(terminalReadback.success()); - assertTrue(terminalReadback.replayed()); + assertFalse(terminalReadback.replayed()); assertEquals("CONNECT_SCOPE_INVALID", terminalReadback.outcomeCode()); + assertEquals(expiredTerminalOperation, retainedOperation.get()); assertEquals("FAILED", retainedOperation.get().status()); assertEquals("CONNECT_SCOPE_INVALID", retainedOperation.get().outcome()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) + .finish( + org.mockito.ArgumentMatchers.eq(request.requestId()), + org.mockito.ArgumentMatchers.eq("FAILED"), + org.mockito.ArgumentMatchers.eq("CONNECT_SCOPE_INVALID"), + org.mockito.ArgumentMatchers.isNull(), + org.mockito.ArgumentMatchers.isNull(), + org.mockito.ArgumentMatchers.isNull()); verifyNoInteractions( subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); } + @Test + void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = "expired-committed-connect-scope"; + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-expired-committed-1"); + VerifiedJoinScope unsignedExpiredScope = + new VerifiedJoinScope( + connectScopeId, + 11L, + 7L, + UUID.fromString(REALM_ID), + "demo", + "production", + "production-namespace-7", + "SHARED", + 44L, + 23L, + 17L, + "1999-12-31T23:59:00Z", + "2000-01-01T00:00:00Z", + ""); + VerifiedJoinScope expiredScope = + new VerifiedJoinScope( + unsignedExpiredScope.connectScopeId(), + unsignedExpiredScope.accountId(), + unsignedExpiredScope.tenantId(), + unsignedExpiredScope.realmId(), + unsignedExpiredScope.worldSlug(), + unsignedExpiredScope.realmSlug(), + unsignedExpiredScope.playableStateNamespaceId(), + unsignedExpiredScope.playableStateScope(), + unsignedExpiredScope.gameInstanceId(), + unsignedExpiredScope.catalogRevision(), + unsignedExpiredScope.pointerVersion(), + unsignedExpiredScope.evaluatedAt(), + unsignedExpiredScope.connectScopeExpiresAt(), + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope( + unsignedExpiredScope)); + retainedScope.set(expiredScope); + String callerBinding = + new JwtUtil(JWT_SECRET, 300000L) + .parseToken(bootstrap.bootstrapToken()) + .getPayload() + .get("jti") + .toString(); + var committedOperation = + new AccountJoinOperationRepository.JoinOperation( + expiredScope.accountId(), + expiredScope.tenantId(), + expiredScope.realmId(), + callerBinding, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), + expiredScope.snapshotDigest(), + "AVAILABLE", + true, + 1L, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.request( + expiredScope, callerBinding, true, 1L), + "COMMITTED", + "JOINED", + 701L, + 1L, + 1L, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + request.requestId(), expiredScope, callerBinding), + null, + "AVAILABLE"); + retainedOperation.set(committedOperation); + + JoinPublicProductionResult retry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(retry.success()); + assertFalse(retry.replayed()); + assertEquals("CONNECT_SCOPE_INVALID", retry.outcomeCode()); + assertEquals(committedOperation, retainedOperation.get()); + assertEquals("COMMITTED", retainedOperation.get().status()); + assertEquals("JOINED", retainedOperation.get().outcome()); + assertEquals(701L, retainedOperation.get().membershipId()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finish( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class)); + verifyNoInteractions(subscriptionRepository, accountAuditOutboxRepository); + } + @Test void joinPublicProductionReturnsConflictWhenGlobalRequestIdClaimIsLost() { Account account = new Account(); From d243035e81609285d347135c4ff383531e4964c0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:13:38 +1300 Subject: [PATCH 38/75] Gate hosted readiness on Social Groups served leaf --- dev-tools/certs/README.md | 4 +- dev-tools/certs/generate-dev-certs.sh | 2 +- .../preview/validate-preview-artifact.py | 8 +- dev-tools/tests/dev-demo-workflow-contract.sh | 29 ++++ ...d-identity-controller-manifest-contract.sh | 58 +++++++- .../test_validate_preview_artifact.py | 6 +- k8s/base/grpc-bootstrap.example.yaml | 7 +- .../firemud/templates/network-policies.yaml | 2 +- k8s/hosted-identity-controller/README.md | 2 +- .../networkpolicy.yaml | 19 ++- .../CertificateResourceFactory.java | 4 +- .../model/EnvironmentIdentityPlan.java | 3 +- .../probe/ServedEnvironmentProbe.java | 91 +++++++++++- .../reconcile/HostedIdentityReconciler.java | 5 +- .../DeploymentRolloutServiceTest.java | 3 +- .../probe/ServedEnvironmentProbeTest.java | 79 +++++++++-- .../HostedIdentityReconcilerSafetyTest.java | 130 ++++++++++-------- 17 files changed, 355 insertions(+), 97 deletions(-) diff --git a/dev-tools/certs/README.md b/dev-tools/certs/README.md index 2b29745070..9e8953a274 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -7,7 +7,7 @@ Generated certificate outputs in this directory are ignored by Git and should no ## Script Map - `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target is provided. -- `dev-tools/certs/generate-dev-certs.sh --workload` signs a local development or test-only gRPC workload leaf for the five publication services, Account, or Game Session with the exact SPIFFE URI and service DNS SANs. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. -- Standalone hosted runs retain the legacy shared bundle for other gRPC workloads and consume seven cert-manager-issued runtime-facing `firemud-grpc-` leaf Secrets: five publication workloads, Account, and Game Session. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. +- `dev-tools/certs/generate-dev-certs.sh --workload` signs a local development or test-only gRPC workload leaf for the five publication services, Account, Game Session, or Social Groups with the exact SPIFFE URI and service DNS SANs. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. +- Standalone hosted runs retain the legacy shared bundle for other gRPC workloads and consume eight cert-manager-issued runtime-facing `firemud-grpc-` leaf Secrets: five publication workloads, Account, Game Session, and Social Groups. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. - `dev-tools/certs/ensure-dev-certs.sh` guarantees the canonical local smoke entrypoints have the required cert/key set in place before Compose boots. - `dev-tools/certs/clean-dev-certs.sh` removes generated certificate files from `dev-tools/certs/` unless a target directory or `CERT_DIR` override is provided. diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index ca5abcaae8..0a31711bf9 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -27,7 +27,7 @@ if [[ "${1:-}" == "--workload" ]]; then exit 1 } case "$workload" in - account-service|game-session-service|game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service) + account-service|game-session-service|social-groups-service|game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service) ;; *) echo "unsupported gRPC workload identity: $workload" >&2 diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index 1ae42f4502..c5855bf1bc 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -88,6 +88,7 @@ def _expected_chart_label(chart_metadata_path: Path) -> str: "internal-services-egress", "account-service-controller-ingress", "game-session-service-controller-ingress", + "social-groups-service-controller-ingress", "spring-cloud-gateway-ingress", "spring-cloud-gateway-egress", "tcp-proxy-service-egress", @@ -239,6 +240,7 @@ def _expected_names_for_mode(certificate_identity_mode: str) -> dict[str, set[st { "account-service-controller-ingress", "game-session-service-controller-ingress", + "social-groups-service-controller-ingress", } ) return expected_names @@ -1834,7 +1836,11 @@ def validate_network_policies( }, } if certificate_identity_mode == "hosted-controller": - for workload in ("account-service", "game-session-service"): + for workload in ( + "account-service", + "game-session-service", + "social-groups-service", + ): policy_name = f"{workload}-controller-ingress" spec = _require_mapping( policies[policy_name].get("spec"), diff --git a/dev-tools/tests/dev-demo-workflow-contract.sh b/dev-tools/tests/dev-demo-workflow-contract.sh index 1acef64858..b3203b830e 100644 --- a/dev-tools/tests/dev-demo-workflow-contract.sh +++ b/dev-tools/tests/dev-demo-workflow-contract.sh @@ -364,6 +364,35 @@ openssl pkey -in "$certificate_fixture_dir/valid.key" -check -noout >/dev/null 2 echo "generated publication key failed OpenSSL key validation" >&2 exit 1 } +"$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" --workload \ + "$certificate_fixture_dir/ca.crt" "$certificate_fixture_dir/ca.key" \ + "$certificate_fixture_dir/social-groups.crt" "$certificate_fixture_dir/social-groups.key" \ + pr-42 social-groups-service +social_groups_sans="$(openssl x509 -in "$certificate_fixture_dir/social-groups.crt" \ + -noout -ext subjectAltName)" +grep -Fq 'URI:spiffe://firemud/ns/pr-42/sa/social-groups-service' \ + <<<"$social_groups_sans" || { + echo "generated Social Groups certificate is missing its exact SPIFFE identity" >&2 + exit 1 +} +grep -Fq 'DNS:social-groups-service.pr-42.svc.cluster.local' \ + <<<"$social_groups_sans" || { + echo "generated Social Groups certificate is missing its exact Service DNS SAN" >&2 + exit 1 +} +if "$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" --workload \ + "$certificate_fixture_dir/ca.crt" "$certificate_fixture_dir/ca.key" \ + "$certificate_fixture_dir/unsupported.crt" "$certificate_fixture_dir/unsupported.key" \ + pr-42 unsupported-service >"$certificate_fixture_dir/unsupported.stdout" \ + 2>"$certificate_fixture_dir/unsupported.stderr"; then + echo "workload certificate helper accepted an unlisted service" >&2 + exit 1 +fi +grep -Fq 'unsupported gRPC workload identity: unsupported-service' \ + "$certificate_fixture_dir/unsupported.stderr" || { + echo "workload certificate helper rejected an unknown service without the expected diagnostic" >&2 + exit 1 +} echo "dev-demo certificate fixture: canonical workload certificate generated" >&2 make_profile_certificate() { diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index e9436c0f4a..0245c4213a 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -2098,7 +2098,11 @@ assert { (("firemud.dev/preview", "true"),), (("firemud.dev/dev-demo", "true"),), ) - for workload in ("account-service", "game-session-service") + for workload in ( + "account-service", + "game-session-service", + "social-groups-service", + ) }, grpc_targets PY for text_value in \ @@ -4542,7 +4546,9 @@ if ! helm template hosted-identity-contract "$ROOT_DIR/k8s/helm/firemud" \ >"$helm_rendered"; then fail "Helm chart render failed for resolved hosted values fixture" fi -python3 - "$helm_rendered" "$base_rendered" <<'PY' +python3 - "$helm_rendered" "$base_rendered" "$ARTIFACT_VALIDATOR" <<'PY' +import copy +import importlib.util import sys from pathlib import Path @@ -4564,6 +4570,54 @@ documents = [ for document in yaml.safe_load_all(Path(sys.argv[1]).read_text(encoding="utf-8")) if isinstance(document, dict) ] +validator_spec = importlib.util.spec_from_file_location( + "preview_artifact_validator", sys.argv[3] +) +validator = importlib.util.module_from_spec(validator_spec) +validator_spec.loader.exec_module(validator) +network_policies = [ + document for document in documents if document.get("kind") == "NetworkPolicy" +] +validator.validate_network_policies(network_policies) +social_policy_name = "social-groups-service-controller-ingress" +assert any( + document.get("metadata", {}).get("name") == social_policy_name + for document in network_policies +) +without_social_controller_ingress = [ + document + for document in network_policies + if document.get("metadata", {}).get("name") != social_policy_name +] +try: + validator.validate_network_policies(without_social_controller_ingress) +except ValueError as error: + assert social_policy_name in str(error), str(error) +else: + raise AssertionError( + "preview validator accepted a missing Social Groups controller probe rule" + ) + +unsafe_social_controller_ingress = copy.deepcopy(network_policies) +social_policy = next( + document + for document in unsafe_social_controller_ingress + if document.get("metadata", {}).get("name") == social_policy_name +) +social_policy["spec"]["ingress"][0]["from"][0]["namespaceSelector"]["matchLabels"][ + "kubernetes.io/metadata.name" +] = "kube-system" +try: + validator.validate_network_policies(unsafe_social_controller_ingress) +except ValueError as error: + assert str(error) == ( + f"NetworkPolicy/{social_policy_name} has an unsafe exception" + ), str(error) +else: + raise AssertionError( + "preview validator accepted a widened Social Groups controller ingress" + ) + deployments = {} for document in documents: if document.get("kind") != "Deployment": diff --git a/dev-tools/validation/test_validate_preview_artifact.py b/dev-tools/validation/test_validate_preview_artifact.py index b99a956c61..98f8eb8404 100644 --- a/dev-tools/validation/test_validate_preview_artifact.py +++ b/dev-tools/validation/test_validate_preview_artifact.py @@ -1883,7 +1883,11 @@ def _policy_documents(self, mode): for name, spec in self.validator.EXPECTED_INTERNAL_NETWORK_POLICY_SPECS.items() ] if mode == "hosted-controller": - for workload in ("account-service", "game-session-service"): + for workload in ( + "account-service", + "game-session-service", + "social-groups-service", + ): documents.append( self._policy_document( f"{workload}-controller-ingress", diff --git a/k8s/base/grpc-bootstrap.example.yaml b/k8s/base/grpc-bootstrap.example.yaml index aa278c1e72..7bce1e8168 100644 --- a/k8s/base/grpc-bootstrap.example.yaml +++ b/k8s/base/grpc-bootstrap.example.yaml @@ -1,7 +1,8 @@ # This example only provisions the shared transport/trust Secret. Account Service, Game Session, -# and the five publication workloads also require their separate cert-manager-issued leaf Secrets: -# firemud-grpc-account-service, firemud-grpc-game-session-service, and one firemud-grpc- -# Secret for each publication workload. The shared Secret alone is not sufficient to start them. +# Social Groups, and the five publication workloads also require their separate cert-manager-issued +# leaf Secrets: firemud-grpc-account-service, firemud-grpc-game-session-service, +# firemud-grpc-social-groups-service, and one firemud-grpc- Secret for each publication +# workload. The shared Secret alone is not sufficient to start them. apiVersion: cert-manager.io/v1 kind: Certificate metadata: diff --git a/k8s/helm/firemud/templates/network-policies.yaml b/k8s/helm/firemud/templates/network-policies.yaml index 602ee69048..f5de2c3d8d 100644 --- a/k8s/helm/firemud/templates/network-policies.yaml +++ b/k8s/helm/firemud/templates/network-policies.yaml @@ -121,7 +121,7 @@ spec: - protocol: TCP port: 9000 {{- if eq $certificateIdentityMode "hosted-controller" }} -{{- range $workload := list "account-service" "game-session-service" }} +{{- range $workload := list "account-service" "game-session-service" "social-groups-service" }} --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy diff --git a/k8s/hosted-identity-controller/README.md b/k8s/hosted-identity-controller/README.md index 50a87fde00..797e569005 100644 --- a/k8s/hosted-identity-controller/README.md +++ b/k8s/hosted-identity-controller/README.md @@ -38,7 +38,7 @@ Status contains only non-secret evidence: `observedGeneration`, phase, condition The phases are `Pending`, `Provisioning`, `WaitingForCertificate`, `RuntimeAbsent`, `Syncing`, `Verifying`, `Ready`, `Degraded`, `Blocked`, `Retiring`, and `Retired`. -Normal Active reconciliation observes the derived profile, ensures independent cert-manager ingress and Telnet Certificates/Secrets, retains the shared `firemud-grpc-tls` transport bundle without claiming per-workload identity, and issues separate `-gateway-internal-ws` server and `-tcp-proxy-bridge` client identities from the same fixed internal trust anchor without sharing leaf keys. The Gateway identity has only `serverAuth` and the exact `spring-cloud-gateway-mtls..svc.cluster.local` DNS SAN; the TCP Proxy identity has only `clientAuth` and the exact `spiffe://firemud/ns//sa/tcp-proxy-service` URI SAN. Reconciliation syncs source material to runtime with resource-version compare-and-swap, and rolls all eleven gRPC consumers before fixed-SNI/SAN/issuer endpoint probes. The final acceptance gate performs mutual-TLS handshakes to both fixed Account and Game Session gRPC Services with the current projected client certificate, fixed CA, exact in-cluster SNI/hostname, and each service's current leaf fingerprint; rollout counters alone cannot make either identity Ready. It separately uses the projected TCP Proxy bridge identity to verify the exact Gateway-internal TLS server identity. Existing runtime Secret material is copied to its fixed `*-previous` snapshot in the retained identity namespace before replacement. A clean destination may be created without a predecessor. +Normal Active reconciliation observes the derived profile, ensures independent cert-manager ingress and Telnet Certificates/Secrets, retains the shared `firemud-grpc-tls` transport bundle without claiming per-workload identity, and issues separate `-gateway-internal-ws` server and `-tcp-proxy-bridge` client identities from the same fixed internal trust anchor without sharing leaf keys. The Gateway identity has only `serverAuth` and the exact `spring-cloud-gateway-mtls..svc.cluster.local` DNS SAN; the TCP Proxy identity has only `clientAuth` and the exact `spiffe://firemud/ns//sa/tcp-proxy-service` URI SAN. Reconciliation syncs source material to runtime with resource-version compare-and-swap, and rolls all eleven gRPC consumers before fixed-SNI/SAN/issuer endpoint probes. The final acceptance gate performs mutual-TLS handshakes to the fixed Account, Game Session, and Social Groups gRPC Services with the current projected client certificate, fixed CA, exact in-cluster SNI/hostname, and each service's current leaf fingerprint; rollout counters alone cannot make the controller Ready. It separately uses the projected TCP Proxy bridge identity to verify the exact Gateway-internal TLS server identity. Existing runtime Secret material is copied to its fixed `*-previous` snapshot in the retained identity namespace before replacement. A clean destination may be created without a predecessor. Renewal repeats the same generation-safe sequence. Ordinary internal WebSocket identity renewal updates retained and projected material in place; it does not terminate the bridge. A consumer that has not reloaded the new identity keeps the controller non-ready. Explicit `Retired` intent while a runtime still exists instead scales both `spring-cloud-gateway` and `tcp-proxy-service` to zero and waits for their observed replica counts to reach zero before any retained identity cleanup can proceed, preventing stale in-memory identity reuse when replacement material is unavailable. diff --git a/k8s/hosted-identity-controller/networkpolicy.yaml b/k8s/hosted-identity-controller/networkpolicy.yaml index 10a828bde7..747873978b 100644 --- a/k8s/hosted-identity-controller/networkpolicy.yaml +++ b/k8s/hosted-identity-controller/networkpolicy.yaml @@ -148,9 +148,10 @@ spec: ports: - protocol: TCP port: 2323 - # Ready additionally requires mTLS handshakes to the fixed Account and - # Game Session gRPC Services using their current projected leaves. Runtime - # Namespace labels are externally owned and validated before this probe. + # Ready additionally requires mTLS handshakes to the fixed Account, Game + # Session, and Social Groups gRPC Services using their current projected + # leaves. Runtime Namespace labels are externally owned and validated + # before this probe. - to: - namespaceSelector: matchLabels: @@ -176,6 +177,18 @@ spec: podSelector: matchLabels: app: game-session-service + - namespaceSelector: + matchLabels: + firemud.dev/preview: "true" + podSelector: + matchLabels: + app: social-groups-service + - namespaceSelector: + matchLabels: + firemud.dev/dev-demo: "true" + podSelector: + matchLabels: + app: social-groups-service ports: - protocol: TCP port: 6565 diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java index de8f25897c..2bd9d9f1c7 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java @@ -111,7 +111,9 @@ public GenericKubernetesResource grpcGameSession( renewBefore); } - /** Builds the retained Social Groups workload identity used by protected profile/presence calls. */ + /** + * Builds the retained Social Groups workload identity used by protected profile/presence calls. + */ public GenericKubernetesResource grpcSocialGroups( EnvironmentIdentityPlan plan, Duration renewBefore) { return grpcWorkloadIdentity( diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java index d53f0c2b61..e00ef9e138 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/model/EnvironmentIdentityPlan.java @@ -129,8 +129,7 @@ public String grpcGameSessionSourceSecretName() { } public String grpcSocialGroupsCertificateName() { - return grpcWorkloadIdentityCertificateNames.get( - HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); + return grpcWorkloadIdentityCertificateNames.get(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); } public String grpcSocialGroupsSecretName() { diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java index 9405de9b1c..a9fb3eb6e4 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java @@ -81,6 +81,7 @@ static final class HandshakePolicyRejectedException extends IllegalStateExceptio private static final SecureRandom WEBSOCKET_NONCE_SOURCE = new SecureRandom(); private static final String GRPC_PROBE_SERVICE = "account-service"; private static final String GRPC_GAME_SESSION_PROBE_SERVICE = "game-session-service"; + private static final String GRPC_SOCIAL_GROUPS_PROBE_SERVICE = "social-groups-service"; private static final Logger LOGGER = LoggerFactory.getLogger(ServedEnvironmentProbe.class); private static final ThreadLocal CURRENT_ATTEMPT = new ThreadLocal<>(); private final HostedIdentityProperties properties; @@ -101,7 +102,8 @@ public ProbeResult probe( String expectedGatewayInternalWsLeafSha256, Secret grpcMaterial, String expectedGrpcLeafSha256, - String expectedGrpcGameSessionLeafSha256) { + String expectedGrpcGameSessionLeafSha256, + String expectedGrpcSocialGroupsLeafSha256) { return probe( plan, HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, @@ -112,7 +114,8 @@ public ProbeResult probe( expectedGatewayInternalWsLeafSha256, grpcMaterial, expectedGrpcLeafSha256, - expectedGrpcGameSessionLeafSha256); + expectedGrpcGameSessionLeafSha256, + expectedGrpcSocialGroupsLeafSha256); } public ProbeResult probe( @@ -125,7 +128,8 @@ public ProbeResult probe( String expectedGatewayInternalWsLeafSha256, Secret grpcMaterial, String expectedGrpcLeafSha256, - String expectedGrpcGameSessionLeafSha256) { + String expectedGrpcGameSessionLeafSha256, + String expectedGrpcSocialGroupsLeafSha256) { return probe( plan, exposureMode, @@ -136,6 +140,7 @@ public ProbeResult probe( bridge(hostname, port, tcpProxyBridgeMaterial, expectedGatewayInternalWsLeafSha256), (hostname, port) -> grpc(hostname, port, grpcMaterial, expectedGrpcLeafSha256), (hostname, port) -> grpc(hostname, port, grpcMaterial, expectedGrpcGameSessionLeafSha256), + (hostname, port) -> grpc(hostname, port, grpcMaterial, expectedGrpcSocialGroupsLeafSha256), TOTAL_PROBE_TIMEOUT); } @@ -155,6 +160,7 @@ ProbeResult probe( bridgeProbe, grpcProbe, grpcProbe, + grpcProbe, TOTAL_PROBE_TIMEOUT); } @@ -175,6 +181,7 @@ ProbeResult probe( bridgeProbe, grpcProbe, grpcProbe, + grpcProbe, timeout); } @@ -195,6 +202,7 @@ ProbeResult probe( bridgeProbe, grpcProbe, grpcProbe, + grpcProbe, TOTAL_PROBE_TIMEOUT); } @@ -216,6 +224,7 @@ ProbeResult probe( bridgeProbe, grpcProbe, grpcProbe, + grpcProbe, timeout); } @@ -237,6 +246,53 @@ ProbeResult probe( bridgeProbe, grpcProbe, grpcGameSessionProbe, + grpcProbe, + TOTAL_PROBE_TIMEOUT); + } + + ProbeResult probe( + EnvironmentIdentityPlan plan, + String exposureMode, + int telnetPort, + EndpointProbe httpsProbe, + EndpointProbe telnetProbe, + EndpointProbe bridgeProbe, + EndpointProbe grpcProbe, + EndpointProbe grpcGameSessionProbe, + Duration timeout) { + return probe( + plan, + exposureMode, + telnetPort, + httpsProbe, + telnetProbe, + bridgeProbe, + grpcProbe, + grpcGameSessionProbe, + grpcProbe, + timeout); + } + + ProbeResult probe( + EnvironmentIdentityPlan plan, + String exposureMode, + int telnetPort, + EndpointProbe httpsProbe, + EndpointProbe telnetProbe, + EndpointProbe bridgeProbe, + EndpointProbe grpcProbe, + EndpointProbe grpcGameSessionProbe, + EndpointProbe grpcSocialGroupsProbe) { + return probe( + plan, + exposureMode, + telnetPort, + httpsProbe, + telnetProbe, + bridgeProbe, + grpcProbe, + grpcGameSessionProbe, + grpcSocialGroupsProbe, TOTAL_PROBE_TIMEOUT); } @@ -249,6 +305,7 @@ ProbeResult probe( EndpointProbe bridgeProbe, EndpointProbe grpcProbe, EndpointProbe grpcGameSessionProbe, + EndpointProbe grpcSocialGroupsProbe, Duration timeout) { if (!HostedIdentityContract.PRIVATE_PREVIEW_EXPOSURE_MODE.equals(exposureMode) && !HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE.equals(exposureMode)) { @@ -297,6 +354,21 @@ ProbeResult probe( return new ProbeResult(false, "grpc-material-or-configuration-invalid"); } })); + probes.add( + startProbe( + ProbeName.GRPC_SOCIAL_GROUPS, + () -> { + try { + return grpcSocialGroupsProbe.check( + grpcHostname(plan, GRPC_SOCIAL_GROUPS_PROBE_SERVICE), GRPC_PORT); + } catch (IllegalArgumentException exception) { + LOGGER.debug( + "Social Groups gRPC probe rejected material or configuration for runtime Namespace {}", + plan.runtimeNamespace(), + exception); + return new ProbeResult(false, "grpc-material-or-configuration-invalid"); + } + })); long deadline = System.nanoTime() + timeout.toNanos(); try { List results = new ArrayList<>(probes.size()); @@ -364,7 +436,9 @@ private static void cancelOutstanding(List probes) { } static ProbeResult prefixedResult(ProbeName probeName, ProbeResult result) { - if (probeName == ProbeName.GRPC + if ((probeName == ProbeName.GRPC + || probeName == ProbeName.GRPC_GAME_SESSION + || probeName == ProbeName.GRPC_SOCIAL_GROUPS) && "grpc-material-or-configuration-invalid".equals(result.reason())) { return result; } @@ -468,7 +542,11 @@ interface InternalTlsSocketOpener { } private static String grpcHostname(EnvironmentIdentityPlan plan, String service) { - if (!Set.of(GRPC_PROBE_SERVICE, GRPC_GAME_SESSION_PROBE_SERVICE).contains(service) + if (!Set.of( + GRPC_PROBE_SERVICE, + GRPC_GAME_SESSION_PROBE_SERVICE, + GRPC_SOCIAL_GROUPS_PROBE_SERVICE) + .contains(service) || !plan.grpcConsumers().contains(service)) { throw new IllegalArgumentException("fixed gRPC probe service is not a rollout consumer"); } @@ -959,7 +1037,8 @@ enum ProbeName { TELNET("telnet"), BRIDGE("bridge"), GRPC("grpc"), - GRPC_GAME_SESSION("grpc-game-session"); + GRPC_GAME_SESSION("grpc-game-session"), + GRPC_SOCIAL_GROUPS("grpc-social-groups"); private final String label; diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java index ec6f67cecd..b447b95ada 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java @@ -206,6 +206,8 @@ public UpdateControl reconcile( roleMaterials.material(HostedIdentityContract.GRPC_ACCOUNT_ROLE); CertificateMaterialService.RoleMaterial grpcGameSession = roleMaterials.material(HostedIdentityContract.GRPC_GAME_SESSION_ROLE); + CertificateMaterialService.RoleMaterial grpcSocialGroups = + roleMaterials.material(HostedIdentityContract.GRPC_SOCIAL_GROUPS_ROLE); validateDistinctIdentities( rolePipeline.stream() .map(RoleMaterialBinding::material) @@ -281,7 +283,8 @@ public UpdateControl reconcile( gatewayInternalWs.summary().certificateFingerprint(), grpc.source(), grpcAccount.summary().certificateFingerprint(), - grpcGameSession.summary().certificateFingerprint()); + grpcGameSession.summary().certificateFingerprint(), + grpcSocialGroups.summary().certificateFingerprint()); } else { probes = new ServedEnvironmentProbe.ProbeResult(false, "rollout-pending"); } diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java index 41b56b51d0..58eb5c76d9 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/DeploymentRolloutServiceTest.java @@ -206,8 +206,7 @@ void workloadIdentityRevisionRollsAccountAndPublicationDeploymentsUntilAllReady( .get(HostedIdentityContract.GRPC_REVISION_ANNOTATION)); verify(lockedSocialGroups).replace(socialGroupsReplacement.capture()); assertEquals( - expectedWorkloadRevision( - "grpc-current", "social-groups-current", "social-groups-leaf"), + expectedWorkloadRevision("grpc-current", "social-groups-current", "social-groups-leaf"), socialGroupsReplacement .getValue() .getSpec() diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java index f845f2917b..832187b658 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java @@ -128,6 +128,57 @@ void readinessProbeRequiresBridgeAndInternalGrpcAcceptanceAfterPublicEndpoints() probe.probe(plan, 32001, ready, ready, ready, ready).reason()); } + @Test + void readinessProbeRequiresSocialGroupsToServeItsCurrentLeafAtItsFixedEndpoint() { + HostedIdentityProperties properties = new HostedIdentityProperties(); + EnvironmentIdentityPlan plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); + List endpoints = Collections.synchronizedList(new ArrayList<>()); + ServedEnvironmentProbe.EndpointProbe ready = + (hostname, port) -> { + endpoints.add(hostname + ":" + port); + return new ServedEnvironmentProbe.ProbeResult(true, "ready"); + }; + ServedEnvironmentProbe.EndpointProbe staleSocialGroupsLeaf = + (hostname, port) -> { + assertEquals("social-groups-service.pr-42.svc.cluster.local", hostname); + assertEquals(6565, port); + return new ServedEnvironmentProbe.ProbeResult(false, "leaf-fingerprint-mismatch"); + }; + + ServedEnvironmentProbe probe = new ServedEnvironmentProbe(properties); + assertEquals( + "grpc-social-groups-leaf-fingerprint-mismatch", + probe + .probe( + plan, + HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, + 32001, + ready, + ready, + ready, + ready, + ready, + staleSocialGroupsLeaf) + .reason()); + assertTrue(endpoints.contains("account-service.pr-42.svc.cluster.local:6565")); + assertTrue(endpoints.contains("game-session-service.pr-42.svc.cluster.local:6565")); + + ServedEnvironmentProbe.ProbeResult converged = + probe.probe( + plan, + HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, + 32001, + ready, + ready, + ready, + ready, + ready, + ready); + + assertTrue(converged.ready()); + assertTrue(endpoints.contains("social-groups-service.pr-42.svc.cluster.local:6565")); + } + @Test void privateReadinessSkipsOnlyThePublicTelnetProbe() { HostedIdentityProperties properties = new HostedIdentityProperties(); @@ -158,9 +209,10 @@ void privateReadinessSkipsOnlyThePublicTelnetProbe() { "pr-42.preview.firedevops.net:443", "spring-cloud-gateway-mtls.pr-42.svc.cluster.local:443", "account-service.pr-42.svc.cluster.local:6565", - "game-session-service.pr-42.svc.cluster.local:6565"), + "game-session-service.pr-42.svc.cluster.local:6565", + "social-groups-service.pr-42.svc.cluster.local:6565"), Set.copyOf(endpoints)); - assertEquals(4, endpoints.size()); + assertEquals(5, endpoints.size()); } @Test @@ -192,9 +244,15 @@ void failureClassificationUsesStableProbeNamesRatherThanListPositions() { new ServedEnvironmentProbe.ProbeResult(false, "rejected"); assertEquals( - List.of("grpc-rejected", "https-rejected", "bridge-rejected", "telnet-rejected"), + List.of( + "grpc-rejected", + "grpc-social-groups-rejected", + "https-rejected", + "bridge-rejected", + "telnet-rejected"), List.of( ServedEnvironmentProbe.ProbeName.GRPC, + ServedEnvironmentProbe.ProbeName.GRPC_SOCIAL_GROUPS, ServedEnvironmentProbe.ProbeName.HTTPS, ServedEnvironmentProbe.ProbeName.BRIDGE, ServedEnvironmentProbe.ProbeName.TELNET) @@ -230,9 +288,10 @@ void readinessProbeSuppliesEachDerivedEndpointToItsProbeSeam() { "pr-42.preview.firedevops.net:32001", "spring-cloud-gateway-mtls.pr-42.svc.cluster.local:443", "account-service.pr-42.svc.cluster.local:6565", - "game-session-service.pr-42.svc.cluster.local:6565"), + "game-session-service.pr-42.svc.cluster.local:6565", + "social-groups-service.pr-42.svc.cluster.local:6565"), Set.copyOf(endpoints)); - assertEquals(5, endpoints.size()); + assertEquals(6, endpoints.size()); } @Test @@ -240,7 +299,7 @@ void readinessProbeRunsEveryEndpointConcurrentlyWithinOneDeadline() { HostedIdentityProperties properties = new HostedIdentityProperties(); EnvironmentIdentityPlan plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); ServedEnvironmentProbe probe = new ServedEnvironmentProbe(properties); - CountDownLatch started = new CountDownLatch(5); + CountDownLatch started = new CountDownLatch(6); EndpointProbeState state = new EndpointProbeState(started); ServedEnvironmentProbe.EndpointProbe endpoint = state::check; @@ -248,7 +307,7 @@ void readinessProbeRunsEveryEndpointConcurrentlyWithinOneDeadline() { probe.probe(plan, 32001, endpoint, endpoint, endpoint, endpoint, Duration.ofSeconds(10)); assertEquals("served-bridge-and-grpc-accepted", result.reason()); - assertEquals(5, state.calls.get()); + assertEquals(6, state.calls.get()); assertEquals(0, started.getCount()); } @@ -257,8 +316,8 @@ void readinessProbeCancelsAndClosesEveryOutstandingEndpointAttemptAtDeadline() t HostedIdentityProperties properties = new HostedIdentityProperties(); EnvironmentIdentityPlan plan = new EnvironmentIdentityPlanner(properties).plan("pr-42"); ServedEnvironmentProbe probe = new ServedEnvironmentProbe(properties); - CountDownLatch started = new CountDownLatch(5); - CountDownLatch interrupted = new CountDownLatch(5); + CountDownLatch started = new CountDownLatch(6); + CountDownLatch interrupted = new CountDownLatch(6); List openSockets = Collections.synchronizedList(new ArrayList<>()); ServedEnvironmentProbe.EndpointProbe endpoint = (hostname, port) -> { @@ -282,7 +341,7 @@ void readinessProbeCancelsAndClosesEveryOutstandingEndpointAttemptAtDeadline() t assertEquals("probe-deadline-exceeded", result.reason()); assertTrue(started.await(1, TimeUnit.SECONDS)); assertTrue(interrupted.await(1, TimeUnit.SECONDS)); - assertEquals(5, openSockets.size()); + assertEquals(6, openSockets.size()); for (SSLSocket openSocket : openSockets) { verify(openSocket).close(); } diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java index b204f4d53e..16e18a534b 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java @@ -211,6 +211,7 @@ void workloadIdentityProjectionMustBeAcceptedBeforeReadiness() { anyString(), any(Secret.class), anyString(), + anyString(), anyString())) .thenReturn(new ServedEnvironmentProbe.ProbeResult(true, "served")); Map acknowledgedProjections = @@ -278,7 +279,8 @@ void workloadIdentityProjectionMustBeAcceptedBeforeReadiness() { anyString(), any(Secret.class), org.mockito.ArgumentMatchers.eq("b".repeat(64)), - org.mockito.ArgumentMatchers.eq("c".repeat(64))); + org.mockito.ArgumentMatchers.eq("c".repeat(64)), + org.mockito.ArgumentMatchers.eq("d".repeat(64))); } @Test @@ -323,67 +325,71 @@ void probeStatusOwnsReasonAndMessageAfterEarlierGatesPass() { } @Test - void staleGameSessionServedLeafBlocksControllerReadiness() { - var expected = - new RuntimeProfileService.RuntimeProfile( - "uid", - "a".repeat(40), - "a".repeat(40), - HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, - 32016, - true); - DeploymentHeadGateFixture fixture = new DeploymentHeadGateFixture(expected); - when(fixture.batch.tcpProxyBridge()) - .thenReturn( - DeploymentHeadGateFixture.material( - fixture.plan, HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE, "4")); - MixedOperation> secrets = mock(MixedOperation.class); - NonNamespaceOperation> runtimeSecrets = - mock(NonNamespaceOperation.class); - Resource absent = mock(Resource.class); - when(fixture.client.secrets()).thenReturn(secrets); - when(secrets.inNamespace(fixture.plan.runtimeNamespace())).thenReturn(runtimeSecrets); - when(runtimeSecrets.withName(fixture.plan.tcpProxyBridgeSecretName())).thenReturn(absent); - when(absent.get()).thenReturn(null); - when(fixture.rollout.sync(any(), any(), anyString(), anyString(), anyString(), anyMap(), any())) - .thenReturn(new DeploymentRolloutService.RolloutResult(true, true, true)); - when(fixture.probes.probe( - any(), - anyString(), - anyInt(), - anyString(), - anyString(), - org.mockito.ArgumentMatchers.isNull(), - anyString(), - any(Secret.class), - anyString(), - anyString())) - .thenReturn( - new ServedEnvironmentProbe.ProbeResult( - false, "grpc-game-session-leaf-fingerprint-mismatch")); + void staleGameSessionOrSocialGroupsServedLeafBlocksControllerReadiness() { + for (String[] staleLeaf : + new String[][] {{"game-session-service", "c"}, {"social-groups-service", "d"}}) { + var expected = + new RuntimeProfileService.RuntimeProfile( + "uid", + "a".repeat(40), + "a".repeat(40), + HostedIdentityContract.PUBLIC_PREVIEW_EXPOSURE_MODE, + 32016, + true); + DeploymentHeadGateFixture fixture = new DeploymentHeadGateFixture(expected); + String failureReason = "grpc-" + staleLeaf[0] + "-leaf-fingerprint-mismatch"; + when(fixture.batch.tcpProxyBridge()) + .thenReturn( + DeploymentHeadGateFixture.material( + fixture.plan, HostedIdentityContract.TCP_PROXY_BRIDGE_ROLE, "4")); + MixedOperation> secrets = mock(MixedOperation.class); + NonNamespaceOperation> runtimeSecrets = + mock(NonNamespaceOperation.class); + Resource absent = mock(Resource.class); + when(fixture.client.secrets()).thenReturn(secrets); + when(secrets.inNamespace(fixture.plan.runtimeNamespace())).thenReturn(runtimeSecrets); + when(runtimeSecrets.withName(fixture.plan.tcpProxyBridgeSecretName())).thenReturn(absent); + when(absent.get()).thenReturn(null); + when(fixture.rollout.sync( + any(), any(), anyString(), anyString(), anyString(), anyMap(), any())) + .thenReturn(new DeploymentRolloutService.RolloutResult(true, true, true)); + when(fixture.probes.probe( + any(), + anyString(), + anyInt(), + anyString(), + anyString(), + org.mockito.ArgumentMatchers.isNull(), + anyString(), + any(Secret.class), + org.mockito.ArgumentMatchers.eq("b".repeat(64)), + org.mockito.ArgumentMatchers.eq("c".repeat(64)), + org.mockito.ArgumentMatchers.eq("d".repeat(64)))) + .thenReturn(new ServedEnvironmentProbe.ProbeResult(false, failureReason)); - UpdateControl result = fixture.reconcile(); + UpdateControl result = fixture.reconcile(); - HostedEnvironmentIdentityStatus status = result.getResource().orElseThrow().getStatus(); - assertEquals(HostedEnvironmentIdentityStatus.Phase.Verifying, status.getPhase()); - assertEquals("ServedProbePending", status.getConditions().get(0).getReason()); - assertEquals( - "grpc-game-session-leaf-fingerprint-mismatch", status.getConditions().get(0).getMessage()); - verify(fixture.probes) - .probe( - any(), - anyString(), - anyInt(), - anyString(), - anyString(), - org.mockito.ArgumentMatchers.isNull(), - anyString(), - any(Secret.class), - org.mockito.ArgumentMatchers.eq("b".repeat(64)), - org.mockito.ArgumentMatchers.eq("c".repeat(64))); - verify(fixture.projections, never()) - .acknowledge( - any(), any(), anyString(), anyString(), anyLong(), anyLong(), anyString(), any()); + HostedEnvironmentIdentityStatus status = result.getResource().orElseThrow().getStatus(); + assertEquals(HostedEnvironmentIdentityStatus.Phase.Verifying, status.getPhase()); + assertEquals("ServedProbePending", status.getConditions().get(0).getReason()); + assertEquals(failureReason, status.getConditions().get(0).getMessage()); + verify(fixture.probes) + .probe( + any(), + anyString(), + anyInt(), + anyString(), + anyString(), + org.mockito.ArgumentMatchers.isNull(), + anyString(), + any(Secret.class), + org.mockito.ArgumentMatchers.eq("b".repeat(64)), + org.mockito.ArgumentMatchers.eq("c".repeat(64)), + org.mockito.ArgumentMatchers.eq("d".repeat(64))); + verify(fixture.projections, never()) + .acknowledge( + any(), any(), anyString(), anyString(), anyLong(), anyLong(), anyString(), any()); + } } @Test @@ -590,6 +596,7 @@ void readinessBoundaryRejectsAChangedRuntimeTupleBeforeAcknowledgement() { anyString(), any(Secret.class), anyString(), + anyString(), anyString())) .thenReturn(new ServedEnvironmentProbe.ProbeResult(true, "served")); @@ -648,6 +655,7 @@ void malformedRuntimeProfileAtReadinessBoundaryFailsClosedWithoutAcknowledgement anyString(), any(Secret.class), anyString(), + anyString(), anyString())) .thenReturn(new ServedEnvironmentProbe.ProbeResult(true, "served")); @@ -869,6 +877,7 @@ void projectionAcknowledgementFenceNamesTheProtectedAction() { anyString(), any(Secret.class), anyString(), + anyString(), anyString())) .thenReturn(new ServedEnvironmentProbe.ProbeResult(true, "served")); when(fixture.projections.acknowledge( @@ -2310,6 +2319,7 @@ void missingBridgeProjectionMapsReconciliationToVerifyingProbeStatus() { anyString(), any(Secret.class), anyString(), + anyString(), anyString())) .thenReturn( new ServedEnvironmentProbe.ProbeResult(false, "material-or-leaf-fingerprint-missing")); From d334d2af6f0a090adafd373661887b1a5007bb87 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:13:45 +1300 Subject: [PATCH 39/75] Bind bootstrap realm scope to exact pointer reread --- .../service/impl/AccountServiceImpl.java | 22 ++++++++++-- .../service/impl/AccountServiceImplTest.java | 34 +++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 7057f9db5a..0a50307794 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -393,11 +393,10 @@ public List listBootstrapRealms(String bootstrapToken, String RuntimeRealmTarget current = requireRealmTarget( discovered.tenantId(), discovered.worldSlug(), discovered.realmSlug()); - if (discovered.visible() != current.visible() - || discovered.publicProductionRealm() != current.publicProductionRealm()) { + if (!sameRuntimeRealmAuthority(discovered, current)) { throw admissionPointerUnavailable( new IllegalStateException( - "Public realm is no longer visible for bootstrap discovery")); + "Public realm authority changed during bootstrap discovery")); } return current; }) @@ -1555,6 +1554,23 @@ private boolean isPublicProductionRealm(RuntimeRealmTarget realm) { return realm.visible() && realm.publicProductionRealm(); } + private boolean sameRuntimeRealmAuthority( + RuntimeRealmTarget expected, RuntimeRealmTarget actual) { + return expected.tenantId() == actual.tenantId() + && expected.realmId().equals(actual.realmId()) + && expected.playableStateNamespaceId().equals(actual.playableStateNamespaceId()) + && expected.gameInstanceId() == actual.gameInstanceId() + && expected.worldSlug().equals(actual.worldSlug()) + && expected.realmSlug().equals(actual.realmSlug()) + && expected.pointerVersion() == actual.pointerVersion() + && expected.catalogRevision() == actual.catalogRevision() + && expected.visible() == actual.visible() + && expected.publicProductionRealm() == actual.publicProductionRealm() + && expected.stateScope().equals(actual.stateScope()) + && expected.characterCreationPolicy().equals(actual.characterCreationPolicy()) + && expected.requiresCharacterSelection() == actual.requiresCharacterSelection(); + } + private String mintConnectScopeId( BootstrapContext bootstrapContext, RuntimeRealmTarget realm, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index fa1d9ab279..249c8bc649 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -2005,6 +2005,40 @@ void listBootstrapRealmsDoesNotIssueScopeWhenPublicPointerBecomesPrivateBeforeFi .insert(org.mockito.ArgumentMatchers.any()); } + @Test + void listBootstrapRealmsDoesNotIssueScopeWhenPointerChangesDuringDiscovery() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + + var initiallyDiscovered = gameSessionClient.listGameplayRealms("demo").getFirst(); + var changedRealmId = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; + var currentRealm = + initiallyDiscovered.toBuilder().setRealmId(changedRealmId).setPointerVersion(18L).build(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(java.util.List.of(initiallyDiscovered), java.util.List.of(currentRealm)); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + admissionPointer(7L, "demo", "production", "44", 18L, true, true, "SHARED", "ALLOW_NEW") + .toBuilder() + .setRealmId(changedRealmId) + .build()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any()); + } + @ParameterizedTest @ValueSource(strings = {"101", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { From b5cd82ff142a7b1d8fa901cb007fbd2c6d9c8522 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:20:15 +1300 Subject: [PATCH 40/75] Format front-stage Game Session catalog proof --- .../gamesession/command/text/GameplayWorldCatalog.java | 8 ++++---- .../service/impl/GameSessionGrpcServiceTest.java | 4 +--- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 5f2bf4e07e..163d01bc8e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -210,8 +210,8 @@ public List visibleWorlds() { * *

Text discovery intentionally continues to use {@link #visibleWorlds()}, which filters * malformed or ambiguous rows for its existing negative-admission behavior. The gRPC discovery - * boundary validates completeness and tenant-global public-realm uniqueness on one exact - * snapshot before projecting it. + * boundary validates completeness and tenant-global public-realm uniqueness on one exact snapshot + * before projecting it. */ public List visibleWorldsFromAuthoritySnapshot() { if (authorityPointerSupplier == null) { @@ -233,8 +233,8 @@ public List visibleWorldsFromAuthoritySnapshot() { } /** - * Requires a direct public-production admission target to match the sole visible public realm - * in its tenant's current authoritative pointer snapshot. + * Requires a direct public-production admission target to match the sole visible public realm in + * its tenant's current authoritative pointer snapshot. */ public void requireUniqueVisiblePublicProductionRealm( GameplayAdmissionPointerSnapshot expectedPointer) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 0a33e6b2b1..938639bb7c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -638,9 +638,7 @@ void publicAdmissionRejectsNonUniqueTenantGlobalPublicRealm() { .thenReturn(java.util.Optional.of(selectedPublicRealm)); Mockito.when(pointerAuthorityService.listPointers()) .thenReturn( - List.of( - selectedPublicRealm, - authorityPointer("beta", "live", 7L, 55L, true, true))); + List.of(selectedPublicRealm, authorityPointer("beta", "live", 7L, 55L, true, true))); GameSessionGrpcService service = catalogService(pointerAuthorityService); AtomicReference response = new AtomicReference<>(); From 3b42efd81ad5c8b446c862f99bb3a5f106890cf1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:25:22 +1300 Subject: [PATCH 41/75] Format CAS-stage pointer authority proof --- ...meplayAdmissionPointerEventRepository.java | 5 ++-- .../GameplayAdmissionPointerRepository.java | 4 +-- ...ameplayAdmissionPointerRepositoryTest.java | 3 +- ...yAdmissionPointerAuthorityServiceTest.java | 30 ++++++++----------- ...missionPointerControlPlaneServiceTest.java | 5 ++-- 5 files changed, 19 insertions(+), 28 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java index 446f513199..c37e1d298c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java @@ -35,9 +35,8 @@ public List findByWorldSlugAndRealmSlugOrderByIdD .fetch(this::toEntity); } - public List - findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( - Long tenantId, String worldSlug, String realmSlug) { + public List findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( + Long tenantId, String worldSlug, String realmSlug) { return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER_EVENT) .where( GAMEPLAY_ADMISSION_POINTER_EVENT diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index 797c93a2cf..9d8ab545ec 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -41,8 +41,8 @@ public long count() { * Serializes the empty-store bootstrap check and seed writes across Game Session pods. * *

The caller must invoke this inside the transaction that performs the subsequent count and - * any seed writes so PostgreSQL retains the advisory lock through commit or rollback. Non-Postgres - * dialects skip the lock for local test compatibility. + * any seed writes so PostgreSQL retains the advisory lock through commit or rollback. + * Non-Postgres dialects skip the lock for local test compatibility. */ public void lockForBootstrap() { lockAdvisoryTransaction(BOOTSTRAP_ADVISORY_LOCK_KEY); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index aea1612a36..3279597344 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -132,8 +132,7 @@ void pointerAuditOrdersByEventIdWhenPodTimestampMovesBackward() throws Exception GameplayAdmissionPointerEvent secondSaved = repository.save(laterWriteWithSkewedClock); var audit = - repository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( - 7L, "demo", "production"); + repository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc(7L, "demo", "production"); assertEquals(secondSaved.getId(), audit.getFirst().getId()); assertEquals(firstSaved.getId(), audit.get(1).getId()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index 5d2f82aa1d..ad3fd50c39 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -44,9 +44,8 @@ void upsertPointerRejectsMismatchedExpectedVersion() { existing.setId(11L); existing.setPointerVersion(3L); existing.setStateScope("SHARED"); - when( - pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( - 1L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); assertThrows( @@ -101,9 +100,8 @@ void upsertPointerRejectsUnknownStateScope() { @Test void upsertPointerAllowsCreateWhenExpectedVersionPairIsZero() { - when( - pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( - 1L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.empty()); when(pointerRepository.save(any(GameplayAdmissionPointer.class))) .thenAnswer( @@ -155,9 +153,8 @@ void upsertPointerAllowsCreateWhenExpectedVersionPairIsZero() { @Test void upsertPointerAdvancesCatalogRevisionWithoutAdvancingPointerVersion() { GameplayAdmissionPointer existing = existingPointer(); - when( - pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( - 1L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); when(pointerRepository.save(any(GameplayAdmissionPointer.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -195,9 +192,8 @@ void upsertPointerAdvancesCatalogRevisionWithoutAdvancingPointerVersion() { @Test void upsertPointerExactNoOpDoesNotAdvanceOrPersistVersions() { GameplayAdmissionPointer existing = existingPointer(); - when( - pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( - 1L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); GameplayAdmissionPointerSnapshot snapshot = @@ -271,9 +267,8 @@ void upsertPointerRejectsStaleExpectedVersionsForExactNoOp() { void upsertPointerRejectsStaleCatalogRevisionEvenWhenPointerVersionMatches() { GameplayAdmissionPointer existing = existingPointer(); existing.setCatalogRevision(2L); - when( - pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( - 1L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); assertThrows( @@ -306,9 +301,8 @@ void upsertPointerRejectsStaleCatalogRevisionEvenWhenPointerVersionMatches() { @Test void upsertPointerRejectsExistingMutationWithoutExpectedPair() { GameplayAdmissionPointer existing = existingPointer(); - when( - pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( - 1L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); assertThrows( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java index 6a9f692198..3a2a01ac26 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java @@ -63,9 +63,8 @@ void listRejectsRetainedPreV7AuditWithUnknownRevisionAndIdentity() { when(pointerRepository.findAllByOrderByWorldSlugAscRealmSlugAsc()) .thenReturn(List.of(currentPointer)); - when( - eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( - 1L, "demo", "production")) + when(eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( + 1L, "demo", "production")) .thenReturn(List.of(retainedPreV7Event)); DatabaseGameplayAdmissionPointerAuthorityService authorityService = From 0506b1ef79fd2e6fc934178dbbf6237fe3f441b5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:33:43 +1300 Subject: [PATCH 42/75] docs(identity): align hosted leaf implementation status --- ...kubernetes-native-secret-delivery-without-mandatory-vault.md | 2 +- .../infrastructure/environment-and-secrets-catalog.md | 2 +- k8s/hosted-identity-controller/README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/design/architecture/decisions/adr-0032-kubernetes-native-secret-delivery-without-mandatory-vault.md b/design/architecture/decisions/adr-0032-kubernetes-native-secret-delivery-without-mandatory-vault.md index 64e54937d4..9c6b3db1a2 100644 --- a/design/architecture/decisions/adr-0032-kubernetes-native-secret-delivery-without-mandatory-vault.md +++ b/design/architecture/decisions/adr-0032-kubernetes-native-secret-delivery-without-mandatory-vault.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Kubernetes Secret mounts, cert-manager examples, expected-binding preflight, and secret-compliance evidence exist, but the repository does not satisfy the complete target. Base manifests mount JWT signing material beyond Account, gRPC workloads commonly share one TLS Secret, and production Secret encryption-at-rest/audit proof plus automated rotation/convergence remain incomplete. Hosted preview/dev-demo Helm currently uses the shared `firemud-grpc-tls` Secret across gRPC workloads; that proves encrypted transport only, not target per-workload identity or player-facing equivalence. The target remains distinct leaf Secrets per workload with a shared CA, with generic per-workload identity preflight proof still unimplemented. +Kubernetes Secret mounts, cert-manager examples, expected-binding preflight, and secret-compliance evidence exist, but the repository does not satisfy the complete target. Base manifests still mount JWT signing material beyond Account, three of the eleven hosted gRPC workloads still use shared leaf material, and production Secret encryption-at-rest/audit proof plus automated rotation/convergence remain incomplete. Hosted preview/dev-demo Helm now defines eight distinct gRPC workload leaf Secrets: five publication workloads plus Account, Game Session, and Social Groups. The shared `firemud-grpc-tls` Secret remains for the common CA trust bundle and the three remaining shared-leaf workloads. Static render and controller-contract proof covers the eight distinct workload bindings and their readiness evidence; live certificate issuance, served-identity convergence, and production-promotion proof remain incomplete. The target remains distinct leaf Secrets for every workload with a shared CA. ## Decision Record diff --git a/design/architecture/infrastructure/environment-and-secrets-catalog.md b/design/architecture/infrastructure/environment-and-secrets-catalog.md index dc4585b15a..23cd54ce1d 100644 --- a/design/architecture/infrastructure/environment-and-secrets-catalog.md +++ b/design/architecture/infrastructure/environment-and-secrets-catalog.md @@ -102,7 +102,7 @@ Only an explicitly labelled one-shot test/CI stack may collapse roles into a sin ## TLS & Certificates -Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; see [Security Architecture](../system-architecture-security.md#cross-service-trust). The canonical target provisions certificates through **cert-manager** and mounts distinct per-workload leaf certificate/private-key Secrets so every service has a concrete private identity. Current hosted Helm manifests for `pr-preview` and `dev-demo-cluster` use the shared `firemud-grpc-tls` Secret across gRPC workloads; that is evidence of encrypted mTLS transport only, not distinct workload leaf identity or player-facing equivalence. Explicit local-development and throwaway-test profiles may use plaintext internal transport, including the documented `ws://` Proxy-to-Gateway bridge, and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. Hosted `pr-preview` currently uses the shared-secret mTLS boundary and remains non-player-facing/non-promotion evidence; the canonical non-local target remains distinct per-workload mTLS. These certificates secure: +Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; see [Security Architecture](../system-architecture-security.md#cross-service-trust). The canonical target provisions certificates through **cert-manager** and mounts distinct per-workload leaf certificate/private-key Secrets so every service has a concrete private identity. Hosted Helm for `pr-preview` and `dev-demo-cluster` defines eight distinct gRPC workload leaves: five publication workloads plus Account, Game Session, and Social Groups. The shared `firemud-grpc-tls` Secret supplies the common CA trust bundle and remains the leaf source for three other hosted gRPC workloads. Static render and hosted-controller contract checks cover the eight distinct bindings and readiness evidence; live issuance and served-identity convergence remain unproved. Explicit local-development and throwaway-test profiles may use plaintext internal transport, including the documented `ws://` Proxy-to-Gateway bridge, and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. Hosted `pr-preview` remains non-player-facing and does not provide production-promotion evidence; the canonical non-local target remains distinct per-workload mTLS. These certificates secure: - All mTLS-protected gRPC calls between services - Any internal WebSocket bridges that require mTLS (for example, the TCP Proxy Service connecting to Spring Cloud Gateway over `wss://`) diff --git a/k8s/hosted-identity-controller/README.md b/k8s/hosted-identity-controller/README.md index 797e569005..4ee1596bcd 100644 --- a/k8s/hosted-identity-controller/README.md +++ b/k8s/hosted-identity-controller/README.md @@ -38,7 +38,7 @@ Status contains only non-secret evidence: `observedGeneration`, phase, condition The phases are `Pending`, `Provisioning`, `WaitingForCertificate`, `RuntimeAbsent`, `Syncing`, `Verifying`, `Ready`, `Degraded`, `Blocked`, `Retiring`, and `Retired`. -Normal Active reconciliation observes the derived profile, ensures independent cert-manager ingress and Telnet Certificates/Secrets, retains the shared `firemud-grpc-tls` transport bundle without claiming per-workload identity, and issues separate `-gateway-internal-ws` server and `-tcp-proxy-bridge` client identities from the same fixed internal trust anchor without sharing leaf keys. The Gateway identity has only `serverAuth` and the exact `spring-cloud-gateway-mtls..svc.cluster.local` DNS SAN; the TCP Proxy identity has only `clientAuth` and the exact `spiffe://firemud/ns//sa/tcp-proxy-service` URI SAN. Reconciliation syncs source material to runtime with resource-version compare-and-swap, and rolls all eleven gRPC consumers before fixed-SNI/SAN/issuer endpoint probes. The final acceptance gate performs mutual-TLS handshakes to the fixed Account, Game Session, and Social Groups gRPC Services with the current projected client certificate, fixed CA, exact in-cluster SNI/hostname, and each service's current leaf fingerprint; rollout counters alone cannot make the controller Ready. It separately uses the projected TCP Proxy bridge identity to verify the exact Gateway-internal TLS server identity. Existing runtime Secret material is copied to its fixed `*-previous` snapshot in the retained identity namespace before replacement. A clean destination may be created without a predecessor. +Normal Active reconciliation observes the derived profile, ensures independent cert-manager ingress and Telnet Certificates/Secrets, tracks the eight distinct hosted gRPC workload leaves alongside the shared `firemud-grpc-tls` bundle (which remains the common CA trust source and leaf source for three other gRPC workloads), and issues separate `-gateway-internal-ws` server and `-tcp-proxy-bridge` client identities from the same fixed internal trust anchor without sharing leaf keys. The eight workload leaves are the five publication roles plus Account, Game Session, and Social Groups; static render and controller-contract checks cover their fixed bindings and readiness evidence. The Gateway identity has only `serverAuth` and the exact `spring-cloud-gateway-mtls..svc.cluster.local` DNS SAN; the TCP Proxy identity has only `clientAuth` and the exact `spiffe://firemud/ns//sa/tcp-proxy-service` URI SAN. Reconciliation syncs source material to runtime with resource-version compare-and-swap, and rolls all eleven gRPC consumers before fixed-SNI/SAN/issuer endpoint probes. The final acceptance gate performs mutual-TLS handshakes to the fixed Account, Game Session, and Social Groups gRPC Services with the current projected client certificate, fixed CA, exact in-cluster SNI/hostname, and each service's current leaf fingerprint; rollout counters alone cannot make the controller Ready. These checks do not establish live certificate issuance or production-promotion evidence. It separately uses the projected TCP Proxy bridge identity to verify the exact Gateway-internal TLS server identity. Existing runtime Secret material is copied to its fixed `*-previous` snapshot in the retained identity namespace before replacement. A clean destination may be created without a predecessor. Renewal repeats the same generation-safe sequence. Ordinary internal WebSocket identity renewal updates retained and projected material in place; it does not terminate the bridge. A consumer that has not reloaded the new identity keeps the controller non-ready. Explicit `Retired` intent while a runtime still exists instead scales both `spring-cloud-gateway` and `tcp-proxy-service` to zero and waits for their observed replica counts to reach zero before any retained identity cleanup can proceed, preventing stale in-memory identity reuse when replacement material is unavailable. From df5f357f83ede051f4f5fd09956870776b73136f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:17:51 +1300 Subject: [PATCH 43/75] Fail closed on invalid admission pointer bootstrap seeds --- ...ayAdmissionPointerBootstrapProperties.java | 7 +- ...yAdmissionPointerBootstrapInitializer.java | 88 +++++++++++++++--- .../src/main/resources/application.yml | 2 +- ...issionPointerBootstrapInitializerTest.java | 90 +++++++++++++++++-- 4 files changed, 162 insertions(+), 25 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameplayAdmissionPointerBootstrapProperties.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameplayAdmissionPointerBootstrapProperties.java index 65ac39f720..4d8cb0385b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameplayAdmissionPointerBootstrapProperties.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameplayAdmissionPointerBootstrapProperties.java @@ -12,14 +12,15 @@ public class GameplayAdmissionPointerBootstrapProperties { private List pointers = new ArrayList<>( List.of( - defaultPointerSeed("demo", "Demo World", 1L, 1L, false), - defaultPointerSeed("sandbox", "Builder Sandbox", 1L, 2L, true))); + defaultPointerSeed("demo", "Demo World", 1L, 1L, true, false), + defaultPointerSeed("sandbox", "Builder Sandbox", 1L, 2L, false, true))); private static PointerSeed defaultPointerSeed( String worldSlug, String worldDisplayName, long tenantId, long gameInstanceId, + boolean publicProductionRealm, boolean requiresCharacterSelection) { PointerSeed pointer = new PointerSeed(); pointer.setWorldSlug(worldSlug); @@ -29,7 +30,7 @@ private static PointerSeed defaultPointerSeed( pointer.setTenantId(tenantId); pointer.setGameInstanceId(gameInstanceId); pointer.setVisible(true); - pointer.setPublicProductionRealm(true); + pointer.setPublicProductionRealm(publicProductionRealm); pointer.setRequiresCharacterSelection(requiresCharacterSelection); pointer.setStateScope(StateScope.SHARED); pointer.setCharacterCreationPolicy(CharacterCreationPolicy.ALLOW_NEW); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java index 69be4769e1..5862e51591 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java @@ -1,5 +1,11 @@ package net.firedevops.firemud.gamesession.data; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.gamesession.config.GameplayAdmissionPointerBootstrapProperties; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; @@ -34,18 +40,10 @@ public void run(ApplicationArguments args) { if (pointerRepository.count() > 0) { return; } - if (bootstrapProperties.getPointers() == null) { - return; - } - for (GameplayAdmissionPointerBootstrapProperties.PointerSeed pointer : - bootstrapProperties.getPointers()) { - if (pointer == null - || pointer.getWorldSlug() == null - || pointer.getWorldSlug().isBlank() - || pointer.getRealmSlug() == null - || pointer.getRealmSlug().isBlank()) { - continue; - } + List pointers = + bootstrapProperties.getPointers(); + validateSeeds(pointers); + for (GameplayAdmissionPointerBootstrapProperties.PointerSeed pointer : pointers) { authorityService.upsertPointer( new GameplayAdmissionPointerMutation( pointer.getWorldSlug(), @@ -75,6 +73,72 @@ public void run(ApplicationArguments args) { } } + private static void validateSeeds( + List pointers) { + if (pointers == null || pointers.isEmpty()) { + throw new IllegalArgumentException("Gameplay admission pointer bootstrap seeds are required"); + } + + Set worldRealmKeys = new HashSet<>(); + Set runtimeTargetKeys = new HashSet<>(); + Map publicRealmCounts = new HashMap<>(); + Set tenantIds = new HashSet<>(); + for (int index = 0; index < pointers.size(); index++) { + GameplayAdmissionPointerBootstrapProperties.PointerSeed pointer = pointers.get(index); + if (pointer == null) { + throw invalidSeed(index, "must not be null"); + } + requireText(pointer.getWorldSlug(), index, "world slug"); + requireText(pointer.getWorldDisplayName(), index, "world display name"); + requireText(pointer.getRealmSlug(), index, "realm slug"); + requireText(pointer.getRealmDisplayName(), index, "realm display name"); + if (pointer.getTenantId() <= 0) { + throw invalidSeed(index, "tenant ID must be positive"); + } + if (pointer.getGameInstanceId() <= 0) { + throw invalidSeed(index, "game instance ID must be positive"); + } + + tenantIds.add(pointer.getTenantId()); + String worldRealmKey = + pointer.getTenantId() + + ":" + + pointer.getWorldSlug().trim().toLowerCase(Locale.ROOT) + + ":" + + pointer.getRealmSlug().trim().toLowerCase(Locale.ROOT); + if (!worldRealmKeys.add(worldRealmKey)) { + throw invalidSeed(index, "duplicates a tenant world and realm selector"); + } + String runtimeTargetKey = pointer.getTenantId() + ":" + pointer.getGameInstanceId(); + if (!runtimeTargetKeys.add(runtimeTargetKey)) { + throw invalidSeed(index, "duplicates a tenant runtime target"); + } + if (pointer.isVisible() && pointer.isPublicProductionRealm()) { + publicRealmCounts.merge(pointer.getTenantId(), 1L, Long::sum); + } + } + + for (long tenantId : tenantIds) { + if (publicRealmCounts.getOrDefault(tenantId, 0L) != 1L) { + throw new IllegalArgumentException( + "Gameplay admission pointer bootstrap must define exactly one visible public " + + "production realm for tenant " + + tenantId); + } + } + } + + private static void requireText(String value, int index, String field) { + if (value == null || value.isBlank()) { + throw invalidSeed(index, field + " is required"); + } + } + + private static IllegalArgumentException invalidSeed(int index, String reason) { + return new IllegalArgumentException( + "Invalid gameplay admission pointer bootstrap seed at index " + index + ": " + reason); + } + private static String stateScopeName( GameplayAdmissionPointerBootstrapProperties.PointerSeed pointer) { GameplayAdmissionPointerBootstrapProperties.StateScope stateScope = pointer.getStateScope(); diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index c3e79dbb18..3591f95ac9 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -78,7 +78,7 @@ firemud: tenant-id: ${FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID:1} game-instance-id: ${FIREMUD_BOOTSTRAP_SANDBOX_GAME_INSTANCE_ID:2} visible: true - public-production-realm: true + public-production-realm: false requires-character-selection: true state-scope: SHARED character-creation-policy: ALLOW_NEW diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index a89593a35f..857a551a19 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -1,6 +1,8 @@ package net.firedevops.firemud.gamesession.data; 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.Mockito.inOrder; import static org.mockito.Mockito.never; @@ -41,10 +43,6 @@ void setUp() { @Test void runSeedsBootstrapPointersWhenAuthorityStoreIsEmpty() throws Exception { when(pointerRepository.count()).thenReturn(0L); - properties.setPointers( - List.of( - pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, false), - pointerSeed("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, true))); initializer.run(new DefaultApplicationArguments(new String[] {})); @@ -71,6 +69,21 @@ void runSeedsBootstrapPointersWhenAuthorityStoreIsEmpty() throws Exception { assertEquals(0L, mutations.get(0).expectedCatalogRevision()); assertEquals("sandbox", mutations.get(1).worldSlug()); assertTrue(mutations.get(1).requiresCharacterSelection()); + assertFalse(mutations.get(1).publicProductionRealm()); + } + + @Test + void defaultEffectiveBootstrapSeedsHaveOneVisiblePublicProductionRealmPerTenant() { + List pointers = + properties.getPointers(); + + assertEquals(2, pointers.size()); + assertEquals("demo", pointers.get(0).getWorldSlug()); + assertTrue(pointers.get(0).isVisible()); + assertTrue(pointers.get(0).isPublicProductionRealm()); + assertEquals("sandbox", pointers.get(1).getWorldSlug()); + assertTrue(pointers.get(1).isVisible()); + assertFalse(pointers.get(1).isPublicProductionRealm()); } @Test @@ -84,7 +97,7 @@ void runSkipsSeedMutationsOnRestartWhenAuthorityStoreAlreadyHasPointers() throws } @Test - void runSkipsBlankBootstrapPointerSeeds() throws Exception { + void runRejectsMalformedBootstrapPointerSeedsBeforeAnyMutation() throws Exception { when(pointerRepository.count()).thenReturn(0L); properties.setPointers( new java.util.ArrayList<>( @@ -94,12 +107,71 @@ void runSkipsBlankBootstrapPointerSeeds() throws Exception { pointerSeed("sandbox", "Builder Sandbox", "", "Live Realm", 1L, 3L, true), null))); + assertThrows( + IllegalArgumentException.class, + () -> initializer.run(new DefaultApplicationArguments(new String[] {}))); + + verify(authorityService, never()).upsertPointer(org.mockito.ArgumentMatchers.any()); + } + + @Test + void runRejectsMultipleVisiblePublicProductionSeedsForTenantBeforeAnyMutation() throws Exception { + when(pointerRepository.count()).thenReturn(0L); + GameplayAdmissionPointerBootstrapProperties.PointerSeed sandbox = + pointerSeed("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, true); + properties.setPointers( + List.of( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, false), sandbox)); + + assertThrows( + IllegalArgumentException.class, + () -> initializer.run(new DefaultApplicationArguments(new String[] {}))); + + verify(authorityService, never()).upsertPointer(org.mockito.ArgumentMatchers.any()); + } + + @Test + void runRejectsNoVisiblePublicProductionSeedForTenantBeforeAnyMutation() throws Exception { + when(pointerRepository.count()).thenReturn(0L); + GameplayAdmissionPointerBootstrapProperties.PointerSeed demo = + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, false); + demo.setPublicProductionRealm(false); + properties.setPointers(List.of(demo)); + + assertThrows( + IllegalArgumentException.class, + () -> initializer.run(new DefaultApplicationArguments(new String[] {}))); + + verify(authorityService, never()).upsertPointer(org.mockito.ArgumentMatchers.any()); + } + + @Test + void runRejectsDuplicateWorldRealmSeedsBeforeAnyMutation() throws Exception { + when(pointerRepository.count()).thenReturn(0L); + properties.setPointers( + List.of( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, false), + pointerSeed(" DEMO ", "Duplicate World", "PRODUCTION", "Live Realm", 1L, 2L, true))); + + assertThrows( + IllegalArgumentException.class, + () -> initializer.run(new DefaultApplicationArguments(new String[] {}))); + + verify(authorityService, never()).upsertPointer(org.mockito.ArgumentMatchers.any()); + } + + @Test + void runAllowsSameWorldRealmSelectorInDifferentTenants() throws Exception { + when(pointerRepository.count()).thenReturn(0L); + properties.setPointers( + List.of( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, false), + pointerSeed("demo", "Other Demo", "production", "Live Realm", 2L, 1L, false))); + initializer.run(new DefaultApplicationArguments(new String[] {})); - ArgumentCaptor mutationCaptor = - ArgumentCaptor.forClass(GameplayAdmissionPointerMutation.class); - verify(authorityService).upsertPointer(mutationCaptor.capture()); - assertEquals("demo", mutationCaptor.getValue().worldSlug()); + verify(authorityService, org.mockito.Mockito.times(2)) + .upsertPointer(org.mockito.ArgumentMatchers.any()); } @Test From 2c451bc48021a5fbdf0bc50ab14310d738059585 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:34:38 +1300 Subject: [PATCH 44/75] Require canonical playable namespace IDs at join ingress --- .../service/impl/AccountGrpcService.java | 17 +- .../service/impl/AccountServiceImpl.java | 22 ++- .../service/impl/AccountGrpcServiceTest.java | 48 +++++- .../service/impl/AccountServiceImplTest.java | 149 +++++++++++++----- .../PublicInternalRouteBlockFilterTest.java | 3 +- 5 files changed, 185 insertions(+), 54 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 116d3c74c4..4478433016 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -201,7 +201,7 @@ private DirectTextCallerContext directTextCaller( requirePositiveRequestId(context.getAccountId(), "accountId"), requirePositiveRequestId(context.getTenantId(), "tenantId"), requireCanonicalRealmId(context.getRealmId()), - requireText(context.getPlayableStateNamespaceId(), "playableStateNamespaceId"), + requireCanonicalPlayableStateNamespaceId(context.getPlayableStateNamespaceId()), requireText(context.getPlayableStateScope(), "playableStateScope"), requirePositiveRequestId(context.getGameInstanceId(), "gameInstanceId"), requireText(context.getSessionId(), "sessionId"), @@ -223,6 +223,21 @@ private UUID requireCanonicalRealmId(String value) { } } + private String requireCanonicalPlayableStateNamespaceId(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("playableStateNamespaceId is required"); + } + try { + UUID namespaceId = UUID.fromString(value); + if (!namespaceId.toString().equals(value)) { + throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID"); + } + return value; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID", ex); + } + } + private String requireText(String value, String fieldName) { int maxLength = "connectScopeId".equals(fieldName) ? 2048 : 128; if (value == null || value.isBlank() || value.length() > maxLength) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 0a50307794..29fdda6358 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -2431,9 +2431,8 @@ private RuntimeRealmTarget buildRuntimeRealmTarget( long tenantId = requirePositiveLong(tenantIdText, "tenantId"); UUID realmId = requireCanonicalRealmId(realmIdText); long gameInstanceId = requirePositiveLong(gameInstanceIdText, "gameInstanceId"); - if (!StringUtils.hasText(playableStateNamespaceId)) { - throw new IllegalArgumentException("playableStateNamespaceId is required"); - } + String canonicalPlayableStateNamespaceId = + requireCanonicalPlayableStateNamespaceId(playableStateNamespaceId); if (catalogRevision <= 0) { throw new IllegalArgumentException("catalogRevision must be positive"); } @@ -2452,7 +2451,7 @@ private RuntimeRealmTarget buildRuntimeRealmTarget( return new RuntimeRealmTarget( tenantId, realmId, - playableStateNamespaceId, + canonicalPlayableStateNamespaceId, gameInstanceId, worldSlug, realmSlug, @@ -2495,6 +2494,21 @@ private UUID requireCanonicalRealmId(Object value) { } } + private String requireCanonicalPlayableStateNamespaceId(String value) { + if (!StringUtils.hasText(value)) { + throw new IllegalArgumentException("playableStateNamespaceId is required"); + } + try { + UUID namespaceId = UUID.fromString(value); + if (!namespaceId.toString().equals(value)) { + throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID"); + } + return value; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID", ex); + } + } + private record ConnectScopeContext( long accountId, long tenantId, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index c64e116fc8..97ab9c3fc8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -67,6 +67,7 @@ class AccountGrpcServiceTest { private static final String WORKLOAD_NAMESPACE = "test"; private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; private static final String OTHER_REALM_ID = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; + private static final String PLAYABLE_STATE_NAMESPACE_ID = "c6ed6a44-c7e7-4f18-81fc-078a74e67c07"; private static final GrpcPeerIdentity GAME_SESSION_PEER = new GrpcPeerIdentity( "spiffe://firemud/ns/test/sa/game-session-service", @@ -78,7 +79,7 @@ private static PlayerExecutionContext validPlayerContext() { .setAccountId("10") .setTenantId("20") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("realm-state-30") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setPlayableStateScope("realm:30") .setGameInstanceId("40") .setSessionId("session-1") @@ -93,7 +94,7 @@ private static IssueDirectTextConnectScopeRequest validScopeRequest() { .setRealmId(REALM_ID) .setWorldSlug("world") .setRealmSlug("public") - .setPlayableStateNamespaceId("realm-state-30") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setPlayableStateScope("realm:30") .setGameInstanceId("40") .setCatalogRevision(5) @@ -179,7 +180,7 @@ void issueDirectTextConnectScopeAcceptsExactGameSessionPeerAndTypedTarget() { 10L, 20L, UUID.fromString(REALM_ID), - "realm-state-30", + PLAYABLE_STATE_NAMESPACE_ID, "realm:30", 40L, "session-1", @@ -189,7 +190,7 @@ void issueDirectTextConnectScopeAcceptsExactGameSessionPeerAndTypedTarget() { UUID.fromString(REALM_ID), "world", "public", - "realm-state-30", + PLAYABLE_STATE_NAMESPACE_ID, "realm:30", 40L, 5L, @@ -229,7 +230,7 @@ void joinPublicProductionMembershipPreservesStoredFailureOutcome() { 10L, 20L, UUID.fromString(REALM_ID), - "realm-state-30", + PLAYABLE_STATE_NAMESPACE_ID, "realm:30", 40L, "session-1", @@ -365,6 +366,43 @@ void directTextScopeRejectsNoncanonicalRealmIdsAtBothIngressFields(String realmI Mockito.verifyNoInteractions(accountService); } + @ParameterizedTest + @ValueSource( + strings = { + "shared-live", + "C6ED6A44-C7E7-4F18-81FC-078A74E67C07", + "c6ed6a44c7e74f1881fc078a74e67c07" + }) + void directTextMethodsRejectNoncanonicalPlayableStateNamespaceIdsAtIngress(String namespaceId) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + PlayerExecutionContext malformedContext = + validPlayerContext().toBuilder().setPlayableStateNamespaceId(namespaceId).build(); + RecordingObserver scopeObserver = + new RecordingObserver<>(); + RecordingObserver joinObserver = + new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.issueDirectTextConnectScope( + validScopeRequest().toBuilder().setPlayerContext(malformedContext).build(), + scopeObserver)); + withPeer( + GAME_SESSION_PEER, + () -> + service.joinPublicProductionMembership( + validJoinRequest().toBuilder().setPlayerContext(malformedContext).build(), + joinObserver)); + + assertEquals("INVALID_ARGUMENT", scopeObserver.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", joinObserver.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + @Test void authenticateFailureReturnsErrorDetail() { PingService pingService = Mockito.mock(PingService.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 249c8bc649..aca95e5413 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -85,6 +85,9 @@ class AccountServiceImplTest { private static final String JWT_SECRET = "mysecretkey123456789012345678901"; private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; + private static final String PLAYABLE_STATE_NAMESPACE_ID = "c6ed6a44-c7e7-4f18-81fc-078a74e67c07"; + private static final String PLAYABLE_STATE_NAMESPACE_ID_TENANT_8 = + "a741a4b8-a2cb-405e-a330-8fbf3dfb841f"; @Mock private AccountRepository accountRepository; @Mock private AccountAuditOutboxRepository accountAuditOutboxRepository; @Mock private AccountConnectScopeRepository accountConnectScopeRepository; @@ -157,7 +160,7 @@ void setup() { .setTenantId("7") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -176,7 +179,7 @@ void setup() { .setTenantId("7") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -829,7 +832,7 @@ void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTrans UUID.fromString(REALM_ID), "demo", "production", - "production-namespace-7", + PLAYABLE_STATE_NAMESPACE_ID, "SHARED", 44L, 23L, @@ -939,7 +942,7 @@ void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { UUID.fromString(REALM_ID), "demo", "production", - "production-namespace-7", + PLAYABLE_STATE_NAMESPACE_ID, "SHARED", 44L, 23L, @@ -1843,7 +1846,7 @@ void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { .setTenantId("bad") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -1904,7 +1907,7 @@ void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { .setTenantId("7") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -2058,7 +2061,7 @@ void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { .setTenantId("7") .setGameInstanceId("44") .setRealmId(realmId) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -2273,7 +2276,7 @@ void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { Map.entry("realmId", realmId), Map.entry("worldSlug", "demo"), Map.entry("realmSlug", "production"), - Map.entry("playableStateNamespaceId", "production-namespace-7"), + Map.entry("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID), Map.entry("playableStateScope", "SHARED"), Map.entry("gameInstanceId", "44"), Map.entry("catalogRevision", "23"), @@ -2639,7 +2642,7 @@ void issueDirectTextConnectScopeRejectsBlankRequestIdBeforeAuthorityOrScopeWork( 11L, 7L, UUID.fromString(REALM_ID), - "production-namespace-7", + PLAYABLE_STATE_NAMESPACE_ID, "SHARED", 44L, "session-1", @@ -2822,7 +2825,7 @@ void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { .setTenantId("7") .setGameInstanceId("99") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) @@ -2876,7 +2879,7 @@ void issueConnectTokenRejectsWorldMismatchAfterBootstrapDiscovery() { .setTenantId("7") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -2934,7 +2937,7 @@ void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { .setTenantId("") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -2996,7 +2999,7 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() .setTenantId("7") .setGameInstanceId("99") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) @@ -3234,7 +3237,7 @@ void issueConnectTokenRejectsPresentNonAdmittingMembership( .setTenantId("7") .setGameInstanceId("55") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(true) @@ -3253,7 +3256,7 @@ void issueConnectTokenRejectsPresentNonAdmittingMembership( .setTenantId("7") .setGameInstanceId("55") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(true) @@ -3327,7 +3330,7 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { .setTenantId("7") .setGameInstanceId("99") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) @@ -3362,7 +3365,7 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { .setTenantId("7") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -3605,7 +3608,7 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis .setTenantId("7") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -3625,7 +3628,7 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis .setTenantId("7") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -3681,7 +3684,7 @@ void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { .setTenantId("7") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -3734,7 +3737,7 @@ void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { .setTenantId("7") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -3781,11 +3784,59 @@ void listBootstrapRealmsIncludesRealmStatePolicy() { .get("realmId")); assertEquals("SHARED", realms.getFirst().stateScope()); assertEquals(23L, realms.getFirst().catalogRevision()); - assertEquals("production-namespace-7", realms.getFirst().playableStateNamespaceId()); + assertEquals(PLAYABLE_STATE_NAMESPACE_ID, realms.getFirst().playableStateNamespaceId()); assertEquals("PLAYABLE_STATE_SCOPE_SHARED", realms.getFirst().playableStateScope()); assertEquals("ALLOW_NEW", realms.getFirst().characterCreationPolicy()); } + @ParameterizedTest + @ValueSource( + strings = { + "shared-live", + "C6ED6A44-C7E7-4F18-81FC-078A74E67C07", + "c6ed6a44c7e74f1881fc078a74e67c07" + }) + void listBootstrapRealmsRejectsNoncanonicalPlayableStateNamespaceIdFromReachableRealm( + String namespaceId) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(namespaceId) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + @Test void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { Account account = new Account(); @@ -3806,7 +3857,7 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { .setTenantId("bad") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -3822,7 +3873,7 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { .setTenantId("7") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -3863,7 +3914,7 @@ void listBootstrapRealmsRejectsRealmWithUnknownStateScope() { .setTenantId("7") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -3905,7 +3956,7 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { .setTenantId("7") .setGameInstanceId("91") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -3924,7 +3975,7 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { .setTenantId("7") .setGameInstanceId("91") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -3981,7 +4032,7 @@ void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() .setTenantId("7") .setGameInstanceId("bad") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -4029,7 +4080,7 @@ void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { .setTenantId("7") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -4076,7 +4127,7 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setTenantId("7") .setGameInstanceId("91") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -4095,7 +4146,7 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setTenantId("7") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -4114,7 +4165,7 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setTenantId("7") .setGameInstanceId("91") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -4174,7 +4225,7 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { .setTenantId("7") .setGameInstanceId("44") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(17L) .setVisible(true) @@ -4189,7 +4240,7 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { .setTenantId("8") .setGameInstanceId("45") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-8") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID_TENANT_8) .setCatalogRevision(23L) .setPointerVersion(18L) .setVisible(true) @@ -4318,7 +4369,7 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { .setTenantId("7") .setGameInstanceId("55") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(false) @@ -4366,7 +4417,7 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( .setTenantId("7") .setGameInstanceId("55") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) @@ -4385,7 +4436,7 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( .setTenantId("7") .setGameInstanceId("55") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) @@ -4429,7 +4480,7 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( .setTenantId("7") .setGameInstanceId("55") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) @@ -4491,7 +4542,7 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( .setTenantId("7") .setGameInstanceId("55") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) @@ -4510,7 +4561,7 @@ void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( .setTenantId("7") .setGameInstanceId("55") .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(23L) .setPointerVersion(19L) .setVisible(visible) @@ -5021,7 +5072,7 @@ private static DirectTextCallerContext directTextCaller() { 11L, 7L, UUID.fromString(REALM_ID), - "production-namespace-7", + PLAYABLE_STATE_NAMESPACE_ID, "SHARED", 44L, "session-1", @@ -5034,7 +5085,7 @@ private static DirectTextJoinTarget directTextTarget() { UUID.fromString(REALM_ID), "demo", "production", - "production-namespace-7", + PLAYABLE_STATE_NAMESPACE_ID, "SHARED", 44L, 23L, @@ -5069,7 +5120,7 @@ private static net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer ad .setTenantId(Long.toString(tenantId)) .setGameInstanceId(gameInstanceId) .setRealmId(REALM_ID) - .setPlayableStateNamespaceId("production-namespace-" + tenantId) + .setPlayableStateNamespaceId(playableStateNamespaceIdForTenant(tenantId)) .setCatalogRevision(23L) .setPointerVersion(pointerVersion) .setVisible(visible) @@ -5080,6 +5131,18 @@ private static net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer ad .build(); } + private static String playableStateNamespaceIdForTenant(long tenantId) { + return switch ((int) tenantId) { + case 7 -> PLAYABLE_STATE_NAMESPACE_ID; + case 8 -> PLAYABLE_STATE_NAMESPACE_ID_TENANT_8; + default -> + UUID.nameUUIDFromBytes( + ("playable-state-namespace-" + tenantId) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .toString(); + }; + } + private static AccountTenantMembership membership(Account account, long tenantId) { AccountTenantMembership membership = new AccountTenantMembership(); membership.setId(tenantId * 100 + (account.getId() == null ? 0L : account.getId())); diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java index 8b2911c920..1bad11ccc0 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java @@ -329,7 +329,8 @@ private WebFilterChain chain(AtomicBoolean chainCalled) { } private void assertBlockedPost(String path) { - MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post(path).build()); + MockServerWebExchange exchange = + MockServerWebExchange.from(MockServerHttpRequest.post(path).build()); AtomicBoolean chainCalled = new AtomicBoolean(false); filter.filter(exchange, chain(chainCalled)).block(); From 478e3b2377ec8651c45819c47640b80b9f149ff4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 09:33:53 +1300 Subject: [PATCH 45/75] Clarify hosted readiness and Social Groups egress guidance --- k8s/hosted-identity-controller/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/k8s/hosted-identity-controller/README.md b/k8s/hosted-identity-controller/README.md index 4ee1596bcd..8df1914c3a 100644 --- a/k8s/hosted-identity-controller/README.md +++ b/k8s/hosted-identity-controller/README.md @@ -18,9 +18,9 @@ There is no user-supplied hostname, Secret, Certificate, issuer, port, key, roll The trusted preview workflow derives an explicit mode from the validated runtime artifact: a `ClusterIP` `tcp-proxy-service` selects `private`, and a `NodePort` selects `public`. The runtime Namespace must carry the matching `firemud.dev/preview-exposure-mode` label; an absent, unknown, or changed mode is invalid. The controller never infers private mode from a failed public probe. -In `private` mode, the runtime TCP Proxy Service remains `ClusterIP`, has no NodePort, and has no canonical Telnet-port annotation. `telnetPort=0` is an internal profile sentinel only. After all five labeled, key-complete shared-role projections and the required Gateway/TCP Proxy rollouts converge, `Ready=True` requires served HTTPS, the private Gateway-to-TCP Proxy mutual-TLS bridge, and gRPC probes. The private proof therefore proves the internal bridge without claiming a public TCP endpoint, Telnet smoke, or gameplay acceptance. +In `private` mode, the runtime TCP Proxy Service remains `ClusterIP`, has no NodePort, and has no canonical Telnet-port annotation. `telnetPort=0` is an internal profile sentinel only. After all five labeled, key-complete publication projections, the distinct Account, Game Session, and Social Groups workload projections, and the required Gateway/TCP Proxy rollouts converge, `Ready=True` requires served HTTPS, the private Gateway-to-TCP Proxy mutual-TLS bridge, and gRPC probes. The private proof therefore proves the internal bridge without claiming a public TCP endpoint, Telnet smoke, or gameplay acceptance. -In `public` mode, the trusted allocator supplies the reserved NodePort and the runtime Namespace carries its Telnet-port annotation. `Ready=True` retains the public Telnet probe in addition to HTTPS, the Gateway-to-TCP Proxy bridge, gRPC, all five shared-role projections, and rollout convergence; the trusted workflow then requires the public `LOGIN -> PLAY -> LOOK` smoke. A public probe or smoke failure is terminal for public mode and cannot fall back to private mode. This bounded private mode does not replace the public two-path target in [ADR 0178](../../design/architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md). +In `public` mode, the trusted allocator supplies the reserved NodePort and the runtime Namespace carries its Telnet-port annotation. `Ready=True` retains the public Telnet probe in addition to HTTPS, the Gateway-to-TCP Proxy bridge, gRPC, all five publication projections, the distinct Account, Game Session, and Social Groups workload projections, and rollout convergence; the trusted workflow then requires the public `LOGIN -> PLAY -> LOOK` smoke. A public probe or smoke failure is terminal for public mode and cannot fall back to private mode. This bounded private mode does not replace the public two-path target in [ADR 0178](../../design/architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md). ## Resource and status contract @@ -52,7 +52,7 @@ Kubernetes RBAC cannot constrain `create`, `escalate`, or `bind` with `resourceN The NetworkPolicy is fail-closed for controller egress. Its raw manifest contains required address markers, and the trusted bootstrap replaces them with validated `/32` IPv4 CIDRs in a private render. `--api-service-ipv4`, `--api-endpoint-ipv4`, and `--public-probe-ipv4` are required together for `observe` or `active` mode; a paused bootstrap without them substitutes `127.0.0.1/32` for all three destinations so the break-glass pause cannot reopen broad egress. The bootstrap reads back the `kubernetes.default` Service ClusterIP and the single observed API endpoint on TCP/6443 before any cluster write, and fails closed unless the fixed `dev.preview.firedevops.net` lookup returns exactly one matching IPv4 A record. -The hosted k3s cluster uses flannel VXLAN with kube-router policy enforcement: `kubernetes.default` is exposed on ClusterIP `:443`, DNATed to the hosted node API endpoint `:6443`, and kube-router evaluates the effective post-DNAT destination port. Separate exact rules therefore cover the API Service on TCP/443, the observed API endpoint on TCP/6443, and the fixed public probe address on TCP/443 plus NodePorts 32000-32016. In the observed LoadBalancer path, public HTTPS is DNATed to the kube-system Traefik pods on TCP/8443. Only public preview mode uses the TCP Proxy NodePort path, which is DNATed to selected `tcp-proxy-service` pods on TCP/2323; private mode uses the in-cluster ClusterIP bridge and never requires that NodePort. The policy grants only exact, label-scoped target ports. A separate selector rule reaches only `spring-cloud-gateway` pods in namespaces carrying the externally owned canonical preview or dev-demo label on TCP/443 and TCP/8443. DNS and the label-scoped Account and Game Session TCP/6565 selectors remain exact. Kubernetes NetworkPolicy cannot identify an API server or public hostname, so the controller must enforce the derived SNI/SAN/issuer allowlist itself. Standard NetworkPolicy implementations may exempt traffic to the local node, and the actual post-DNAT behavior and exact allow/deny boundary—including public NodePort target-port behavior—must be proven live; static rendering is not operational proof. PO-3.2 remains incomplete until the live allow/deny matrix and served Gateway↔TCP Proxy bridge proof succeed. +The hosted k3s cluster uses flannel VXLAN with kube-router policy enforcement: `kubernetes.default` is exposed on ClusterIP `:443`, DNATed to the hosted node API endpoint `:6443`, and kube-router evaluates the effective post-DNAT destination port. Separate exact rules therefore cover the API Service on TCP/443, the observed API endpoint on TCP/6443, and the fixed public probe address on TCP/443 plus NodePorts 32000-32016. In the observed LoadBalancer path, public HTTPS is DNATed to the kube-system Traefik pods on TCP/8443. Only public preview mode uses the TCP Proxy NodePort path, which is DNATed to selected `tcp-proxy-service` pods on TCP/2323; private mode uses the in-cluster ClusterIP bridge and never requires that NodePort. The policy grants only exact, label-scoped target ports. A separate selector rule reaches only `spring-cloud-gateway` pods in namespaces carrying the externally owned canonical preview or dev-demo label on TCP/443 and TCP/8443. DNS and the label-scoped Account, Game Session, and Social Groups TCP/6565 selectors remain exact. Kubernetes NetworkPolicy cannot identify an API server or public hostname, so the controller must enforce the derived SNI/SAN/issuer allowlist itself. Standard NetworkPolicy implementations may exempt traffic to the local node, and the actual post-DNAT behavior and exact allow/deny boundary—including public NodePort target-port behavior—must be proven live; static rendering is not operational proof. PO-3.2 remains incomplete until the live allow/deny matrix and served Gateway↔TCP Proxy bridge proof succeed. The checked-in Deployment contains fail-closed image and activation markers. `bootstrap-hosted-identity-controller.sh` accepts only the approved image repository with a full SHA-256 digest and an explicit `paused`, `observe`, or `active` mode. Before invoking `kubectl`, it uses GitHub CLI attestation verification to require default SLSA provenance from this repository's `runtime-images.yml` workflow on exactly `develop` or `main` and rejects self-hosted-runner provenance. The trusted operator context therefore requires Python 3 with PyYAML, `gh` authenticated for GitHub API and private-repository attestation reads, read authentication for the private GHCR image, and network access to GitHub API, GHCR, and the Sigstore trust services used by GitHub attestations. After verification, bootstrap substitutes the image, gRPC trust-anchor fingerprint, and mode in a private render. For every mode, it validates the fixed `firemud-system/firemud-grpc-ca` certificate, key, and configured fingerprint before its first cluster write. It then applies and reads back the fail-closed namespace guard and its `Deny` binding before applying the namespace-lifecycle ClusterRoleBinding, followed by server-side apply without force-conflict takeover for the complete install. Its default is `paused`; Active bootstrap retains the later gate that verifies every required validating admission policy and binding before the controller is permitted to reconcile. From bc1b50590c1ae8f34f1b825dfdf94a03c734963f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 10:07:48 +1300 Subject: [PATCH 46/75] Correct shared leaf workload comment --- dev-tools/hosted/shared/ensure-grpc-tls-secret.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh b/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh index 71eacf60e1..399c3fc851 100644 --- a/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh +++ b/dev-tools/hosted/shared/ensure-grpc-tls-secret.sh @@ -280,8 +280,8 @@ if ((shared_snapshot_status == 0)); then "${shared_rotation_resources[*]}" || exit 1 assert_key_matches_certificate "$shared_cert" "$shared_key" else - # The legacy shared bundle is still required by the four remaining - # shared-leaf workloads. Generate it once, then preserve its leaf on every later run. + # The legacy shared bundle is still required by remaining shared-leaf workloads. + # Generate it once, then preserve its leaf on every later run. "$legacy_generator" "$cert_dir" for required_file in ca.crt client.crt client.key ca.key; do [[ -s "$cert_dir/$required_file" ]] || { From ce461785ae119e33fc8c412e25904186ac561e1b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 19:45:39 +1300 Subject: [PATCH 47/75] Classify unknown realm-list world selectors as client errors --- .../gamesession/service/impl/GameSessionGrpcService.java | 5 +---- .../gamesession/service/impl/GameSessionGrpcServiceTest.java | 4 ++-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 90b5843d5b..dd79edf848 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -556,10 +556,7 @@ public void listGameplayRealms( WorldView world = gameplayWorldCatalog .resolveWorldFromAuthoritySnapshot(worldSelector) - .orElseThrow( - () -> - new CatalogRevisionUnavailableException( - "Authoritative gameplay world selection is unavailable")); + .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay world selection")); List realms = gameplayWorldCatalog.visibleRealms(world).stream() .map(realm -> toGameplayRealm(world.slug(), realm)) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index c9fa338865..243136b757 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -1033,7 +1033,7 @@ public void onCompleted() {} } @Test - void unknownNamedWorldFailsClosedAsAdmissionPointerUnavailable() { + void unknownNamedWorldReturnsInvalidArgument() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of()); @@ -1052,7 +1052,7 @@ void unknownNamedWorldFailsClosedAsAdmissionPointerUnavailable() { ListGameplayRealmsResponse response = listGameplayRealms(service, "unknown-world"); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); assertEquals(0, response.getRealmsCount()); } From 5cf8474f54b4b6f19455b15907cb1029547ffc5d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 00:06:47 +1300 Subject: [PATCH 48/75] Preserve common peer trust for Account and Game Session leaves --- .../environment-and-secrets-overview.md | 4 +- dev-tools/deploy/preflight.py | 131 +++++++-------- ...d-identity-controller-manifest-contract.sh | 2 +- dev-tools/tests/preflight-contract.sh | 152 ++++++++++-------- k8s/base/account-service.yaml | 16 +- k8s/base/game-session-service.yaml | 16 +- 6 files changed, 177 insertions(+), 144 deletions(-) diff --git a/design/architecture/infrastructure/environment-and-secrets-overview.md b/design/architecture/infrastructure/environment-and-secrets-overview.md index c824b0d341..6c162d5237 100644 --- a/design/architecture/infrastructure/environment-and-secrets-overview.md +++ b/design/architecture/infrastructure/environment-and-secrets-overview.md @@ -135,7 +135,7 @@ This section describes the Kubernetes-backed environments that use the canonical - Kubernetes `ConfigMap` objects store non‑secret configuration values like host names or feature flags. - Sensitive values (database passwords, TLS private keys, and interim JWT signing bundles) are delivered through Kubernetes `Secret` objects. The public `jwt-jwks` projection is delivered separately as read-only public material; hosted preview materializes it as a `ConfigMap`. -- TLS certificates are issued by **cert-manager** and rotated automatically. The eight gRPC workload consumers (the five publication services plus Account, Game Session, and Social Groups) use distinct leaf certificate/private-key Secrets; other gRPC workloads still use the shared leaf identity. Publication and Social Groups Pods use their own Secret for the leaf and key and project only `ca.crt` from the shared `firemud-grpc-tls` bundle for peer trust. The checked-in Kustomize Account and Game Session Pods use `/tls/ca.crt` from their respective leaf Secret for peer trust, while hosted Helm projects `ca.crt` from the shared bundle for these workloads too. Hosted rendering remains incomplete evidence for the full target identity boundary and is not player-facing equivalence. Services reload updated certificates using `TlsCertificateWatcher` / `GrpcServerTlsReloader`. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). +- TLS certificates are issued by **cert-manager** and rotated automatically. The eight gRPC workload consumers (the five publication services plus Account, Game Session, and Social Groups) use distinct leaf certificate/private-key Secrets; other gRPC workloads still use the shared leaf identity. Each distinct workload projects only `tls.crt` and `tls.key` from its own Secret at `/tls`, and only `ca.crt` from the shared `firemud-grpc-tls` bundle at `/grpc-trust` for peer trust. Live issuance and served-identity readiness remain unproved, and hosted rendering is not player-facing or promotion evidence. Services reload updated certificates using `TlsCertificateWatcher` / `GrpcServerTlsReloader`. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). - JWT authority and lifecycle are defined by [JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md). This overview records only the interim Account private-bundle mount, public JWKS mounts, and watcher delivery. - In player-facing environments (`hobby-self-hosted`, staging, production), the selected `INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK` mode allows only Account Service to consume JWT private signing material from a mounted file via `FIREMUD_AUTH_JWT_SECRET_PATH`, and only Account uses `JwtSecretWatcher` on that path; Account and every validator must consume the public JWKS projection. The selected `TARGET_NON_EXPORTABLE_SIGNER` mode has no private path or application private material and uses the same public-JWKS consumer boundary. The current `LEGACY_SECRET_DIAGNOSTIC` mode is shared-HMAC Secret/path wiring evidence only and is never player-facing authorization; inline-only or HMAC-only configuration and private-key mounts in validators are non-compliant for accepted modes. Current hosted preview is a separate HMAC/test wiring path and its hosted validation does not prove validator consumption. - Database credentials are stored in Secrets and rotated via explicit operational Jobs and runbooks (for example `db-credential-rotation` in `system-architecture-backup-recovery.md#post-restore-secret-hardening`); there is no fully automatic cadence today. @@ -446,7 +446,7 @@ The catalog document groups these variables by subsystem (PostgreSQL, Redis, TLS ## Certificate Management and Watchers -Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; see [Security Architecture](../system-architecture-security.md#cross-service-trust). Explicit local-development and throwaway-test profiles may use the documented plaintext internal transports and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. In hosted `pr-preview` and `dev-demo-cluster`, trusted certificate workflows provision distinct cert-manager-issued leaves for the five publication services, Account, Game Session, and Social Groups. The checked-in `k8s/base/` Pod manifests bind and mount each workload's corresponding `firemud-grpc-` Secret; they do not issue those certificates. Live leaf issuance and consumer readiness must be proven before hosted identity activation. Staging and production operators must provision all eight namespace-scoped workload Secrets and the shared `firemud-grpc-tls` trust bundle through the environment bootstrap process in the [deployment runbook](../system-architecture-deployment-runbook.md#environment-bootstrap). Other gRPC workloads continue to use the legacy shared leaf. Publication and Social Groups Pods read peer trust from only the public `ca.crt` key projected from `firemud-grpc-tls`, while their private identities remain in their service-specific Secrets. The checked-in Kustomize Account and Game Session Pods read peer trust from `/tls/ca.crt` in their respective leaf Secrets; hosted Helm instead uses the shared bundle's `ca.crt` projection for these workloads. The shared CA bundle must validate each of the eight distinct workload leaves as well as the shared leaf, so workloads using the shared trust projection can verify either leaf generation. Hosted rendering remains non-player-facing/non-promotion evidence. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). These certificates secure: +Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; see [Security Architecture](../system-architecture-security.md#cross-service-trust). Explicit local-development and throwaway-test profiles may use the documented plaintext internal transports and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. In hosted `pr-preview` and `dev-demo-cluster`, trusted certificate workflows provision distinct cert-manager-issued leaves for the five publication services, Account, Game Session, and Social Groups. The checked-in `k8s/base/` Pod manifests bind and mount each workload's corresponding `firemud-grpc-` Secret; they do not issue those certificates. Live leaf issuance and consumer readiness must be proven before hosted identity activation. Staging and production operators must provision all eight namespace-scoped workload Secrets and the shared `firemud-grpc-tls` trust bundle through the environment bootstrap process in the [deployment runbook](../system-architecture-deployment-runbook.md#environment-bootstrap). Other gRPC workloads continue to use the legacy shared leaf. Each of the eight distinct workload Pods projects only `tls.crt` and `tls.key` from its own Secret for its private identity, and only the public `ca.crt` key from `firemud-grpc-tls` for peer trust. The shared CA bundle must validate each of the eight distinct workload leaves as well as the shared leaf, so every distinct workload can verify either leaf generation during the intended mixed bootstrap. Hosted rendering remains non-player-facing/non-promotion evidence, and live issuance and consumer convergence remain unproved. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). These certificates secure: - All mTLS-protected gRPC calls between services - Any internal WebSocket bridges that require mTLS (for example, the TCP Proxy Service connecting to Spring Cloud Gateway over `wss://`) diff --git a/dev-tools/deploy/preflight.py b/dev-tools/deploy/preflight.py index 9b51da90a0..772156d50d 100644 --- a/dev-tools/deploy/preflight.py +++ b/dev-tools/deploy/preflight.py @@ -153,11 +153,9 @@ def _hosted_bridge_secret_ready_attempts_for_timeout(timeout_seconds: int) -> in SHARED_TRUST_GRPC_WORKLOADS = ( *PUBLICATION_GRPC_WORKLOADS, "social-groups-service", -) -GRPC_WORKLOAD_SECRET_CONSUMERS = ( - *SHARED_TRUST_GRPC_WORKLOADS, *ACCOUNT_GAME_SESSION_GRPC_WORKLOADS, ) +GRPC_WORKLOAD_SECRET_CONSUMERS = SHARED_TRUST_GRPC_WORKLOADS GRPC_WORKLOAD_LEAF_SECRET_KEYS = {"tls.crt", "tls.key", "ca.crt"} PUBLICATION_GRPC_TRUST_SECRET_NAME = "firemud-grpc-tls" PUBLICATION_GRPC_TRUST_SECRET_KEYS = {"ca.crt"} @@ -950,7 +948,7 @@ def publication_workload_secret_requirements( expected: dict[str, Any], documents: list[dict[str, Any]], ) -> tuple[tuple[str, str, set[str]], ...]: - """Resolve workload leaf Secrets and the shared publication CA trust Secret.""" + """Resolve workload leaf Secrets and the shared gRPC CA trust Secret.""" expected_namespace = secret_binding_namespace( get(expected, "internalBindings.postgres.credentialsRef") ) @@ -977,7 +975,6 @@ def publication_workload_secret_requirements( leaf_secret_names: list[str] = [] for workload in GRPC_WORKLOAD_SECRET_CONSUMERS: is_publication_workload = workload in PUBLICATION_GRPC_WORKLOADS - uses_shared_trust = workload in SHARED_TRUST_GRPC_WORKLOADS workload_label = ( "publication workload" if is_publication_workload else "gRPC workload" ) @@ -1024,51 +1021,38 @@ def publication_workload_secret_requirements( raise ValueError( f"Expected exactly one grpc-tls volume for {workload_label} {workload}; found {len(grpc_volumes)}" ) - if uses_shared_trust and len(trust_volumes) != 1: + if len(trust_volumes) != 1: raise ValueError( f"Expected exactly one grpc-trust volume for {workload_label} {workload}; found {len(trust_volumes)}" ) - if not uses_shared_trust and trust_volumes: - raise ValueError( - f"Rendered {workload_label} {workload} must mount its CA from the leaf Secret, not grpc-trust" - ) grpc_volume = grpc_volumes[0] secret = grpc_volume.get("secret") secret_name = secret.get("secretName") if isinstance(secret, dict) else None expected_leaf_items = {("tls.crt", "tls.crt"), ("tls.key", "tls.key")} leaf_items = secret.get("items") if isinstance(secret, dict) else None - if uses_shared_trust: - leaf_projection_is_valid = ( - isinstance(leaf_items, list) - and len(leaf_items) == len(expected_leaf_items) - and all( - isinstance(item, dict) - and set(item) == {"key", "path"} - and isinstance(item.get("key"), str) - and isinstance(item.get("path"), str) - for item in leaf_items - ) - and { - (item["key"], item["path"]) - for item in leaf_items - if isinstance(item, dict) - } - == expected_leaf_items - ) - else: - # The Account and Game Session Kustomize volumes intentionally project the - # complete cert-manager Secret, including ca.crt, into /tls. - leaf_projection_is_valid = isinstance(secret, dict) and "items" not in secret + leaf_projection_is_valid = ( + isinstance(leaf_items, list) + and len(leaf_items) == len(expected_leaf_items) + and all( + isinstance(item, dict) + and set(item) == {"key", "path"} + and isinstance(item.get("key"), str) + and isinstance(item.get("path"), str) + for item in leaf_items + ) + and { + (item["key"], item["path"]) + for item in leaf_items + if isinstance(item, dict) + } + == expected_leaf_items + ) if ( not isinstance(secret, dict) or not isinstance(secret_name, str) or not secret_name.strip() or secret_name != secret_name.strip() - or not set(secret).issubset( - {"secretName", "defaultMode", "items"} - if uses_shared_trust - else {"secretName", "defaultMode"} - ) + or not set(secret).issubset({"secretName", "defaultMode", "items"}) or set(grpc_volume) != {"name", "secret"} or not leaf_projection_is_valid ): @@ -1092,39 +1076,38 @@ def publication_workload_secret_requirements( f"{expected_leaf_secret_name}; found {secret_name}" ) - if uses_shared_trust: - trust_volume = trust_volumes[0] - trust_secret = trust_volume.get("secret") - trust_secret_name = ( - trust_secret.get("secretName") if isinstance(trust_secret, dict) else None + trust_volume = trust_volumes[0] + trust_secret = trust_volume.get("secret") + trust_secret_name = ( + trust_secret.get("secretName") if isinstance(trust_secret, dict) else None + ) + expected_trust_items = {("ca.crt", "ca.crt")} + trust_items = trust_secret.get("items") if isinstance(trust_secret, dict) else None + if ( + not isinstance(trust_secret, dict) + or trust_secret_name != PUBLICATION_GRPC_TRUST_SECRET_NAME + or not set(trust_secret).issubset({"secretName", "defaultMode", "items"}) + or set(trust_volume) != {"name", "secret"} + or not isinstance(trust_items, list) + or len(trust_items) != len(expected_trust_items) + or any( + not isinstance(item, dict) + or set(item) != {"key", "path"} + or not isinstance(item.get("key"), str) + or not isinstance(item.get("path"), str) + for item in trust_items + ) + or { + (item["key"], item["path"]) + for item in trust_items + if isinstance(item, dict) + } + != expected_trust_items + ): + raise ValueError( + f"Rendered {workload_label} {workload} requires the shared CA-only " + f"Secret {PUBLICATION_GRPC_TRUST_SECRET_NAME} in its grpc-trust volume" ) - expected_trust_items = {("ca.crt", "ca.crt")} - trust_items = trust_secret.get("items") if isinstance(trust_secret, dict) else None - if ( - not isinstance(trust_secret, dict) - or trust_secret_name != PUBLICATION_GRPC_TRUST_SECRET_NAME - or not set(trust_secret).issubset({"secretName", "defaultMode", "items"}) - or set(trust_volume) != {"name", "secret"} - or not isinstance(trust_items, list) - or len(trust_items) != len(expected_trust_items) - or any( - not isinstance(item, dict) - or set(item) != {"key", "path"} - or not isinstance(item.get("key"), str) - or not isinstance(item.get("path"), str) - for item in trust_items - ) - or { - (item["key"], item["path"]) - for item in trust_items - if isinstance(item, dict) - } - != expected_trust_items - ): - raise ValueError( - f"Rendered {workload_label} {workload} requires the shared CA-only " - f"Secret {PUBLICATION_GRPC_TRUST_SECRET_NAME} in its grpc-trust volume" - ) containers = pod_spec.get("containers") if not isinstance(containers, list): @@ -1196,9 +1179,7 @@ def publication_workload_secret_requirements( expected_grpc_paths = { "FIREMUD_GRPC_CERT_CHAIN_PATH": "/tls/tls.crt", "FIREMUD_GRPC_PRIVATE_KEY_PATH": "/tls/tls.key", - "FIREMUD_GRPC_CA_CERT_PATH": ( - "/grpc-trust/ca.crt" if uses_shared_trust else "/tls/ca.crt" - ), + "FIREMUD_GRPC_CA_CERT_PATH": "/grpc-trust/ca.crt", } grpc_paths: dict[str, str] = {} for name in GRPC_TLS_PATH_NAMES: @@ -1241,9 +1222,8 @@ def publication_workload_secret_requirements( expected_mounts = { "grpc-tls": "/tls", + "grpc-trust": "/grpc-trust", } - if uses_shared_trust: - expected_mounts["grpc-trust"] = "/grpc-trust" validated_mounts: dict[str, dict[str, Any]] = {} for volume_name, mount_path in expected_mounts.items(): mounts = [mount for mount in volume_mounts if mount.get("name") == volume_name] @@ -1263,7 +1243,6 @@ def publication_workload_secret_requirements( ) validated_mounts[volume_name] = mount - ca_trust_mount = "/grpc-trust" if uses_shared_trust else "/tls" if any( not path_is_under_mount(path, "/tls") for path in ( @@ -1271,7 +1250,7 @@ def publication_workload_secret_requirements( grpc_paths["FIREMUD_GRPC_PRIVATE_KEY_PATH"], ) ) or not path_is_under_mount( - grpc_paths["FIREMUD_GRPC_CA_CERT_PATH"], ca_trust_mount + grpc_paths["FIREMUD_GRPC_CA_CERT_PATH"], "/grpc-trust" ): raise ValueError( f"Rendered {workload_label} {workload} gRPC TLS paths do not match its leaf/trust mount layout" diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index 0245c4213a..804ce78ee1 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -4834,7 +4834,7 @@ for service in ( ).get("spec", {}).get("strategy", {}) if base_strategy.get("type") != "Recreate": fail(f"Kustomize base Deployment/{service} must use non-rolling Recreate strategy") -for service in publication_services + ("social-groups-service",): +for service in distinct_workload_services: assert_distinct_workload_service(service, base_deployments, "Kustomize base") PY diff --git a/dev-tools/tests/preflight-contract.sh b/dev-tools/tests/preflight-contract.sh index f453a3c447..6ea2e047f2 100644 --- a/dev-tools/tests/preflight-contract.sh +++ b/dev-tools/tests/preflight-contract.sh @@ -1002,7 +1002,7 @@ spec: - name: FIREMUD_GRPC_PRIVATE_KEY_PATH value: /tls/tls.key - name: FIREMUD_GRPC_CA_CERT_PATH - value: /tls/ca.crt + value: /grpc-trust/ca.crt envFrom: - secretRef: name: postgres-credentials @@ -1012,6 +1012,9 @@ spec: - name: grpc-tls mountPath: /tls readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true - name: jwt-signing-keys mountPath: /var/run/secrets/firemud/jwt readOnly: true @@ -1022,6 +1025,17 @@ spec: - name: grpc-tls secret: secretName: firemud-grpc-account-service + 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: jwt-signing-keys secret: secretName: jwt-signing-keys @@ -1045,15 +1059,29 @@ spec: - name: FIREMUD_GRPC_PRIVATE_KEY_PATH value: /tls/tls.key - name: FIREMUD_GRPC_CA_CERT_PATH - value: /tls/ca.crt + value: /grpc-trust/ca.crt volumeMounts: - name: grpc-tls mountPath: /tls readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true volumes: - name: grpc-tls secret: secretName: firemud-grpc-game-session-service + 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 --- apiVersion: apps/v1 kind: Deployment @@ -9941,55 +9969,8 @@ publication_documents = [ } }, } - for workload in module.SHARED_TRUST_GRPC_WORKLOADS + for workload in module.GRPC_WORKLOAD_SECRET_CONSUMERS ] -for workload in module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS: - publication_documents.append( - { - "kind": "Deployment", - "metadata": {"name": workload, "namespace": "firemud"}, - "spec": { - "template": { - "spec": { - "volumes": [ - { - "name": "grpc-tls", - "secret": { - "secretName": f"firemud-grpc-{workload}", - }, - }, - ], - "containers": [ - { - "name": workload, - "env": [ - { - "name": path_name, - "value": path, - } - for path_name, path in zip( - module.GRPC_TLS_PATH_NAMES, - ( - "/tls/tls.crt", - "/tls/tls.key", - "/tls/ca.crt", - ), - ) - ], - "volumeMounts": [ - { - "name": "grpc-tls", - "mountPath": "/tls", - "readOnly": True, - }, - ], - } - ], - } - } - }, - } - ) if module.PUBLICATION_GRPC_WORKLOADS != ( "game-design-service", "world-management-service", @@ -10001,8 +9982,9 @@ if module.PUBLICATION_GRPC_WORKLOADS != ( if module.SHARED_TRUST_GRPC_WORKLOADS != ( *module.PUBLICATION_GRPC_WORKLOADS, "social-groups-service", + *module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS, ): - raise SystemExit("Social Groups must have a distinct leaf and the shared CA-only trust projection") + raise SystemExit("all eight distinct workloads must use the shared CA-only trust projection") publication_requirements = module.publication_workload_secret_requirements( publication_expected, publication_documents ) @@ -10076,9 +10058,7 @@ expect_publication_static_failure( for workload in module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS: - workload_index = len(module.SHARED_TRUST_GRPC_WORKLOADS) + ( - module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS.index(workload) - ) + workload_index = module.SHARED_TRUST_GRPC_WORKLOADS.index(workload) wrong_leaf_documents = copy.deepcopy(publication_documents) wrong_leaf_documents[workload_index]["spec"]["template"]["spec"]["volumes"][0][ "secret" @@ -10089,19 +10069,65 @@ for workload in module.ACCOUNT_GAME_SESSION_GRPC_WORKLOADS: f"grpc-tls Secret must be firemud-grpc-{workload}", ) - missing_ca_projection_documents = copy.deepcopy(publication_documents) - missing_ca_projection_documents[workload_index]["spec"]["template"]["spec"][ - "volumes" - ][0]["secret"]["items"] = [ - {"key": "tls.crt", "path": "tls.crt"}, - {"key": "tls.key", "path": "tls.key"}, + old_leaf_trust_documents = copy.deepcopy(publication_documents) + old_leaf_trust_spec = old_leaf_trust_documents[workload_index]["spec"]["template"][ + "spec" ] + old_leaf_trust_spec["volumes"] = [ + volume for volume in old_leaf_trust_spec["volumes"] if volume["name"] != "grpc-trust" + ] + old_leaf_trust_spec["containers"][0]["volumeMounts"] = [ + mount + for mount in old_leaf_trust_spec["containers"][0]["volumeMounts"] + if mount["name"] != "grpc-trust" + ] + old_leaf_trust_spec["volumes"][0]["secret"].pop("items") + next( + entry + for entry in old_leaf_trust_spec["containers"][0]["env"] + if entry["name"] == "FIREMUD_GRPC_CA_CERT_PATH" + )["value"] = "/tls/ca.crt" expect_publication_static_failure( - f"a {workload} leaf volume that omits ca.crt", - missing_ca_projection_documents, - "malformed grpc-tls Secret volume", + f"the obsolete {workload} leaf-CA-only trust layout", + old_leaf_trust_documents, + "Expected exactly one grpc-trust volume", + ) + + wrong_shared_trust_documents = copy.deepcopy(publication_documents) + wrong_shared_trust_spec = wrong_shared_trust_documents[workload_index]["spec"][ + "template" + ]["spec"] + wrong_shared_trust = next( + volume + for volume in wrong_shared_trust_spec["volumes"] + if volume["name"] == "grpc-trust" + ) + wrong_shared_trust["secret"]["secretName"] = f"firemud-grpc-{workload}" + expect_publication_static_failure( + f"a wrong {workload} shared trust Secret", + wrong_shared_trust_documents, + "requires the shared CA-only Secret firemud-grpc-tls", ) + for shared_private_key in ("client.key", "client.crt"): + private_shared_material_documents = copy.deepcopy(publication_documents) + private_shared_spec = private_shared_material_documents[workload_index]["spec"][ + "template" + ]["spec"] + private_shared_trust = next( + volume + for volume in private_shared_spec["volumes"] + if volume["name"] == "grpc-trust" + ) + private_shared_trust["secret"]["items"].append( + {"key": shared_private_key, "path": shared_private_key} + ) + expect_publication_static_failure( + f"a {workload} shared trust projection containing {shared_private_key}", + private_shared_material_documents, + "requires the shared CA-only Secret firemud-grpc-tls", + ) + swapped_leaf_documents = copy.deepcopy(publication_documents) first_leaf = swapped_leaf_documents[0]["spec"]["template"]["spec"]["volumes"][0][ diff --git a/k8s/base/account-service.yaml b/k8s/base/account-service.yaml index 660c68f15b..715a49e7cc 100644 --- a/k8s/base/account-service.yaml +++ b/k8s/base/account-service.yaml @@ -36,7 +36,7 @@ spec: - name: FIREMUD_GRPC_PRIVATE_KEY_PATH value: /tls/tls.key - name: FIREMUD_GRPC_CA_CERT_PATH - value: /tls/ca.crt + value: /grpc-trust/ca.crt envFrom: - configMapRef: name: firemud-config @@ -46,6 +46,9 @@ spec: - name: grpc-tls mountPath: /tls readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true - name: jwt-signing-keys mountPath: /var/run/secrets/firemud/jwt readOnly: true @@ -117,6 +120,17 @@ spec: - name: grpc-tls secret: secretName: firemud-grpc-account-service + 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: jwt-signing-keys secret: secretName: jwt-signing-keys diff --git a/k8s/base/game-session-service.yaml b/k8s/base/game-session-service.yaml index 4e1157951b..22cc946d32 100644 --- a/k8s/base/game-session-service.yaml +++ b/k8s/base/game-session-service.yaml @@ -37,7 +37,7 @@ spec: - name: FIREMUD_GRPC_PRIVATE_KEY_PATH value: /tls/tls.key - name: FIREMUD_GRPC_CA_CERT_PATH - value: /tls/ca.crt + value: /grpc-trust/ca.crt envFrom: - configMapRef: name: firemud-config @@ -47,6 +47,9 @@ spec: - name: grpc-tls mountPath: /tls readOnly: true + - name: grpc-trust + mountPath: /grpc-trust + readOnly: true - name: jwt-signing-keys mountPath: /var/run/secrets/firemud/jwt readOnly: true @@ -115,6 +118,17 @@ spec: - name: grpc-tls secret: secretName: firemud-grpc-game-session-service + 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: jwt-signing-keys secret: secretName: jwt-signing-keys From b810e5232927ac6b6283d49592d4af1a33b6bca3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 01:20:48 +1300 Subject: [PATCH 49/75] Stop advertising the unavailable public JOIN facade --- .../account-service/api-contracts.md | 2 +- .../src/main/resources/openapi.yaml | 63 +------------------ .../controller/AuthControllerTest.java | 20 ++++++ 3 files changed, 24 insertions(+), 61 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index bc2d9f4394..6bec48fb8a 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -190,7 +190,7 @@ These RPCs and schemas are accepted target state but are not present in the curr | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | | `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** it checks tenant `gameplayAvailable`, the current partial membership response without enforcing its emitted lifecycle state or generation, and public `allowPublicJoin`, but it does not yet enforce the complete private/playtest grant-and-entitlement target at connect-token issuance. **Current response drift:** the live `ConnectTokenResponse` body exposes the internal `jti`; the target response is metadata-only and must not expose `jti` or any raw token. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | -| `POST` | `/auth/bootstrap/join` | **Local Account controller and operation; complete production proof incomplete.** The local `JoinPublicProductionMembership` operation implements explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then reads entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Exact-final-head PostgreSQL proof, recovery/reconciliation after an unknown commit outcome, direct text end-to-end proof, and membership-generation snapshot proof remain open. | +| `POST` | `/auth/bootstrap/join` | **Local Account controller and operation; complete production proof incomplete.** The local `JoinPublicProductionMembership` operation implements explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then reads entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Exact-final-head PostgreSQL proof, recovery/reconciliation after an unknown commit outcome, direct text end-to-end proof, and membership-generation snapshot proof remain open. Public Gateway exposure remains denied/target-only pending the existing recovery, PostgreSQL, and direct text-client proof in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md); the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | | `DELETE` | `/tenants/{tenantId}/memberships/me` | Leave a joined game using caller-bound membership authority; removes future membership-based discovery/admission while retained character, purchase, audit, and legal data follow their owning policies | | `GET` | `/internal/runtime/tenants/{tenantId}/entitlements` | Internal runtime/admission entitlement snapshot for gameplay-affecting services | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index bb407e7ef7..4f3423930f 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -5,7 +5,9 @@ info: API for user accounts and authentication. The obsolete caller-asserted POST /accounts/{accountId}/external route is removed and denied at the public edge; no provider-linking route is available until the - server-verified global-account flow and its proof converge. + server-verified global-account flow and its proof converge. The public + POST /auth/bootstrap/join facade is target-only and denied until Account + recovery, PostgreSQL, and direct text-client proof are complete. version: 1.0.0 license: name: PolyForm Noncommercial License 1.0.0 @@ -130,35 +132,6 @@ components: requestId: type: string required: [connectScopeId, requestId] - JoinPublicProductionRequest: - type: object - properties: - connectScopeId: - type: string - description: Account-issued, caller-bound realm discovery scope - requestId: - type: string - description: Stable ID for this explicit join attempt; use a new ID for a new attempt - required: [connectScopeId, requestId] - JoinPublicProductionResult: - type: object - properties: - success: - type: boolean - outcomeCode: - type: string - accountId: - type: integer - tenantId: - type: integer - membershipId: - type: integer - membershipVersion: - type: integer - membershipAuthorityGeneration: - type: integer - replayed: - type: boolean ConnectTokenResponse: type: object properties: @@ -482,36 +455,6 @@ paths: $ref: '#/components/schemas/ErrorDetail' '401': description: Invalid or expired bootstrap token - /auth/bootstrap/join: - post: - summary: Explicitly join the selected public-production realm from a player-bootstrap scope - operationId: joinPublicProduction - security: - - bearerAuth: [] - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/JoinPublicProductionRequest' - responses: - '200': - description: Durable membership snapshot after a successful join or exact replay - content: - application/json: - schema: - type: object - properties: - status: - $ref: '#/components/schemas/ResultStatus' - data: - $ref: '#/components/schemas/JoinPublicProductionResult' - error: - $ref: '#/components/schemas/ErrorDetail' - '401': - description: Scope, policy, or membership state denied the join - '503': - $ref: '#/components/responses/RetryableAuthenticationUnavailable' /auth/connect-token: post: summary: Mint a short-lived gameplay connect token from a valid player-bootstrap token diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java index 1c604f3f24..704589da3f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java @@ -3,6 +3,8 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.matchesPattern; import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -13,6 +15,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.List; +import java.util.Map; import net.firedevops.firemud.accountservice.dto.AuthenticationResult; import net.firedevops.firemud.accountservice.dto.BootstrapCharacterDto; import net.firedevops.firemud.accountservice.dto.BootstrapRealmDto; @@ -36,6 +39,7 @@ import org.springframework.http.MediaType; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; +import org.yaml.snakeyaml.Yaml; import tools.jackson.databind.ObjectMapper; @WebMvcTest(AuthController.class) @@ -47,6 +51,22 @@ class AuthControllerTest { @MockitoBean private AccountService accountService; + @Test + void publicOpenApiOmitsUnavailableBootstrapJoin() throws Exception { + try (var input = getClass().getResourceAsStream("/openapi.yaml")) { + Map document = new Yaml().load(input); + Map paths = (Map) document.get("paths"); + Map components = (Map) document.get("components"); + Map schemas = (Map) components.get("schemas"); + + assertFalse(paths.containsKey("/auth/bootstrap/join")); + assertTrue(((Map) paths.get("/auth/player-bootstrap")).containsKey("post")); + assertTrue(((Map) paths.get("/auth/connect-token")).containsKey("post")); + assertFalse(schemas.containsKey("JoinPublicProductionRequest")); + assertFalse(schemas.containsKey("JoinPublicProductionResult")); + } + } + @Test void loginReturnsTokenAndAccountId() throws Exception { LoginRequest request = new LoginRequest("demo", "password"); From 57427f10368743a3214f68f72c2292b57ad1b457 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 02:35:17 +1300 Subject: [PATCH 50/75] Document unavailable admission-pointer authority and prove response --- .../logging-admin-service/api-contracts.md | 6 +-- ...e-session-runtime-and-tick-coordination.md | 2 + .../src/main/resources/openapi.yaml | 11 +++++ .../AdmissionPointerControllerTest.java | 45 +++++++++++++++++++ 4 files changed, 61 insertions(+), 3 deletions(-) diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index d4980cd14f..eb9cb06238 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -24,12 +24,12 @@ Routine rollback is expected to leave ordinary gameplay available while scoped A ## Implementation Status -- Feature-flag toggles and scoped tick-remediation pause/resume ingress routes now hard fail closed as unavailable operator mutations until the minimum three-part schema/authorization gate exists: their action-family schemas, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus redemption by the receiving authoritative owner. This minimum gate is necessary but not sufficient for live-success support; supported execution also requires the complete durable, idempotent, fenced owner-mutation contract in [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md), including durable intent/audit, stable digest-bound request identity, authoritative-owner state, safety/recovery gates, and durable acknowledgement. The HTTP entrypoints preserve authentication, authorization, and basic request validation, then return `503 Service Unavailable` with stable action-specific unavailable error codes (`FEATURE_FLAG_TOGGLE_UNAVAILABLE` or `TICK_REMEDIATION_UNAVAILABLE`) without invoking a service, owner, or audit dependency. The internal `ToggleFeatureFlag` gRPC entrypoint preserves admin-role, positive-tenant, and feature-name validation, then returns an application-level `UNAVAILABLE` error without dispatch. No Logging & Admin feature-flag or tick forwarding method remains callable internally. Admission-pointer reads, audit, and prepared-upgrade proof reads remain live. Public POST/operator mutation routes under `/admission-pointers`, `/cutover`, or `/version-upgrades` are target-only absent: no public HTTP handlers or Gateway write forwarding exist. Internal preparation/cutover service and control-plane implementation remains behind internal trust boundaries, and there is no current UI control. +- Feature-flag toggles and scoped tick-remediation pause/resume ingress routes now hard fail closed as unavailable operator mutations until the minimum three-part schema/authorization gate exists: their action-family schemas, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus redemption by the receiving authoritative owner. This minimum gate is necessary but not sufficient for live-success support; supported execution also requires the complete durable, idempotent, fenced owner-mutation contract in [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md), including durable intent/audit, stable digest-bound request identity, authoritative-owner state, safety/recovery gates, and durable acknowledgement. The HTTP entrypoints preserve authentication, authorization, and basic request validation, then return `503 Service Unavailable` with stable action-specific unavailable error codes (`FEATURE_FLAG_TOGGLE_UNAVAILABLE` or `TICK_REMEDIATION_UNAVAILABLE`) without invoking a service, owner, or audit dependency. The internal `ToggleFeatureFlag` gRPC entrypoint preserves admin-role, positive-tenant, and feature-name validation, then returns an application-level `UNAVAILABLE` error without dispatch. No Logging & Admin feature-flag or tick forwarding method remains callable internally. Admission-pointer reads, audit, and prepared-upgrade proof reads remain live; the current-pointer list is available only with exact latest-audit identity/catalog evidence and returns `503` when that authority is unavailable. Public POST/operator mutation routes under `/admission-pointers`, `/cutover`, or `/version-upgrades` are target-only absent: no public HTTP handlers or Gateway write forwarding exist. Internal preparation/cutover service and control-plane implementation remains behind internal trust boundaries, and there is no current UI control. - Availability vocabulary is explicit: **implemented-but-externally-gated** means an executable public controller/owner path exists but the shared mutation gate is incomplete; **target-only absent** means no executable public route exists. Admission-pointer mutation, version-upgrade preparation, and prepared cutover use the latter classification at public HTTP ingress even though internal preparation/cutover implementation remains. Quota-override ingress is also target-only absent. No generic tick-remediation payload or reserved `remediate` route is part of the target; each future recovery operation requires a named typed contract implemented by its authoritative workflow owner. - No forwarded owner mutation is currently supported as a live Logging & Admin capability until its minimum schema/authorization gate and the complete durable, idempotent, fenced owner-execution contract in [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) are implemented and proved. The service-local `POST /moderation/actions` endpoint and `ApplyModerationAction` gRPC path now hard fail closed after their narrow tenant/admin checks: HTTP returns `503 Service Unavailable`, gRPC returns an application-level `UNAVAILABLE` error, and neither path dispatches or persists the generic legacy `moderation_actions` row. They remain unsupported, nonconformant implementation drift and must not be wired or called as available mutations; separate fixed-category policy/audit evidence and owner enforcement state are absent, and they are not Gateway-forwarded or supported at external ingress. In the target local workflow, once its applicable schema/authorization and local durable intent/audit requirements are implemented, Logging & Admin records durable intent/case/audit evidence and redeems its one Account reference exactly once; it never forwards that reference or performs owner enforcement. A future typed owner-enforcement command uses a separately issued reference redeemed by its receiving owner. Game Session and Social & Groups synchronously consume the live `EvaluateModerationPolicy` read at the `GAMEPLAY_ADMISSION` and `CHAT_SEND` enforcement boundaries, but that evaluation does not make the legacy action route live. Fixed-category owner commands, monotonic owner state, bounded appeals, and broader policy coverage are not implemented. Existing Game Session `/sessions*` lifecycle routes are current owner-local hooks, not a complete external Logging & Admin route family. Separate current read and investigation surfaces include the PostgreSQL-backed log query, saga reads, metrics, and owner/control-plane reads; profile-aware indexed or console/journal query integration and embedded dashboard endpoints remain target-only and unimplemented. - Current `POST /logs/query` and `QueryLogs` read only the service-owned PostgreSQL `log_events` table. They require an exact tenant and apply case-insensitive containment to the stored message, returning the matching messages. They do not query deployed structured logs, mirror data to Elasticsearch, prove the ADR 0162 emitter-to-query path, implement a compatible indexed or console/journal profile, or expose Kibana/Grafana embedding. - The current moderation proto's `scope` and `action` fields are unrestricted strings, which is drift from ADR 0141's closed typed target rather than permission to accept arbitrary categories. Converged moderation ingress must validate the closed-category, typed-scope vocabulary and reject unknown values, `account_security_lock`, and its aliases before persistence. Only Account-owned security policy and recovery may create, extend, expire, remove, or clear `account_security_lock`; the moderation action route cannot create or clear it. `EvaluateModerationPolicy` remains a live read and carries no mutation authorization reference. -- Live admission-pointer reads, audit, and prepared-upgrade proof reads are part of the core operator/control-plane availability model and must not depend on observability backends. Admission-pointer mutation and preparation handlers are absent from public HTTP ingress and OpenAPI; their internal service/control-plane implementation must not be described as current live operator mutation support. +- Admission-pointer reads, audit, and prepared-upgrade proof reads are part of the core operator/control-plane availability model and must not depend on observability backends. `GET /admission-pointers` returns unavailable when a current pointer lacks matching latest audit identity/catalog evidence; historical audit remains a raw read that preserves unknown legacy identity. Admission-pointer mutation and preparation handlers are absent from public HTTP ingress and OpenAPI; their internal service/control-plane implementation must not be described as current live operator mutation support. - The internal `SetAdmissionPointerRequest` DTO omits `actorPrincipal`. `AdmissionPointerServiceImpl` derives the actor from the authenticated internal caller context and writes that derived value to the control-plane request; `actorPrincipal` is response/audit data, not client-supplied write authority. - Public administrative report persistence is currently unavailable. The unsafe controller that formerly occupied `POST /reports` and its `/api/admin/reports/**` Gateway exposure have been removed because the canonical role- and purpose-scoped authorization and live reference-validation checks are not implemented. Any restored administrative surface uses the distinct `POST /admin/reports` service path. `POST /reports` is reserved for the separate player-bootstrap submission contract and must bind the `player-bootstrap` subject and live tenant membership; it must not be inferred from or share the unavailable administrative route. The internal `CreateReport` gRPC contract is not public HTTP or player ingress, but its target exact workload/method authorization is unproved: current transport mTLS alone does not establish an allowlisted receiver identity. The interim receiver requires an internal-service JWT naming `social-groups-service`, while certificate-derived exact workload/method authorization remains unproved. Caller-supplied tenant, reporter, and optional target identities are data references only. - `ApplyModerationAction` has an implementation path, but `/moderation/actions` plus the gRPC action now hard fail closed after narrow tenant/admin checks. HTTP returns `503 Service Unavailable`, gRPC returns an application-level `UNAVAILABLE` error, and neither path dispatches or persists the generic legacy `moderation_actions` row. They remain unsupported/nonconformant drift, not available mutation support. The target gate requires the action-family schema, shared cross-language `mutationDigest/v1` vectors, Account authorization-reference issuance, and receiving-boundary validation/redemption. Separate fixed-category policy/audit evidence and owner enforcement are absent, and no forwarding occurs. Target behavior is Logging & Admin intent/case/audit persistence followed by exactly-once redemption of its local Account reference; that reference is never forwarded. A separate future owner-enforcement command has its own Account reference and receiving-owner redemption. The separate live `EvaluateModerationPolicy` contract supplies synchronous decisions consumed by Game Session at `GAMEPLAY_ADMISSION` and Social & Groups at `CHAT_SEND`; that compatibility read is a legacy, deny-only lookup over generic action rows ordered by recency, is nonconformant with ADR 0141's broadest-effect response precedence (`platform_access_ban` over `account_security_lock`, `chat_ban` over `chat_mute`), and does not implement or prove all five fixed categories or their independent lifecycles. It is not operator mutation support. Fixed-category owner-local enforcement, bounded appeals, and broader coverage remain target work under [Moderation Policies](./moderation-policies.md). @@ -65,7 +65,7 @@ The interim legacy numeric pin-read contract must also remain exact across JavaS - The service-local route `/moderation/actions` is an unavailable/gated human mutation and is not Gateway-forwarded or supported at external ingress until its action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and Logging & Admin validation/redemption exist. Current behavior hard fails closed after narrow tenant checks without dispatch or persistence; separate fixed-category policy/audit evidence and owner enforcement are absent, and no Gateway route forwards it. Target behavior records and redeems the local Logging & Admin intent/audit mutation with one Account reference; that reference is never forwarded. A separate future typed owner-enforcement command has its own request identity/digest and Account reference, redeemed by the receiving owner. They separately consume the synchronous `EvaluateModerationPolicy` result at `GAMEPLAY_ADMISSION` and `CHAT_SEND` while the target command path remains unimplemented. - `GET /sagas` – list Logging & Admin-local Saga instances; this is not platform-wide adopter aggregation. Returns `503 SAGA_DASHBOARD_UNAVAILABLE` when the conditional Saga/database beans are unavailable. - `GET /sagas/{id}/steps` – inspect steps for a known Logging & Admin-local Saga instance. An unknown instance returns `404 NOT_FOUND`; a known instance with no steps returns `200` with an empty list. Returns `503 SAGA_DASHBOARD_UNAVAILABLE` when the conditional Saga/database beans are unavailable. -- `GET /admission-pointers` – list the caller-visible Game Session route records joined with their separately revisioned catalog/policy projection, including `OPEN`/`CLOSED`, the route version, and the explicit public-production policy used by admission and first-join membership creation. +- `GET /admission-pointers` – list the caller-visible Game Session route records joined with their separately revisioned catalog/policy projection, including `OPEN`/`CLOSED`, the route version, and the explicit public-production policy used by admission and first-join membership creation. The list is available only while each current pointer's latest audit row exactly matches its catalog revision, `realmId`, and playable-state namespace; unavailable or incomplete current authority returns HTTP 503. Historical audit reads preserve unknown legacy identity fields. See the [current implementation and proof status](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#operator-readback-and-facade-boundaries). - `GET /admission-pointers/{tenantId}/{worldSlug}/{realmSlug}/audit` – read the append-only cutover audit history for one gameplay realm pointer, using the same canonical `{tenantId, worldSlug, realmSlug}` key as admission authority itself instead of inferring tenant ownership from world/realm selectors after the read. - Realm display, visibility, and public-production policy mutations use a separately revisioned catalog/policy control-plane surface; they must not be smuggled through a route mutation or invalidate active gameplay merely by changing presentation metadata. - Admission-pointer mutation, version-upgrade preparation, and prepared-cutover execution are target-only absent public HTTP/operator capabilities under `/admission-pointers`, `/cutover`, and `/version-upgrades`: they have no public HTTP handlers or Gateway write forwarding. Internal preparation/cutover service and control-plane implementation remains available only behind internal trust boundaries, and there is no current UI control. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index cc9d1d20d4..bb25f64549 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -154,6 +154,8 @@ Game Session control-plane reads are canonical and bounded. The runtime-state re Logging & Admin consumes Game Session directly and has no parallel command, ownership, coordinator, follow-up, or result database. Current REST surfaces are `GET /game-session-pins/{tenantId}/{gameInstanceId}`, `GET /game-session-pins/{tenantId}/{gameInstanceId}/convergence`, `GET /gameplay-commands/{tenantId}/{gameInstanceId}/{commandId}`, `GET /remote-command-coordinators/{tenantId}/{coordinatorId}`, `GET /remote-command-coordinators/{tenantId}`, `GET /remote-followups/{tenantId}/{followupId}`, `GET /remote-followups/{tenantId}`, `GET /remote-followup-results/{tenantId}/{resultId}`, `GET /remote-followup-results/{tenantId}`, and `GET /tick-remediation/status/{tenantId}`. Every route is tenant-guarded; point reads validate tenant and exact id, list reads validate every returned row, invalid enum filters fail closed, and control-plane scope mismatches are rejected. +The live `GET /admission-pointers` list also requires each current pointer to have a latest audit row matching its catalog revision, `realmId`, and playable-state namespace; missing, incomplete, or mismatched evidence returns `AUTHORITY_UNAVAILABLE`, which Logging & Admin exposes as HTTP 503. Historical audit reads remain available and preserve legacy unknown identity fields rather than filling them from the current pointer. Ordinary admission-pointer writes remain closed; the separate audited present-attestation operation and retained-row database proof are unimplemented. See the [Game Session current-pointer guard](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java), [guard proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java), and [Logging & Admin response mapping](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java) with its [focused tests](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java). + Coordinator listing has a bounded REST filter set of origin/target game instance and region, state, follow-up id, command id, and limit. Upstream coordinator, follow-up, and result reads also expose first-class filters across scope and epochs, routing bundle, script/plugin/dispatch provenance, payload/source/queue/claim state, target entity/effect and target-command identity/outcomes, deadlines and late-result policy, script-event identity, and result error/message/outcomes. Rich list hydration is bounded in bulk rather than issuing one point lookup per row. Point and list DTOs preserve linked follow-up, result, target-command, publication, event, source, deadline, and current runtime comparison fields. ### Lifecycle and Feature Authority diff --git a/services/logging-admin-service/src/main/resources/openapi.yaml b/services/logging-admin-service/src/main/resources/openapi.yaml index 6d9d52fb39..3f8624339b 100644 --- a/services/logging-admin-service/src/main/resources/openapi.yaml +++ b/services/logging-admin-service/src/main/resources/openapi.yaml @@ -1670,6 +1670,11 @@ paths: get: summary: List visible gameplay admission pointers operationId: listAdmissionPointers + description: >- + The list is available only when every current pointer has a latest audit + row matching its catalog revision, realm ID, and playable-state namespace. + Missing or incomplete current authority returns 503. Historical audit reads + preserve unknown legacy identity fields. responses: '200': description: Admission pointer list @@ -1686,6 +1691,12 @@ paths: $ref: '#/components/schemas/AdmissionPointerDto' error: $ref: '#/components/schemas/ErrorDetail' + '503': + description: Current admission-pointer authority or matching audit evidence is unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponseError' /admission-pointers/{tenantId}/{worldSlug}/{realmSlug}/audit: get: summary: Read admission-pointer audit history diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java index 80f1ecd48a..482a68e270 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.loggingadmin.controller; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -29,6 +31,8 @@ import org.springframework.http.HttpHeaders; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.server.ResponseStatusException; +import org.yaml.snakeyaml.Yaml; @WebMvcTest(AdmissionPointerController.class) @AutoConfigureMockMvc(addFilters = false) @@ -89,6 +93,47 @@ void listPointersReturnsVisibleEntries() throws Exception { .value("22222222-2222-2222-2222-222222222222")); } + @Test + void listPointersMapsUnavailableCurrentAuthorityToServiceUnavailable() throws Exception { + when(admissionPointerService.listPointers()) + .thenThrow( + new ResponseStatusException( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + "current pointer authority unavailable")); + String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + + mockMvc + .perform(get("/admission-pointers").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.error.code").value("SERVICE_UNAVAILABLE")) + .andExpect(jsonPath("$.error.message").value("current pointer authority unavailable")); + } + + @Test + void openApiDocumentsAdmissionPointerList503Response() throws Exception { + Map document; + try (var input = getClass().getResourceAsStream("/openapi.yaml")) { + assertNotNull(input); + document = new Yaml().load(input); + } + + Map paths = (Map) document.get("paths"); + Map admissionPointers = (Map) paths.get("/admission-pointers"); + Map getOperation = (Map) admissionPointers.get("get"); + Map responses = (Map) getOperation.get("responses"); + Map success = (Map) responses.get("200"); + Map unavailable = (Map) responses.get("503"); + Map successContent = (Map) success.get("content"); + Map unavailableContent = (Map) unavailable.get("content"); + Map successJson = (Map) successContent.get("application/json"); + Map unavailableJson = (Map) unavailableContent.get("application/json"); + Map successSchema = (Map) successJson.get("schema"); + Map unavailableSchema = (Map) unavailableJson.get("schema"); + + assertEquals("#/components/schemas/ApiResponseError", unavailableSchema.get("$ref")); + assertEquals("object", successSchema.get("type")); + } + @Test void auditReturnsEntries() throws Exception { when(admissionPointerService.listPointerAudit(2L, "demo", "production")) From 4847bf2129c16e11f589e0c77c49727404103594 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 02:56:13 +1300 Subject: [PATCH 51/75] Keep unproved admission pointer bootstrap fail closed --- ...e-session-runtime-and-tick-coordination.md | 2 + ...yAdmissionPointerBootstrapInitializer.java | 62 +++----------- ...issionPointerBootstrapInitializerTest.java | 85 +++++-------------- 3 files changed, 35 insertions(+), 114 deletions(-) diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index bb25f64549..3c7dc4c84a 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -156,6 +156,8 @@ Logging & Admin consumes Game Session directly and has no parallel command, owne The live `GET /admission-pointers` list also requires each current pointer to have a latest audit row matching its catalog revision, `realmId`, and playable-state namespace; missing, incomplete, or mismatched evidence returns `AUTHORITY_UNAVAILABLE`, which Logging & Admin exposes as HTTP 503. Historical audit reads remain available and preserve legacy unknown identity fields rather than filling them from the current pointer. Ordinary admission-pointer writes remain closed; the separate audited present-attestation operation and retained-row database proof are unimplemented. See the [Game Session current-pointer guard](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java), [guard proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java), and [Logging & Admin response mapping](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java) with its [focused tests](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java). +When the admission-pointer store is empty, configured seed data is validated but is not published: configuration does not carry owner-validated World `ACTIVE` lifecycle/epoch proof or a fence binding that proof to the pointer and audit commit. Startup logs that admission remains closed. Existing persisted pointers and their read guards are unchanged on restart. Enabling bootstrap publication requires a separately implemented and proved owner-provisioning/fence contract; no later `ACTIVE` observation or restart automatically publishes these seeds. See the [World Lifecycle and Admission Boundary](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary) and [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). + Coordinator listing has a bounded REST filter set of origin/target game instance and region, state, follow-up id, command id, and limit. Upstream coordinator, follow-up, and result reads also expose first-class filters across scope and epochs, routing bundle, script/plugin/dispatch provenance, payload/source/queue/claim state, target entity/effect and target-command identity/outcomes, deadlines and late-result policy, script-event identity, and result error/message/outcomes. Rich list hydration is bounded in bulk rather than issuing one point lookup per row. Point and list DTOs preserve linked follow-up, result, target-command, publication, event, source, deadline, and current runtime comparison fields. ### Lifecycle and Feature Authority diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java index 5862e51591..084cc75155 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java @@ -9,8 +9,8 @@ import lombok.RequiredArgsConstructor; import net.firedevops.firemud.gamesession.config.GameplayAdmissionPointerBootstrapProperties; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; +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; @@ -18,8 +18,8 @@ import org.springframework.transaction.annotation.Transactional; /** - * Bootstraps the persisted gameplay admission-pointer authority from configuration only when the - * authority store is empty and full pointer audit identity is available. + * Validates configured admission-pointer seeds while keeping an empty authority store closed until + * owner-validated World lifecycle proof is available. */ @Component @RequiredArgsConstructor @@ -29,8 +29,10 @@ havingValue = "true", matchIfMissing = true) public class GameplayAdmissionPointerBootstrapInitializer implements ApplicationRunner { + private static final Logger LOGGER = + LoggerFactory.getLogger(GameplayAdmissionPointerBootstrapInitializer.class); + private final GameplayAdmissionPointerRepository pointerRepository; - private final GameplayAdmissionPointerAuthorityService authorityService; private final GameplayAdmissionPointerBootstrapProperties bootstrapProperties; @Override @@ -43,34 +45,9 @@ public void run(ApplicationArguments args) { List pointers = bootstrapProperties.getPointers(); validateSeeds(pointers); - for (GameplayAdmissionPointerBootstrapProperties.PointerSeed pointer : pointers) { - authorityService.upsertPointer( - new GameplayAdmissionPointerMutation( - pointer.getWorldSlug(), - pointer.getWorldDisplayName(), - pointer.getRealmSlug(), - pointer.getRealmDisplayName(), - pointer.getTenantId(), - pointer.getGameInstanceId(), - pointer.isVisible(), - pointer.isPublicProductionRealm(), - pointer.isRequiresCharacterSelection(), - stateScopeName(pointer), - characterCreationPolicyName(pointer), - "system/bootstrap", - "Initial gameplay pointer bootstrap", - "bootstrap:" - + pointer.getTenantId() - + ":" - + pointer.getGameInstanceId() - + ":" - + pointer.getWorldSlug() - + ":" - + pointer.getRealmSlug(), - 0L, - 0L, - null)); - } + LOGGER.warn( + "Skipping configured gameplay admission pointer bootstrap because owner-validated " + + "World ACTIVE lifecycle and epoch proof is unavailable; admission remains closed"); } private static void validateSeeds( @@ -138,23 +115,4 @@ private static IllegalArgumentException invalidSeed(int index, String reason) { return new IllegalArgumentException( "Invalid gameplay admission pointer bootstrap seed at index " + index + ": " + reason); } - - private static String stateScopeName( - GameplayAdmissionPointerBootstrapProperties.PointerSeed pointer) { - GameplayAdmissionPointerBootstrapProperties.StateScope stateScope = pointer.getStateScope(); - return (stateScope != null - ? stateScope - : GameplayAdmissionPointerBootstrapProperties.StateScope.SHARED) - .name(); - } - - private static String characterCreationPolicyName( - GameplayAdmissionPointerBootstrapProperties.PointerSeed pointer) { - GameplayAdmissionPointerBootstrapProperties.CharacterCreationPolicy policy = - pointer.getCharacterCreationPolicy(); - return (policy != null - ? policy - : GameplayAdmissionPointerBootstrapProperties.CharacterCreationPolicy.ALLOW_NEW) - .name(); - } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index 857a551a19..e2c9b3f124 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -5,19 +5,16 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.List; import net.firedevops.firemud.gamesession.config.GameplayAdmissionPointerBootstrapProperties; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -27,7 +24,6 @@ @ExtendWith(MockitoExtension.class) class GameplayAdmissionPointerBootstrapInitializerTest { @Mock private GameplayAdmissionPointerRepository pointerRepository; - @Mock private GameplayAdmissionPointerAuthorityService authorityService; private GameplayAdmissionPointerBootstrapProperties properties; private GameplayAdmissionPointerBootstrapInitializer initializer; @@ -35,41 +31,19 @@ class GameplayAdmissionPointerBootstrapInitializerTest { @BeforeEach void setUp() { properties = new GameplayAdmissionPointerBootstrapProperties(); - initializer = - new GameplayAdmissionPointerBootstrapInitializer( - pointerRepository, authorityService, properties); + initializer = new GameplayAdmissionPointerBootstrapInitializer(pointerRepository, properties); } @Test - void runSeedsBootstrapPointersWhenAuthorityStoreIsEmpty() throws Exception { + void runKeepsAdmissionClosedForValidDefaultSeedsWhenAuthorityStoreIsEmpty() throws Exception { when(pointerRepository.count()).thenReturn(0L); initializer.run(new DefaultApplicationArguments(new String[] {})); - ArgumentCaptor mutationCaptor = - ArgumentCaptor.forClass(GameplayAdmissionPointerMutation.class); - verify(authorityService, org.mockito.Mockito.times(2)).upsertPointer(mutationCaptor.capture()); InOrder bootstrapOrder = inOrder(pointerRepository); bootstrapOrder.verify(pointerRepository).lockForBootstrap(); bootstrapOrder.verify(pointerRepository).count(); - List mutations = mutationCaptor.getAllValues(); - assertEquals(2, mutations.size()); - assertEquals("demo", mutations.get(0).worldSlug()); - assertEquals("Demo World", mutations.get(0).worldDisplayName()); - assertEquals("production", mutations.get(0).realmSlug()); - assertEquals("Live Realm", mutations.get(0).realmDisplayName()); - assertEquals(1L, mutations.get(0).tenantId()); - assertEquals(1L, mutations.get(0).gameInstanceId()); - assertEquals("SHARED", mutations.get(0).stateScope()); - assertEquals("ALLOW_NEW", mutations.get(0).characterCreationPolicy()); - assertEquals("system/bootstrap", mutations.get(0).actorPrincipal()); - assertEquals("Initial gameplay pointer bootstrap", mutations.get(0).reason()); - assertEquals("bootstrap:1:1:demo:production", mutations.get(0).controlPlaneRequestId()); - assertEquals(0L, mutations.get(0).expectedPointerVersion()); - assertEquals(0L, mutations.get(0).expectedCatalogRevision()); - assertEquals("sandbox", mutations.get(1).worldSlug()); - assertTrue(mutations.get(1).requiresCharacterSelection()); - assertFalse(mutations.get(1).publicProductionRealm()); + verifyNoMoreInteractions(pointerRepository); } @Test @@ -87,13 +61,14 @@ void defaultEffectiveBootstrapSeedsHaveOneVisiblePublicProductionRealmPerTenant( } @Test - void runSkipsSeedMutationsOnRestartWhenAuthorityStoreAlreadyHasPointers() throws Exception { + void runPreservesExistingPointerAuthorityOnRestart() throws Exception { when(pointerRepository.count()).thenReturn(3L); initializer.run(new DefaultApplicationArguments(new String[] {})); - verify(authorityService, never()).upsertPointer(org.mockito.ArgumentMatchers.any()); + verify(pointerRepository).lockForBootstrap(); verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); } @Test @@ -110,8 +85,9 @@ void runRejectsMalformedBootstrapPointerSeedsBeforeAnyMutation() throws Exceptio assertThrows( IllegalArgumentException.class, () -> initializer.run(new DefaultApplicationArguments(new String[] {}))); - - verify(authorityService, never()).upsertPointer(org.mockito.ArgumentMatchers.any()); + verify(pointerRepository).lockForBootstrap(); + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); } @Test @@ -126,8 +102,9 @@ void runRejectsMultipleVisiblePublicProductionSeedsForTenantBeforeAnyMutation() assertThrows( IllegalArgumentException.class, () -> initializer.run(new DefaultApplicationArguments(new String[] {}))); - - verify(authorityService, never()).upsertPointer(org.mockito.ArgumentMatchers.any()); + verify(pointerRepository).lockForBootstrap(); + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); } @Test @@ -141,8 +118,9 @@ void runRejectsNoVisiblePublicProductionSeedForTenantBeforeAnyMutation() throws assertThrows( IllegalArgumentException.class, () -> initializer.run(new DefaultApplicationArguments(new String[] {}))); - - verify(authorityService, never()).upsertPointer(org.mockito.ArgumentMatchers.any()); + verify(pointerRepository).lockForBootstrap(); + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); } @Test @@ -156,12 +134,13 @@ void runRejectsDuplicateWorldRealmSeedsBeforeAnyMutation() throws Exception { assertThrows( IllegalArgumentException.class, () -> initializer.run(new DefaultApplicationArguments(new String[] {}))); - - verify(authorityService, never()).upsertPointer(org.mockito.ArgumentMatchers.any()); + verify(pointerRepository).lockForBootstrap(); + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); } @Test - void runAllowsSameWorldRealmSelectorInDifferentTenants() throws Exception { + void runKeepsAdmissionClosedForValidSeedsAcrossTenants() throws Exception { when(pointerRepository.count()).thenReturn(0L); properties.setPointers( List.of( @@ -169,27 +148,9 @@ void runAllowsSameWorldRealmSelectorInDifferentTenants() throws Exception { pointerSeed("demo", "Other Demo", "production", "Live Realm", 2L, 1L, false))); initializer.run(new DefaultApplicationArguments(new String[] {})); - - verify(authorityService, org.mockito.Mockito.times(2)) - .upsertPointer(org.mockito.ArgumentMatchers.any()); - } - - @Test - void runDefaultsNullEnumFieldsDuringBootstrapMutation() throws Exception { - when(pointerRepository.count()).thenReturn(0L); - GameplayAdmissionPointerBootstrapProperties.PointerSeed pointer = - pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, false); - pointer.setStateScope(null); - pointer.setCharacterCreationPolicy(null); - properties.setPointers(List.of(pointer)); - - initializer.run(new DefaultApplicationArguments(new String[] {})); - - ArgumentCaptor mutationCaptor = - ArgumentCaptor.forClass(GameplayAdmissionPointerMutation.class); - verify(authorityService).upsertPointer(mutationCaptor.capture()); - assertEquals("SHARED", mutationCaptor.getValue().stateScope()); - assertEquals("ALLOW_NEW", mutationCaptor.getValue().characterCreationPolicy()); + verify(pointerRepository).lockForBootstrap(); + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); } @Test From c1223c3fd87946ac0f37ff524789eed7a8259289 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 03:34:33 +1300 Subject: [PATCH 52/75] Authorize scoped admission pointer reads before audit validation --- .../logging-admin-service/api-contracts.md | 2 +- design/grpc-docs/grpc-api.md | 5 + ...e-session-runtime-and-tick-coordination.md | 2 +- .../v1/game_session_service.proto | 6 +- ...onAdmissionPointerControlPlaneService.java | 11 +- .../GameSessionControlPlaneGrpcService.java | 30 ++- ...missionPointerControlPlaneServiceTest.java | 79 ++++++- ...ameSessionControlPlaneGrpcServiceTest.java | 203 ++++++++++++++++++ .../client/GameSessionControlPlaneClient.java | 7 +- .../impl/AdmissionPointerServiceImpl.java | 29 ++- .../src/main/resources/openapi.yaml | 10 +- .../impl/AdmissionPointerServiceImplTest.java | 39 +++- 12 files changed, 404 insertions(+), 19 deletions(-) diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index eb9cb06238..ab41e485c9 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -24,7 +24,7 @@ Routine rollback is expected to leave ordinary gameplay available while scoped A ## Implementation Status -- Feature-flag toggles and scoped tick-remediation pause/resume ingress routes now hard fail closed as unavailable operator mutations until the minimum three-part schema/authorization gate exists: their action-family schemas, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus redemption by the receiving authoritative owner. This minimum gate is necessary but not sufficient for live-success support; supported execution also requires the complete durable, idempotent, fenced owner-mutation contract in [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md), including durable intent/audit, stable digest-bound request identity, authoritative-owner state, safety/recovery gates, and durable acknowledgement. The HTTP entrypoints preserve authentication, authorization, and basic request validation, then return `503 Service Unavailable` with stable action-specific unavailable error codes (`FEATURE_FLAG_TOGGLE_UNAVAILABLE` or `TICK_REMEDIATION_UNAVAILABLE`) without invoking a service, owner, or audit dependency. The internal `ToggleFeatureFlag` gRPC entrypoint preserves admin-role, positive-tenant, and feature-name validation, then returns an application-level `UNAVAILABLE` error without dispatch. No Logging & Admin feature-flag or tick forwarding method remains callable internally. Admission-pointer reads, audit, and prepared-upgrade proof reads remain live; the current-pointer list is available only with exact latest-audit identity/catalog evidence and returns `503` when that authority is unavailable. Public POST/operator mutation routes under `/admission-pointers`, `/cutover`, or `/version-upgrades` are target-only absent: no public HTTP handlers or Gateway write forwarding exist. Internal preparation/cutover service and control-plane implementation remains behind internal trust boundaries, and there is no current UI control. +- Feature-flag toggles and scoped tick-remediation pause/resume ingress routes now hard fail closed as unavailable operator mutations until the minimum three-part schema/authorization gate exists: their action-family schemas, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus redemption by the receiving authoritative owner. This minimum gate is necessary but not sufficient for live-success support; supported execution also requires the complete durable, idempotent, fenced owner-mutation contract in [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md), including durable intent/audit, stable digest-bound request identity, authoritative-owner state, safety/recovery gates, and durable acknowledgement. The HTTP entrypoints preserve authentication, authorization, and basic request validation, then return `503 Service Unavailable` with stable action-specific unavailable error codes (`FEATURE_FLAG_TOGGLE_UNAVAILABLE` or `TICK_REMEDIATION_UNAVAILABLE`) without invoking a service, owner, or audit dependency. The internal `ToggleFeatureFlag` gRPC entrypoint preserves admin-role, positive-tenant, and feature-name validation, then returns an application-level `UNAVAILABLE` error without dispatch. No Logging & Admin feature-flag or tick forwarding method remains callable internally. Admission-pointer reads, audit, and prepared-upgrade proof reads remain live. The current-pointer list forwards only the caller's authorized tenant scopes; an empty owner request remains reserved for global platform administrators and moderators. Each current pointer in the selected scope requires exact latest-audit identity/catalog evidence, and unavailable authority in that scope returns `503`. Public POST/operator mutation routes under `/admission-pointers`, `/cutover`, or `/version-upgrades` are target-only absent: no public HTTP handlers or Gateway write forwarding exist. Internal preparation/cutover service and control-plane implementation remains behind internal trust boundaries, and there is no current UI control. - Availability vocabulary is explicit: **implemented-but-externally-gated** means an executable public controller/owner path exists but the shared mutation gate is incomplete; **target-only absent** means no executable public route exists. Admission-pointer mutation, version-upgrade preparation, and prepared cutover use the latter classification at public HTTP ingress even though internal preparation/cutover implementation remains. Quota-override ingress is also target-only absent. No generic tick-remediation payload or reserved `remediate` route is part of the target; each future recovery operation requires a named typed contract implemented by its authoritative workflow owner. - No forwarded owner mutation is currently supported as a live Logging & Admin capability until its minimum schema/authorization gate and the complete durable, idempotent, fenced owner-execution contract in [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) are implemented and proved. The service-local `POST /moderation/actions` endpoint and `ApplyModerationAction` gRPC path now hard fail closed after their narrow tenant/admin checks: HTTP returns `503 Service Unavailable`, gRPC returns an application-level `UNAVAILABLE` error, and neither path dispatches or persists the generic legacy `moderation_actions` row. They remain unsupported, nonconformant implementation drift and must not be wired or called as available mutations; separate fixed-category policy/audit evidence and owner enforcement state are absent, and they are not Gateway-forwarded or supported at external ingress. In the target local workflow, once its applicable schema/authorization and local durable intent/audit requirements are implemented, Logging & Admin records durable intent/case/audit evidence and redeems its one Account reference exactly once; it never forwards that reference or performs owner enforcement. A future typed owner-enforcement command uses a separately issued reference redeemed by its receiving owner. Game Session and Social & Groups synchronously consume the live `EvaluateModerationPolicy` read at the `GAMEPLAY_ADMISSION` and `CHAT_SEND` enforcement boundaries, but that evaluation does not make the legacy action route live. Fixed-category owner commands, monotonic owner state, bounded appeals, and broader policy coverage are not implemented. Existing Game Session `/sessions*` lifecycle routes are current owner-local hooks, not a complete external Logging & Admin route family. Separate current read and investigation surfaces include the PostgreSQL-backed log query, saga reads, metrics, and owner/control-plane reads; profile-aware indexed or console/journal query integration and embedded dashboard endpoints remain target-only and unimplemented. - Current `POST /logs/query` and `QueryLogs` read only the service-owned PostgreSQL `log_events` table. They require an exact tenant and apply case-insensitive containment to the stored message, returning the matching messages. They do not query deployed structured logs, mirror data to Elasticsearch, prove the ADR 0162 emitter-to-query path, implement a compatible indexed or console/journal profile, or expose Kibana/Grafana embedding. diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index fd75119096..da688e81e1 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -8090,6 +8090,11 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_ids | [int64](#int64) | repeated | Empty requires a global privileged caller for the all-tenant read. Non-empty IDs must be positive and individually authorized by the forwarded caller context. | + + diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 3c7dc4c84a..3b54fd13ba 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -154,7 +154,7 @@ Game Session control-plane reads are canonical and bounded. The runtime-state re Logging & Admin consumes Game Session directly and has no parallel command, ownership, coordinator, follow-up, or result database. Current REST surfaces are `GET /game-session-pins/{tenantId}/{gameInstanceId}`, `GET /game-session-pins/{tenantId}/{gameInstanceId}/convergence`, `GET /gameplay-commands/{tenantId}/{gameInstanceId}/{commandId}`, `GET /remote-command-coordinators/{tenantId}/{coordinatorId}`, `GET /remote-command-coordinators/{tenantId}`, `GET /remote-followups/{tenantId}/{followupId}`, `GET /remote-followups/{tenantId}`, `GET /remote-followup-results/{tenantId}/{resultId}`, `GET /remote-followup-results/{tenantId}`, and `GET /tick-remediation/status/{tenantId}`. Every route is tenant-guarded; point reads validate tenant and exact id, list reads validate every returned row, invalid enum filters fail closed, and control-plane scope mismatches are rejected. -The live `GET /admission-pointers` list also requires each current pointer to have a latest audit row matching its catalog revision, `realmId`, and playable-state namespace; missing, incomplete, or mismatched evidence returns `AUTHORITY_UNAVAILABLE`, which Logging & Admin exposes as HTTP 503. Historical audit reads remain available and preserve legacy unknown identity fields rather than filling them from the current pointer. Ordinary admission-pointer writes remain closed; the separate audited present-attestation operation and retained-row database proof are unimplemented. See the [Game Session current-pointer guard](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java), [guard proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java), and [Logging & Admin response mapping](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java) with its [focused tests](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java). +The live `GET /admission-pointers` list now forwards only the caller's authorized positive tenant scopes through the Game Session RPC. Scoped callers cannot send an empty scope; an empty `tenant_ids` request preserves the global platform-admin/moderator all-tenant read. Game Session validates every requested tenant before reading, filters current pointers before audit lookups, and denies unauthorized or missing caller context before authority access. Missing, incomplete, or mismatched latest audit evidence for a pointer within the selected scope returns `AUTHORITY_UNAVAILABLE`, which Logging & Admin exposes as HTTP 503. Historical audit reads remain available and preserve legacy unknown identity fields rather than filling them from the current pointer. Ordinary admission-pointer writes remain closed; the separate audited present-attestation operation and retained-row database proof are unimplemented. See the [Game Session current-pointer guard](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java), [guard proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java), and [Logging & Admin response mapping](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java) with its [focused tests](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java). When the admission-pointer store is empty, configured seed data is validated but is not published: configuration does not carry owner-validated World `ACTIVE` lifecycle/epoch proof or a fence binding that proof to the pointer and audit commit. Startup logs that admission remains closed. Existing persisted pointers and their read guards are unchanged on restart. Enabling bootstrap publication requires a separately implemented and proved owner-provisioning/fence contract; no later `ACTIVE` observation or restart automatically publishes these seeds. See the [World Lifecycle and Admission Boundary](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary) and [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index b745ca1c13..34805ae962 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -423,7 +423,11 @@ message AdmissionPointerControlPlaneEntry { string playable_state_namespace_id = 20; } -message ListAdmissionPointersRequest {} +message ListAdmissionPointersRequest { + // Empty requires a global privileged caller for the all-tenant read. + // Non-empty IDs must be positive and individually authorized by the forwarded caller context. + repeated int64 tenant_ids = 1; +} message ListAdmissionPointersResponse { repeated AdmissionPointerControlPlaneEntry pointers = 1; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java index 2d8be97cd4..334e757a84 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java @@ -1,6 +1,8 @@ package net.firedevops.firemud.gamesession.service.impl; +import java.util.List; import java.util.Objects; +import java.util.Set; import net.firedevops.firemud.gamesession.dto.PreparedVersionUpgradeDto; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; @@ -35,9 +37,12 @@ final class GameSessionAdmissionPointerControlPlaneService { this.versionUpgradePreparationService = versionUpgradePreparationService; } - ListAdmissionPointersResponse listAdmissionPointers() { - java.util.List - pointers = gameplayAdmissionPointerAuthorityService.listPointers(); + ListAdmissionPointersResponse listAdmissionPointers(List requestedTenantIds) { + Set tenantScope = Set.copyOf(requestedTenantIds); + List pointers = + gameplayAdmissionPointerAuthorityService.listPointers().stream() + .filter(pointer -> tenantScope.isEmpty() || tenantScope.contains(pointer.tenantId())) + .toList(); java.util.List entries = pointers.stream() .map( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java index 089849a521..787b590481 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java @@ -4,6 +4,7 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.util.List; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; @@ -162,8 +163,8 @@ public void listAdmissionPointers( ListAdmissionPointersRequest request, StreamObserver responseObserver) { try { - requireAdminRole(); - responseObserver.onNext(admissionPointerControlPlaneService.listAdmissionPointers()); + List tenantIds = validateAdmissionPointerListScope(request.getTenantIdsList()); + responseObserver.onNext(admissionPointerControlPlaneService.listAdmissionPointers(tenantIds)); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { ListAdmissionPointersResponse response = @@ -172,6 +173,13 @@ public void listAdmissionPointers( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (IllegalArgumentException ex) { + ListAdmissionPointersResponse response = + ListAdmissionPointersResponse.newBuilder() + .setError(invalidArgumentError("ListAdmissionPointers", ex)) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (AdmissionPointerAuditUnavailableException ex) { logger.warn("ListAdmissionPointers authority unavailable", ex); ListAdmissionPointersResponse response = @@ -197,6 +205,24 @@ public void listAdmissionPointers( } } + private List validateAdmissionPointerListScope(List tenantIds) { + if (tenantIds.isEmpty()) { + requireAdminRole(); + return List.of(); + } + + List validatedTenantIds = + tenantIds.stream() + .map(tenantId -> ControlPlaneRequestParser.requirePositive(tenantId, "tenant_ids")) + .toList(); + for (long tenantId : validatedTenantIds) { + if (!SessionContext.hasTenantAccess(tenantId)) { + throw new AdminAuthorizationException("Tenant access required for admission pointer list"); + } + } + return validatedTenantIds; + } + @Override @Timed(value = "gamesessionGrpc.controlPlane.listAdmissionPointerAudit") public void listAdmissionPointerAudit( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java index 3a2a01ac26..cd5f464f0a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java @@ -1,9 +1,13 @@ package net.firedevops.firemud.gamesession.service.impl; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.List; import java.util.UUID; @@ -12,10 +16,36 @@ import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.VersionUpgradePreparationService; import org.junit.jupiter.api.Test; class GameSessionAdmissionPointerControlPlaneServiceTest { + @Test + void listFiltersTenantScopeBeforeCheckingAuditHistory() { + GameplayAdmissionPointerAuthorityService authorityService = + mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot tenantA = pointer(1L, "tenant-a"); + GameplayAdmissionPointerSnapshot tenantB = pointer(2L, "tenant-b"); + when(authorityService.listPointers()).thenReturn(List.of(tenantA, tenantB)); + when(authorityService.listPointerAudit(2L, "tenant-b", "production")) + .thenReturn(List.of(audit(tenantB))); + GameSessionAdmissionPointerControlPlaneService controlPlaneService = + new GameSessionAdmissionPointerControlPlaneService( + mock(GameInstanceRepository.class), + authorityService, + mock(VersionUpgradePreparationService.class)); + + var response = controlPlaneService.listAdmissionPointers(List.of(2L)); + + assertEquals(1, response.getPointersCount()); + assertEquals("2", response.getPointers(0).getTenantId()); + verify(authorityService).listPointerAudit(2L, "tenant-b", "production"); + verify(authorityService, never()).listPointerAudit(1L, "tenant-a", "production"); + } + @Test void listRejectsRetainedPreV7AuditWithUnknownRevisionAndIdentity() { GameplayAdmissionPointerRepository pointerRepository = @@ -77,6 +107,53 @@ void listRejectsRetainedPreV7AuditWithUnknownRevisionAndIdentity() { assertThrows( AdmissionPointerAuditUnavailableException.class, - controlPlaneService::listAdmissionPointers); + () -> controlPlaneService.listAdmissionPointers(List.of())); + } + + private static GameplayAdmissionPointerSnapshot pointer(long tenantId, String worldSlug) { + UUID realmId = UUID.nameUUIDFromBytes(("realm-" + tenantId).getBytes(StandardCharsets.UTF_8)); + UUID namespaceId = + UUID.nameUUIDFromBytes(("namespace-" + tenantId).getBytes(StandardCharsets.UTF_8)); + return new GameplayAdmissionPointerSnapshot( + worldSlug, + "Tenant World", + "production", + "Live Realm", + tenantId, + tenantId + 10L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 6L, + realmId, + namespaceId); + } + + private static GameplayAdmissionPointerAuditEntry audit( + GameplayAdmissionPointerSnapshot pointer) { + return new GameplayAdmissionPointerAuditEntry( + pointer.worldSlug(), + pointer.realmSlug(), + pointer.worldDisplayName(), + pointer.realmDisplayName(), + pointer.tenantId(), + pointer.gameInstanceId(), + pointer.pointerVersion(), + pointer.catalogRevision(), + pointer.realmId(), + pointer.playableStateNamespaceId(), + pointer.visible(), + pointer.publicProductionRealm(), + pointer.requiresCharacterSelection(), + pointer.stateScope(), + pointer.characterCreationPolicy(), + "tester", + "test audit", + "request-" + pointer.tenantId(), + null, + Instant.parse("2026-09-29T00:00:00Z")); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 772f371d57..a1477da477 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -1751,6 +1751,151 @@ public void onNext(ListAdmissionPointersResponse value) { assertEquals("PERMISSION_DENIED", responseRef.get().getError().getCode()); } + @Test + void listAdmissionPointersAllowsScopedCallerOnlyForRequestedTenantBeforeAuditValidation() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot inaccessiblePointer = scopedAdmissionPointer(1L, "tenant-a"); + GameplayAdmissionPointerSnapshot requestedPointer = scopedAdmissionPointer(2L, "tenant-b"); + Mockito.when(authorityService.listPointers()) + .thenReturn(List.of(inaccessiblePointer, requestedPointer)); + Mockito.when(authorityService.listPointerAudit(2L, "tenant-b", "production")) + .thenReturn(List.of(scopedAdmissionPointerAudit(requestedPointer))); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + + AtomicReference responseRef = new AtomicReference<>(); + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds(2L).build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("", responseRef.get().getError().getCode()); + assertEquals(1, responseRef.get().getPointersCount()); + assertEquals("2", responseRef.get().getPointers(0).getTenantId()); + Mockito.verify(authorityService).listPointerAudit(2L, "tenant-b", "production"); + Mockito.verify(authorityService, Mockito.never()) + .listPointerAudit(1L, "tenant-a", "production"); + } + + @Test + void listAdmissionPointersRejectsScopedCallerRequestingAnotherTenant() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("moderator"))); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds(1L).build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("PERMISSION_DENIED", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + } + + @Test + void listAdmissionPointersRejectsScopedCallerUsingEmptyAllTenantRequest() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.getDefaultInstance(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("PERMISSION_DENIED", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + } + + @Test + void listAdmissionPointersRejectsMissingCallerContext() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds(2L).build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("PERMISSION_DENIED", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + } + + @Test + void listAdmissionPointersRejectsNonPositiveTenantScopeBeforeAuthorityLookup() { + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds(0L).build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("INVALID_ARGUMENT", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + } + + @Test + void listAdmissionPointersFailsClosedForMissingAuditInRequestedTenant() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot requestedPointer = scopedAdmissionPointer(2L, "tenant-b"); + Mockito.when(authorityService.listPointers()).thenReturn(List.of(requestedPointer)); + Mockito.when(authorityService.listPointerAudit(2L, "tenant-b", "production")) + .thenReturn(List.of()); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds(2L).build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); + assertEquals(0, responseRef.get().getPointersCount()); + } + @Test void listAdmissionPointersFailsClosedWhenCurrentPointerHasNoAuditHistory() { GameplayAdmissionPointerAuthorityService authorityService = @@ -9887,6 +10032,64 @@ private static GameSessionControlPlaneGrpcService remoteControlPlaneService( new GameSessionProperties()); } + private static GameSessionControlPlaneGrpcService admissionPointerControlPlaneService( + GameplayAdmissionPointerAuthorityService authorityService) { + return controlPlaneService( + Mockito.mock(GameInstanceRepository.class), + Mockito.mock(GameplayCommandRepository.class), + Mockito.mock(RuntimeRegionStatusRepository.class), + authorityService, + Mockito.mock(InstanceCutoverCompatibilityService.class), + Mockito.mock(VersionUpgradePreparationService.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + } + + private static GameplayAdmissionPointerSnapshot scopedAdmissionPointer( + long tenantId, String worldSlug) { + return new GameplayAdmissionPointerSnapshot( + worldSlug, + "Tenant World", + "production", + "Live Realm", + tenantId, + tenantId + 10L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 6L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")); + } + + private static GameplayAdmissionPointerAuditEntry scopedAdmissionPointerAudit( + GameplayAdmissionPointerSnapshot pointer) { + return new GameplayAdmissionPointerAuditEntry( + pointer.worldSlug(), + pointer.realmSlug(), + pointer.worldDisplayName(), + pointer.realmDisplayName(), + pointer.tenantId(), + pointer.gameInstanceId(), + pointer.pointerVersion(), + pointer.catalogRevision(), + pointer.realmId(), + pointer.playableStateNamespaceId(), + pointer.visible(), + pointer.publicProductionRealm(), + pointer.requiresCharacterSelection(), + pointer.stateScope(), + pointer.characterCreationPolicy(), + "tester", + "test audit", + "request-" + pointer.tenantId(), + null, + Instant.parse("2026-09-29T00:00:00Z")); + } + private static GameInstance runningGameInstance() { GameInstance instance = new GameInstance(); instance.setStatus("RUNNING"); diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClient.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClient.java index 0cd3158367..179f8f25c9 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClient.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClient.java @@ -2,6 +2,7 @@ import jakarta.annotation.PostConstruct; import java.io.IOException; +import java.util.List; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; @@ -83,8 +84,10 @@ protected GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlock GameSessionControlPlaneServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - public ListAdmissionPointersResponse listAdmissionPointers() { - return stub().listAdmissionPointers(ListAdmissionPointersRequest.getDefaultInstance()); + public ListAdmissionPointersResponse listAdmissionPointers(List tenantIds) { + return stub() + .listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addAllTenantIds(tenantIds).build()); } public ListAdmissionPointerAuditResponse listAdmissionPointerAudit( diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java index 2f95e85ce7..a20b795eca 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java @@ -4,6 +4,7 @@ import io.micrometer.core.annotation.Timed; import java.time.Instant; import java.util.List; +import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.security.SessionContext; @@ -49,7 +50,14 @@ public AdmissionPointerServiceImpl(GameSessionControlPlaneClient gameSessionCont @Override @Timed(value = "loggingadmin.admissionPointer.list") public List listPointers() { - ListAdmissionPointersResponse response = gameSessionControlPlaneClient.listAdmissionPointers(); + boolean globalRead = SessionContext.hasGlobalPrivilegedRole(); + List tenantIds = globalRead ? List.of() : accessibleTenantIds(); + if (!globalRead && tenantIds.isEmpty()) { + return List.of(); + } + + ListAdmissionPointersResponse response = + gameSessionControlPlaneClient.listAdmissionPointers(tenantIds); requireNoError(response.getError()); return response.getPointersList().stream() .filter(this::hasTenantAccess) @@ -242,6 +250,25 @@ private boolean hasTenantAccess(AdmissionPointerControlPlaneEntry entry) { return SessionContext.hasTenantAccess(parseLong(entry.getTenantId(), "tenant_id")); } + private List accessibleTenantIds() { + return SessionContext.getScopedRolesMap().keySet().stream() + .map(this::parsePositiveCanonicalTenantId) + .filter(Objects::nonNull) + .filter(SessionContext::hasTenantAccess) + .distinct() + .sorted() + .toList(); + } + + private Long parsePositiveCanonicalTenantId(String value) { + try { + long tenantId = Long.parseLong(value); + return tenantId > 0L && Long.toString(tenantId).equals(value) ? tenantId : null; + } catch (NumberFormatException ex) { + return null; + } + } + private AdmissionPointerDto toDto(AdmissionPointerControlPlaneEntry entry) { return new AdmissionPointerDto( entry.getWorldSlug(), diff --git a/services/logging-admin-service/src/main/resources/openapi.yaml b/services/logging-admin-service/src/main/resources/openapi.yaml index 3f8624339b..d92cd9184e 100644 --- a/services/logging-admin-service/src/main/resources/openapi.yaml +++ b/services/logging-admin-service/src/main/resources/openapi.yaml @@ -1671,10 +1671,12 @@ paths: summary: List visible gameplay admission pointers operationId: listAdmissionPointers description: >- - The list is available only when every current pointer has a latest audit - row matching its catalog revision, realm ID, and playable-state namespace. - Missing or incomplete current authority returns 503. Historical audit reads - preserve unknown legacy identity fields. + Tenant-scoped callers receive pointers only for their authorized tenant + scopes. Global platform administrators and moderators receive the + all-tenant list. Each current pointer in the selected scope must have a + latest audit row matching its catalog revision, realm ID, and playable-state + namespace. Missing or incomplete current authority in that scope returns + 503. Historical audit reads preserve unknown legacy identity fields. responses: '200': description: Admission pointer list diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java index c8c7cfe557..c42733f088 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java @@ -60,8 +60,15 @@ void clear() { @Test void listPointersFiltersToAccessibleTenant() { - SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); - when(gameSessionControlPlaneClient.listAdmissionPointers()) + SessionContext.setContext( + "7", + List.of(), + Map.of( + "2", List.of("tenantAdmin"), + "02", List.of("tenantAdmin"), + "0", List.of("tenantAdmin"), + "-3", List.of("moderator"))); + when(gameSessionControlPlaneClient.listAdmissionPointers(List.of(2L))) .thenReturn( ListAdmissionPointersResponse.newBuilder() .addPointers(pointerEntry("demo", "production", 2L, 7L, 3L)) @@ -73,11 +80,37 @@ void listPointersFiltersToAccessibleTenant() { assertEquals(1, result.size()); assertEquals("demo", result.get(0).worldSlug()); assertEquals(2L, result.get(0).tenantId()); + verify(gameSessionControlPlaneClient).listAdmissionPointers(List.of(2L)); + } + + @Test + void listPointersReturnsEmptyWithoutDispatchWhenNoAccessibleTenantScopeExists() { + List result = service.listPointers(); + + assertEquals(List.of(), result); + verifyNoInteractions(gameSessionControlPlaneClient); + } + + @Test + void globalListPointersUsesAllTenantRequest() { + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + when(gameSessionControlPlaneClient.listAdmissionPointers(List.of())) + .thenReturn( + ListAdmissionPointersResponse.newBuilder() + .addPointers(pointerEntry("demo", "production", 2L, 7L, 3L)) + .addPointers(pointerEntry("sandbox", "preview", 8L, 11L, 1L)) + .build()); + + List result = service.listPointers(); + + assertEquals(2, result.size()); + verify(gameSessionControlPlaneClient).listAdmissionPointers(List.of()); } @Test void listPointersMapsUnavailableAuthorityToServiceUnavailable() { - when(gameSessionControlPlaneClient.listAdmissionPointers()) + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + when(gameSessionControlPlaneClient.listAdmissionPointers(List.of())) .thenReturn( ListAdmissionPointersResponse.newBuilder() .setError( From 58b641341c4edfe8ab59e49d9781f64b4095eaf5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:18:28 +1300 Subject: [PATCH 53/75] Correct admission fixture and runtime-state availability contract --- ...essionWebSocketHandlerIntegrationTest.java | 8 ++++- .../src/main/resources/openapi.yaml | 6 ++++ .../AdmissionPointerControllerTest.java | 36 +++++++++++-------- 3 files changed, 34 insertions(+), 16 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 2e83f690bd..88a4c07cf4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -1671,7 +1671,7 @@ private void resetAdmissionPointers() { 22L, 2L, true, - true, + false, true, "SHARED", "ALLOW_NEW", @@ -1681,6 +1681,12 @@ private void resetAdmissionPointers() { 0L, 0L, null)); + assertThat(gameplayAdmissionPointerAuthorityService.listPointers()) + .filteredOn( + pointer -> + pointer.tenantId() == 22L && pointer.visible() && pointer.publicProductionRealm()) + .extracting(GameplayAdmissionPointerSnapshot::worldSlug) + .containsExactly("demo"); } private static JsonNode json(String payload) { diff --git a/services/logging-admin-service/src/main/resources/openapi.yaml b/services/logging-admin-service/src/main/resources/openapi.yaml index d92cd9184e..1c2db29a1e 100644 --- a/services/logging-admin-service/src/main/resources/openapi.yaml +++ b/services/logging-admin-service/src/main/resources/openapi.yaml @@ -1767,6 +1767,12 @@ paths: $ref: '#/components/schemas/GameInstanceRuntimeStateDto' error: $ref: '#/components/schemas/ErrorDetail' + '503': + description: Current admission-pointer authority or required pointer identity is unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponseError' /admission-pointers/version-upgrades/{tenantId}/{preparationId}: get: summary: Read a prepared version-upgrade proof (live read) diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java index 482a68e270..aaaa69cb51 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java @@ -110,7 +110,7 @@ void listPointersMapsUnavailableCurrentAuthorityToServiceUnavailable() throws Ex } @Test - void openApiDocumentsAdmissionPointerList503Response() throws Exception { + void openApiDocumentsAdmissionPointerRead503Responses() throws Exception { Map document; try (var input = getClass().getResourceAsStream("/openapi.yaml")) { assertNotNull(input); @@ -118,20 +118,26 @@ void openApiDocumentsAdmissionPointerList503Response() throws Exception { } Map paths = (Map) document.get("paths"); - Map admissionPointers = (Map) paths.get("/admission-pointers"); - Map getOperation = (Map) admissionPointers.get("get"); - Map responses = (Map) getOperation.get("responses"); - Map success = (Map) responses.get("200"); - Map unavailable = (Map) responses.get("503"); - Map successContent = (Map) success.get("content"); - Map unavailableContent = (Map) unavailable.get("content"); - Map successJson = (Map) successContent.get("application/json"); - Map unavailableJson = (Map) unavailableContent.get("application/json"); - Map successSchema = (Map) successJson.get("schema"); - Map unavailableSchema = (Map) unavailableJson.get("schema"); - - assertEquals("#/components/schemas/ApiResponseError", unavailableSchema.get("$ref")); - assertEquals("object", successSchema.get("type")); + for (String path : + List.of( + "/admission-pointers", + "/admission-pointers/runtime-state/{tenantId}/{gameInstanceId}")) { + Map admissionPointers = (Map) paths.get(path); + Map getOperation = (Map) admissionPointers.get("get"); + Map responses = (Map) getOperation.get("responses"); + Map success = (Map) responses.get("200"); + Map unavailable = (Map) responses.get("503"); + assertNotNull(unavailable, path + " must document the unavailable response"); + Map successContent = (Map) success.get("content"); + Map unavailableContent = (Map) unavailable.get("content"); + Map successJson = (Map) successContent.get("application/json"); + Map unavailableJson = (Map) unavailableContent.get("application/json"); + Map successSchema = (Map) successJson.get("schema"); + Map unavailableSchema = (Map) unavailableJson.get("schema"); + + assertEquals("#/components/schemas/ApiResponseError", unavailableSchema.get("$ref")); + assertEquals("object", successSchema.get("type")); + } } @Test From 47e3887c3c5ea7e29db3b290d7e20dcd58452e7f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:43:02 +1300 Subject: [PATCH 54/75] test(admission): reject nonpositive pointer runtime identities --- ...ionRuntimeControlPlaneReadServiceTest.java | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java index 89cf63c43b..202fe14169 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java @@ -194,6 +194,26 @@ void runtimeReadFailsClosedWhenAdmissionPointerCatalogRevisionIsMissing() { error.getMessage()); } + @Test + void runtimeReadFailsClosedWhenAdmissionPointerTenantIdIsZero() { + assertRuntimeReadFailsClosedForAdmissionPointerIdentity(0L, 7L); + } + + @Test + void runtimeReadFailsClosedWhenAdmissionPointerTenantIdIsNegative() { + assertRuntimeReadFailsClosedForAdmissionPointerIdentity(-1L, 7L); + } + + @Test + void runtimeReadFailsClosedWhenAdmissionPointerGameInstanceIdIsZero() { + assertRuntimeReadFailsClosedForAdmissionPointerIdentity(1L, 0L); + } + + @Test + void runtimeReadFailsClosedWhenAdmissionPointerGameInstanceIdIsNegative() { + assertRuntimeReadFailsClosedForAdmissionPointerIdentity(1L, -1L); + } + @Test void runtimeReadOmitsPublicationForUnpinnedInstanceWithoutCallingGameDesign() { WorldManagementClient world = mock(WorldManagementClient.class); @@ -573,6 +593,49 @@ private GameSessionRuntimeControlPlaneReadService service(WorldManagementClient return service(world, "RUNNING"); } + private void assertRuntimeReadFailsClosedForAdmissionPointerIdentity( + long pointerTenantId, long pointerGameInstanceId) { + WorldManagementClient world = mock(WorldManagementClient.class); + when(world.getWorldInstanceLifecycle(1L, 7L)) + .thenReturn( + worldLifecycle( + 1L, 7L, 3L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); + GameplayAdmissionPointerAuthorityService authority = + mock(GameplayAdmissionPointerAuthorityService.class); + when(authority.listByRuntimeTarget(1L, 7L)) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Production", + pointerTenantId, + pointerGameInstanceId, + 11L, + true, + true, + true, + "SHARED", + "CREATE_ALLOWED", + 12L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); + GameSessionRuntimeControlPlaneReadService service = + service(world, "RUNNING", null, null, null, null, authority); + + GameSessionRuntimeControlPlaneReadService.RuntimeStateException error = + assertThrows( + GameSessionRuntimeControlPlaneReadService.RuntimeStateException.class, + () -> service.getGameInstanceRuntimeState(1L, runtimeRequest())); + + assertEquals("ADMISSION_POINTER_AUTHORITY_UNAVAILABLE", error.code()); + assertEquals( + "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE: current admission pointer durable identity or catalog revision is unavailable", + error.getMessage()); + verify(authority).listByRuntimeTarget(1L, 7L); + } + private GameSessionRuntimeControlPlaneReadService service( WorldManagementClient world, String status) { return service(world, status, null, null); From 4e9cdbdde8bb9f9542864c325e754ae27ffd12ab Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 15:31:22 +1300 Subject: [PATCH 55/75] Align admission proof reads with exact tenant access --- .../GameSessionControlPlaneGrpcService.java | 21 +- ...ameSessionControlPlaneGrpcServiceTest.java | 222 +++++++++++++++++- 2 files changed, 235 insertions(+), 8 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java index 787b590481..3a437cbafa 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java @@ -118,6 +118,14 @@ private long parseTenantId(String tenantId) { return ControlPlaneRequestParser.parsePositiveLong(tenantId, "tenant_id"); } + private long requireTenantAccess(String tenantId) { + long parsedTenantId = parseTenantId(tenantId); + if (!SessionContext.hasTenantAccess(parsedTenantId)) { + throw new AdminAuthorizationException("Tenant access required"); + } + return parsedTenantId; + } + private long parseGameInstanceId(String gameInstanceId) { return ControlPlaneRequestParser.parsePositiveLong(gameInstanceId, "game_instance_id"); } @@ -229,7 +237,7 @@ public void listAdmissionPointerAudit( ListAdmissionPointerAuditRequest request, StreamObserver responseObserver) { try { - requireAdminRole(); + requireTenantAccess(request.getTenantId()); responseObserver.onNext( admissionPointerControlPlaneService.listAdmissionPointerAudit(request)); responseObserver.onCompleted(); @@ -806,8 +814,7 @@ public void getGameInstanceRuntimeState( GetGameInstanceRuntimeStateRequest request, StreamObserver responseObserver) { try { - requireAdminRole(); - long tenantId = parseTenantId(request.getTenantId()); + long tenantId = requireTenantAccess(request.getTenantId()); GetGameInstanceRuntimeStateResponse response = GetGameInstanceRuntimeStateResponse.newBuilder() .setRuntimeState( @@ -971,10 +978,10 @@ public void validateInstanceCutoverCompatibility( ValidateInstanceCutoverCompatibilityRequest request, StreamObserver responseObserver) { try { - requireAdminRole(); + long tenantId = requireTenantAccess(request.getTenantId()); responseObserver.onNext( versionUpgradeControlPlaneService.validateInstanceCutoverCompatibility( - parseTenantId(request.getTenantId()), + tenantId, parseGameInstanceId(request.getSourceGameInstanceId()), parseGameInstanceId(request.getTargetVersionId()))); responseObserver.onCompleted(); @@ -1048,10 +1055,10 @@ public void getPreparedVersionUpgrade( GetPreparedVersionUpgradeRequest request, StreamObserver responseObserver) { try { - requireAdminRole(); + long tenantId = requireTenantAccess(request.getTenantId()); responseObserver.onNext( versionUpgradeControlPlaneService.getPreparedVersionUpgrade( - parseTenantId(request.getTenantId()), request.getPreparationId())); + tenantId, request.getPreparationId())); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { GetPreparedVersionUpgradeResponse response = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 1133ee51e6..42caa859cb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -612,6 +612,16 @@ public void onNext(GetGameInstanceRuntimeStateResponse value) { assertEquals("region-7", responseRef.get().getRuntimeState().getRegionId()); assertEquals(22L, responseRef.get().getRuntimeState().getRegionEpoch()); assertEquals(17L, responseRef.get().getRuntimeState().getPublication().getVersionId()); + SessionContext.setContext("42", List.of("moderator"), Map.of()); + assertEquals( + "", invokeAdmissionReadProof(service, AdmissionReadProofOperation.RUNTIME_STATE, "1")); + for (String role : List.of("tenantAdmin", "moderator")) { + SessionContext.setContext("42", List.of(), Map.of("1", List.of(role))); + assertEquals( + "", + invokeAdmissionReadProof(service, AdmissionReadProofOperation.RUNTIME_STATE, "1"), + role); + } } @Test @@ -2307,7 +2317,14 @@ public void onNext(ListAdmissionPointerAuditResponse value) { assertFalse(responseRef.get().getAudit(1).hasCatalogRevision()); assertTrue(responseRef.get().getAudit(1).getRealmId().isEmpty()); assertTrue(responseRef.get().getAudit(1).getPlayableStateNamespaceId().isEmpty()); - Mockito.verify(authorityService).listPointerAudit(1L, "demo", "production"); + SessionContext.setContext("42", List.of("moderator"), Map.of()); + assertEquals("", invokeAdmissionReadProof(service, AdmissionReadProofOperation.AUDIT, "1")); + for (String role : List.of("tenantAdmin", "moderator")) { + SessionContext.setContext("42", List.of(), Map.of("1", List.of(role))); + assertEquals( + "", invokeAdmissionReadProof(service, AdmissionReadProofOperation.AUDIT, "1"), role); + } + Mockito.verify(authorityService, Mockito.times(4)).listPointerAudit(1L, "demo", "production"); Mockito.verify(authorityService, Mockito.never()).listPointers(); } @@ -2431,6 +2448,45 @@ public void onNext(ListAdmissionPointerAuditResponse value) { Mockito.verify(authorityService, Mockito.never()).listPointers(); } + @Test + void scopedAdmissionReadProofReceiversRejectOtherTenantBasicRoleAndAbsentContextBeforeReads() { + for (AdmissionCallerContext callerContext : AdmissionCallerContext.values()) { + AdmissionReadProofFixture fixture = admissionReadProofFixture(); + switch (callerContext) { + case OTHER_TENANT -> + SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); + case BASIC_ROLE -> SessionContext.setContext("42", List.of("player"), Map.of()); + case ABSENT -> SessionContext.clear(); + } + + for (AdmissionReadProofOperation operation : AdmissionReadProofOperation.values()) { + assertEquals( + "PERMISSION_DENIED", + invokeAdmissionReadProof(fixture.service(), operation, "2"), + callerContext + " " + operation); + } + + verifyNoAdmissionReadInteractions(fixture); + } + } + + @Test + void scopedAdmissionReadProofReceiversKeepTenantParseErrorsBeforeAuthorization() { + AdmissionReadProofFixture fixture = admissionReadProofFixture(); + + for (String invalidTenantId : List.of("not-a-number", "0", "-1", "9223372036854775808")) { + SessionContext.clear(); + for (AdmissionReadProofOperation operation : AdmissionReadProofOperation.values()) { + assertEquals( + "INVALID_ARGUMENT", + invokeAdmissionReadProof(fixture.service(), operation, invalidTenantId), + invalidTenantId + " " + operation); + } + } + + verifyNoAdmissionReadInteractions(fixture); + } + @Test void getGameplayCommandStatusReturnsLedgerRecordForAdminCaller() { GameplayCommand command = new GameplayCommand(); @@ -8727,6 +8783,16 @@ public void onNext(ValidateInstanceCutoverCompatibilityResponse value) { responseRef.get().getResult()); assertEquals("remap-1", responseRef.get().getRemapSetId()); assertEquals(2, responseRef.get().getParticipantResultsCount()); + SessionContext.setContext("42", List.of("moderator"), Map.of()); + assertEquals( + "", invokeAdmissionReadProof(service, AdmissionReadProofOperation.COMPATIBILITY, "1")); + for (String role : List.of("tenantAdmin", "moderator")) { + SessionContext.setContext("42", List.of(), Map.of("1", List.of(role))); + assertEquals( + "", + invokeAdmissionReadProof(service, AdmissionReadProofOperation.COMPATIBILITY, "1"), + role); + } } @Test @@ -8839,6 +8905,19 @@ public void onNext(GetPreparedVersionUpgradeResponse value) { assertEquals("pvu-req-1", responseRef.get().getPreparation().getControlPlaneRequestId()); assertEquals("55", responseRef.get().getPreparation().getExecutedTargetGameInstanceId()); assertEquals(4L, responseRef.get().getPreparation().getExecutedPointerVersion()); + SessionContext.setContext("42", List.of("moderator"), Map.of()); + assertEquals( + "", + invokeAdmissionReadProof( + service, AdmissionReadProofOperation.PREPARED_VERSION, "1", "pvu-1")); + for (String role : List.of("tenantAdmin", "moderator")) { + SessionContext.setContext("42", List.of(), Map.of("1", List.of(role))); + assertEquals( + "", + invokeAdmissionReadProof( + service, AdmissionReadProofOperation.PREPARED_VERSION, "1", "pvu-1"), + role); + } } private static GameSessionControlPlaneGrpcService newService(GameInstanceRepository repository) { @@ -10151,6 +10230,147 @@ private static GameInstance runningPinnedGameInstance() { return instance; } + private static AdmissionReadProofFixture admissionReadProofFixture() { + GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); + RuntimeRegionStatusRepository runtimeRegionStatusRepository = + Mockito.mock(RuntimeRegionStatusRepository.class); + GameplayAdmissionPointerAuthorityService pointerAuthority = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + InstanceCutoverCompatibilityService compatibilityService = + Mockito.mock(InstanceCutoverCompatibilityService.class); + VersionUpgradePreparationService preparationService = + Mockito.mock(VersionUpgradePreparationService.class); + GameSessionControlPlaneGrpcService service = + controlPlaneService( + gameInstanceRepository, + Mockito.mock(GameplayCommandRepository.class), + runtimeRegionStatusRepository, + pointerAuthority, + compatibilityService, + preparationService, + Mockito.mock(GameDesignClient.class), + BuiltInTextCommandAliasResolver.unsupported(), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + return new AdmissionReadProofFixture( + service, + gameInstanceRepository, + runtimeRegionStatusRepository, + pointerAuthority, + compatibilityService, + preparationService); + } + + private static String invokeAdmissionReadProof( + GameSessionControlPlaneGrpcService service, + AdmissionReadProofOperation operation, + String tenantId) { + return invokeAdmissionReadProof(service, operation, tenantId, "pvu-2"); + } + + private static String invokeAdmissionReadProof( + GameSessionControlPlaneGrpcService service, + AdmissionReadProofOperation operation, + String tenantId, + String preparationId) { + return switch (operation) { + case AUDIT -> { + AtomicReference response = new AtomicReference<>(); + service.listAdmissionPointerAudit( + ListAdmissionPointerAuditRequest.newBuilder() + .setTenantId(tenantId) + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + capturingObserver(response)); + assertNotNull(response.get()); + yield response.get().getError().getCode(); + } + case RUNTIME_STATE -> { + AtomicReference response = new AtomicReference<>(); + service.getGameInstanceRuntimeState( + GetGameInstanceRuntimeStateRequest.newBuilder() + .setTenantId(tenantId) + .setGameInstanceId("7") + .build(), + capturingObserver(response)); + assertNotNull(response.get()); + yield response.get().getError().getCode(); + } + case COMPATIBILITY -> { + AtomicReference response = + new AtomicReference<>(); + service.validateInstanceCutoverCompatibility( + ValidateInstanceCutoverCompatibilityRequest.newBuilder() + .setTenantId(tenantId) + .setSourceGameInstanceId("7") + .setTargetVersionId("9") + .build(), + capturingObserver(response)); + assertNotNull(response.get()); + yield response.get().getError().getCode(); + } + case PREPARED_VERSION -> { + AtomicReference response = new AtomicReference<>(); + service.getPreparedVersionUpgrade( + GetPreparedVersionUpgradeRequest.newBuilder() + .setTenantId(tenantId) + .setPreparationId(preparationId) + .build(), + capturingObserver(response)); + assertNotNull(response.get()); + yield response.get().getError().getCode(); + } + }; + } + + private static void verifyNoAdmissionReadInteractions(AdmissionReadProofFixture fixture) { + Mockito.verifyNoInteractions( + fixture.gameInstanceRepository(), + fixture.runtimeRegionStatusRepository(), + fixture.pointerAuthority(), + fixture.compatibilityService(), + fixture.preparationService()); + } + + private static StreamObserver capturingObserver(AtomicReference response) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + response.set(value); + } + + @Override + public void onError(Throwable throwable) { + fail(throwable); + } + + @Override + public void onCompleted() {} + }; + } + + private enum AdmissionReadProofOperation { + AUDIT, + RUNTIME_STATE, + COMPATIBILITY, + PREPARED_VERSION + } + + private enum AdmissionCallerContext { + OTHER_TENANT, + BASIC_ROLE, + ABSENT + } + + private record AdmissionReadProofFixture( + GameSessionControlPlaneGrpcService service, + GameInstanceRepository gameInstanceRepository, + RuntimeRegionStatusRepository runtimeRegionStatusRepository, + GameplayAdmissionPointerAuthorityService pointerAuthority, + InstanceCutoverCompatibilityService compatibilityService, + VersionUpgradePreparationService preparationService) {} + private static void stubLockedGameInstance( GameInstanceRepository repository, GameInstance instance) { Mockito.when(repository.findByTenantIdAndGameInstanceIdForUpdate(1L, 7L)) From b0babd0b8a03fb1451374022c8d0bb1ce24139b5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 16:02:04 +1300 Subject: [PATCH 56/75] Align pointer CAS implementation status and proof gaps --- .../system-architecture-multi-tenancy.md | 2 +- .../realm-routing-and-playable-state.md | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index 43b67cfcbf..e1a971f6c6 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -14,7 +14,7 @@ The complete playtest initialization and lifecycle contract is owned by [ADR 013 ## Implementation Status -The realm-catalog, admission-pointer, realm-local character, explicit first-join, and quota-boundary contracts below are normative target behavior. Current runtime proof is partial: `IssueConnectToken` and text `PLAY` consume the current Account membership adapter evidence `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the membership and admission flags are true. Text `PLAY` validates the applicable private/playtest realm grant; `IssueConnectToken` checks the selected pointer/visibility and membership inputs but does not yet validate that applicable grant, so token grant validation remains an incomplete implementation/proof gap. The adapter has no lifecycle-state field. The obsolete implicit membership-writer surface has been removed; the membership-generation live reread at connect-token issuance is not implemented; pointer updates still use a read-then-write check with separate pointer/audit/prepared-execution writes; scoped-role population and tenant switching are not fully implemented/proved; authoritative entitlement freshness plus complete owning-service quota enforcement remain incomplete; and broader authority-generation claims, durable projections, and enforcement remain incomplete across issuer, account, tenant, and membership scopes. Explicit `JOIN`/`Join & Play` remains unimplemented, so the first-join flow remains target-state only. Playtest fork creation, reset, expiry automation, owner manifests, and lifecycle routes are also not implemented or end-to-end proved; this status does not weaken the target namespace and isolation rules above. Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. Required focused proof covers distinct-tenant separation, same-tenant stability across process restart with the persisted assignment/version, concurrent first allocation returning one assignment, rejection of a tag collision across allocation versions, and rejection of an active-binding `bindingRef` whose tenant differs from the requested tenant. No end-to-end proof yet demonstrates these target invariants. The remaining gaps do not change the distinct stable `tenantSlug` and tenant-scoped authored-world `worldSlug` selectors, tenant-local `realmSlug` to durable `realmId` resolution, exact-tenant quota binding, or required `GetAdmissionPointer(tenantId, realmId)` contract. +The realm-catalog, admission-pointer, realm-local character, explicit first-join, and quota-boundary contracts below are normative target behavior. Current runtime proof is partial: `IssueConnectToken` and text `PLAY` consume the current Account membership adapter evidence `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the membership and admission flags are true. Text `PLAY` validates the applicable private/playtest realm grant; `IssueConnectToken` checks the selected pointer/visibility and membership inputs but does not yet validate that applicable grant, so token grant validation remains an incomplete implementation/proof gap. The adapter has no lifecycle-state field. The obsolete implicit membership-writer surface has been removed; the membership-generation live reread at connect-token issuance is not implemented; the internal Game Session pointer persistence seam now locks existing rows, checks the expected pointer/catalog revision pair, applies a conditional update, and commits pointer plus audit together. Runtime-target changes advance `pointerVersion` while catalog/policy changes advance `catalogRevision`; external pointer-mutation and cutover control-plane RPCs remain fail-closed, and explicit `CLOSED`, full prepared-execution/hold/drain atomicity, and canonical `{tenantId, realmId}` persistence remain gaps (see the [realm-routing implementation status](../project-management/implementation-tracking/realm-routing-and-playable-state.md#capability-status)); scoped-role population and tenant switching are not fully implemented/proved; authoritative entitlement freshness plus complete owning-service quota enforcement remain incomplete; and broader authority-generation claims, durable projections, and enforcement remain incomplete across issuer, account, tenant, and membership scopes. Explicit `JOIN`/`Join & Play` remains unimplemented, so the first-join flow remains target-state only. Playtest fork creation, reset, expiry automation, owner manifests, and lifecycle routes are also not implemented or end-to-end proved; this status does not weaken the target namespace and isolation rules above. Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. Required focused proof covers distinct-tenant separation, same-tenant stability across process restart with the persisted assignment/version, concurrent first allocation returning one assignment, rejection of a tag collision across allocation versions, and rejection of an active-binding `bindingRef` whose tenant differs from the requested tenant. No end-to-end proof yet demonstrates these target invariants. The remaining gaps do not change the distinct stable `tenantSlug` and tenant-scoped authored-world `worldSlug` selectors, tenant-local `realmSlug` to durable `realmId` resolution, exact-tenant quota binding, or required `GetAdmissionPointer(tenantId, realmId)` contract. --- diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index a7bb6391dc..8ba8f6173d 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -19,9 +19,9 @@ These links add decision provenance only; they do not upgrade routing or playabl | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Filtered WORLDS/REALMS/CHARS discovery is live, but the baseline unique index is `(world_slug, realm_slug)` rather than canonical `{tenantId, worldSlug, realmSlug}`; cross-tenant duplicate selectors are not schema-safe. | +| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Filtered WORLDS/REALMS/CHARS discovery is live. V2 now enforces tenant-local selector uniqueness, and V6 persists generated realm IDs for retained supported rows; canonical `{tenantId, realmId}` repository addressing and retained catalog-to-realm mapping remain gaps (see AA-3.3). | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production admission, non-public discovery requiring both current admitting membership and realm grant, grant reads, and shared/isolated state projection are live; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | -| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer reads and audit reads are live. Internal sequential expected-version and prepared-cutover seams exist but are nonconformant and do not establish the target atomic CAS/cutover. Explicit closure, atomic CAS/cutover bookkeeping, catalog revision separation, tenant-qualified persistence, and bounded active-session drain remain unimplemented. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | +| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority now uses a row-locked expected `{pointerVersion, catalogRevision}` check, a conditional existing-row update, separate route/catalog revisions, and one pointer-plus-audit transaction. Public pointer mutation/cutover RPCs remain fail-closed, so the full target cutover operation is not live. Explicit `CLOSED`, repository addressing by the canonical `{tenantId, realmId}` key and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | ## Canonical Design Sources @@ -106,11 +106,11 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - Blank-scope login/bootstrap command staging currently retains the normalized shell selection hint with `playableStateScope=UNSPECIFIED` when runtime-target authority is absent, ambiguous, or incomplete. The implementation still needs focused proof that this hint cannot be consumed as routing authority or downstream gameplay metadata, plus convergence if any consumer crosses that boundary. - Region-partitioned runtime ownership and broader region fencing are tracked separately from admission routing. Current runtime projections carry region hints where available but do not implement the final execution-partition topology. - Replacement-instance migration/remap mechanics and domain-specific carry-forward rules remain unimplemented, including economy, guild, and combat-specific policy. -- The current pointer model cannot represent explicit `CLOSED`, increments its one version for every upsert including display metadata, and invalidates active bindings against current pointer state rather than ending them through the target bounded drain. +- The current pointer model cannot represent explicit `CLOSED`. Runtime-target changes advance `pointerVersion`; catalog/policy changes advance separate `catalogRevision`, so display and other catalog-only edits do not advance the runtime route version. Current active bindings are still fenced against current pointer state rather than ended through the target bounded drain. - The target replacement cutover also requires one World-owned durable `cutoverHoldId`/`cutoverHoldFence` after target `ACTIVE` proof. The current implementation has no hold record or coordinated acquire/finalize/readback surface; it does not block source/target termination while the hold is unresolved, bind the hold into the pointer/audit/prepared-execution/source-cleanup/drain-fence transaction, or prove safe abort versus finalization. Expiry and contradictory evidence therefore have no implemented reconciliation proof. -- `expectedPointerVersion` is checked after a read, but the database update is not conditional on the expected version. Concurrent writers and duplicate committed versions are not prevented or proven. -- Pointer state and audit event commit together, but `ExecutePreparedVersionCutover` marks the prepared upgrade executed afterward. A crash in that interval lacks the target atomic retry/reconciliation behavior; the target drain work item, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. -- The pointer migration's unique index is `(world_slug, realm_slug)` rather than the canonical tenant-qualified key, so cross-tenant duplicate world/realm selectors are not schema-safe even though repository reads include `tenant_id`. +- The internal authority locks an existing pointer row, requires the expected `pointerVersion` and `catalogRevision` pair, and issues the existing-row update with both prior values in the database predicate. This owner-local CAS does not enable control-plane mutation: the public mutation path remains fail-closed, and full prepared-cutover CAS/readback is unimplemented. +- The internal pointer authority commits pointer state and its audit event together. The `ExecutePreparedVersionCutover` RPC currently fails closed before authority/preparation reads or execution marking, so no live cutover writes prepared-execution state in that transaction. The full target atomic retry/reconciliation boundary, including prepared execution and hold/drain evidence, remains unimplemented; drain work, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. +- Current storage uses the tenant-local selector key `(tenant_id, world_slug, realm_slug)` (V2) and separately persists globally unique `realm_id` values (V6). The target composite `{tenantId, realmId}` key/index is not yet the repository lookup or uniqueness key; canonical realm-ID addressing and retained catalog-to-realm mapping remain unimplemented. - The canonical grant record permits expiry and calls for tenant-admin management; the current Account grant row and internal-only grant endpoints do not implement that follow-through. - The current documentation-only slice passed `./gradlew linkCheck lintMarkdown`. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md); runtime proof is not applicable to this documentation-only checkpoint. @@ -122,7 +122,7 @@ No competing implementation is recorded for visible realm addressing, world-qual | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | -| Game Session | Persisted realm catalog and admission pointers; current audit/read-then-write version check/cutover; catalog projection; session normalization; runtime, tick, command, remote, and operator projections | World-qualified admission-pointer gRPC/control-plane APIs; persisted pointer authority; normalized session helpers | +| Game Session | Persisted realm catalog and admission pointers; internal row-locked dual-revision CAS with atomic pointer/audit persistence; catalog projection; session normalization; runtime, tick, command, remote, and operator projections. Public pointer-mutation and cutover RPCs remain fail-closed. | World-qualified admission-pointer gRPC/control-plane APIs; persisted pointer authority; normalized session helpers | | Account Service | Tenant membership/grants; bootstrap worlds/realms/characters; membership exit; membership-required connect-token issuance; target explicit public-production join | Bootstrap/auth REST and gRPC APIs; runtime membership/grant/entitlement reads; target explicit-join behavior | | Gateway and TCP Proxy | Trusted first-party/Telnet routing propagation; explicit disconnect runtime metadata; authenticated callbacks | Connect context; all-or-none routing headers; `gameInstanceId` disconnect envelope | | Entity Management | Scoped character, roster, item, friend, progression, resource, condition, and playable-state persistence | `{tenantId, gameInstanceId, playableStateScope}` APIs and attested gameplay calls | From 75b4b1ff59e6c44fd78de2304ef1a5c08c4422a1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 19:43:37 +1300 Subject: [PATCH 57/75] Bound admission pointer reads and preserve availability failures --- ...meplayAdmissionPointerEventRepository.java | 15 ++ .../GameplayAdmissionPointerRepository.java | 13 ++ ...eplayAdmissionPointerAuthorityService.java | 5 + ...eplayAdmissionPointerAuthorityService.java | 65 +++--- ...onAdmissionPointerControlPlaneService.java | 26 +-- .../GameSessionControlPlaneGrpcService.java | 79 +++++++- ...ameplayAdmissionPointerRepositoryTest.java | 32 +++ ...yAdmissionPointerAuthorityServiceTest.java | 21 ++ ...missionPointerControlPlaneServiceTest.java | 21 +- ...ameSessionControlPlaneGrpcServiceTest.java | 186 ++++++++++++------ 10 files changed, 350 insertions(+), 113 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java index c37e1d298c..e0f171c876 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java @@ -6,6 +6,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; +import java.util.Optional; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayAdmissionPointerEventRecord; import org.jooq.DSLContext; @@ -48,6 +49,20 @@ public List findByTenantIdAndWorldSlugAndRealmSlu .fetch(this::toEntity); } + public Optional findLatestByTenantIdAndWorldSlugAndRealmSlug( + Long tenantId, String worldSlug, String realmSlug) { + return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER_EVENT) + .where( + GAMEPLAY_ADMISSION_POINTER_EVENT + .TENANT_ID + .eq(tenantId) + .and(GAMEPLAY_ADMISSION_POINTER_EVENT.WORLD_SLUG.eq(worldSlug)) + .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(realmSlug))) + .orderBy(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.desc()) + .limit(1) + .fetchOptional(this::toEntity); + } + public GameplayAdmissionPointerEvent save(GameplayAdmissionPointerEvent entity) { if (entity.getId() == null) { GameplayAdmissionPointerEventRecord record = dsl.newRecord(GAMEPLAY_ADMISSION_POINTER_EVENT); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index 5582c6255d..820ec58437 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -100,6 +100,19 @@ public List findAllByOrderByWorldSlugAscRealmSlugAsc() .fetch(this::toEntity); } + public List findAllByTenantIdInOrderByWorldSlugAscRealmSlugAsc( + List tenantIds) { + if (tenantIds.isEmpty()) { + return List.of(); + } + return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + .where(GAMEPLAY_ADMISSION_POINTER.TENANT_ID.in(tenantIds)) + .orderBy( + GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG.asc(), + GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.asc()) + .fetch(this::toEntity); + } + public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { if (entity.getId() == null) { if (!"SHARED".equals(entity.getStateScope()) && !"ISOLATED".equals(entity.getStateScope())) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java index c2f2b4abee..b56e4b159f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java @@ -6,6 +6,8 @@ public interface GameplayAdmissionPointerAuthorityService { List listPointers(); + List listPointersForTenants(List tenantIds); + Optional findPointer( long tenantId, String worldSlug, String realmSlug); @@ -15,4 +17,7 @@ Optional findPointer( List listPointerAudit( long tenantId, String worldSlug, String realmSlug); + + Optional findLatestPointerAudit( + long tenantId, String worldSlug, String realmSlug); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index a744dc6d7d..3186b87cdc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -45,6 +45,14 @@ public List listPointers() { .toList(); } + @Override + @Transactional(readOnly = true) + public List listPointersForTenants(List tenantIds) { + return pointerRepository.findAllByTenantIdInOrderByWorldSlugAscRealmSlugAsc(tenantIds).stream() + .map(this::toSnapshot) + .toList(); + } + @Override @Transactional(readOnly = true) public Optional findPointer( @@ -151,32 +159,43 @@ public List listPointerAudit( return eventRepository .findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc(tenantId, worldSlug, realmSlug) .stream() - .map( - event -> - new GameplayAdmissionPointerAuditEntry( - event.getWorldSlug(), - event.getRealmSlug(), - event.getWorldDisplayName(), - event.getRealmDisplayName(), - event.getTenantId(), - event.getGameInstanceId(), - event.getPointerVersion(), - event.getCatalogRevision(), - event.getRealmId(), - event.getPlayableStateNamespaceId(), - event.isVisible(), - event.isPublicProductionRealm(), - event.isRequiresCharacterSelection(), - event.getStateScope(), - event.getCharacterCreationPolicy(), - event.getActorPrincipal(), - event.getReason(), - event.getControlPlaneRequestId(), - event.getPreparedVersionUpgradeId(), - event.getOccurredAt())) + .map(this::toAuditEntry) .toList(); } + @Override + @Transactional(readOnly = true) + public Optional findLatestPointerAudit( + long tenantId, String worldSlug, String realmSlug) { + return eventRepository + .findLatestByTenantIdAndWorldSlugAndRealmSlug(tenantId, worldSlug, realmSlug) + .map(this::toAuditEntry); + } + + private GameplayAdmissionPointerAuditEntry toAuditEntry(GameplayAdmissionPointerEvent event) { + return new GameplayAdmissionPointerAuditEntry( + event.getWorldSlug(), + event.getRealmSlug(), + event.getWorldDisplayName(), + event.getRealmDisplayName(), + event.getTenantId(), + event.getGameInstanceId(), + event.getPointerVersion(), + event.getCatalogRevision(), + event.getRealmId(), + event.getPlayableStateNamespaceId(), + event.isVisible(), + event.isPublicProductionRealm(), + event.isRequiresCharacterSelection(), + event.getStateScope(), + event.getCharacterCreationPolicy(), + event.getActorPrincipal(), + event.getReason(), + event.getControlPlaneRequestId(), + event.getPreparedVersionUpgradeId(), + event.getOccurredAt()); + } + private GameplayAdmissionPointerSnapshot toSnapshot(GameplayAdmissionPointer pointer) { return new GameplayAdmissionPointerSnapshot( pointer.getWorldSlug(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java index 334e757a84..38f9ebb972 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java @@ -39,18 +39,25 @@ final class GameSessionAdmissionPointerControlPlaneService { ListAdmissionPointersResponse listAdmissionPointers(List requestedTenantIds) { Set tenantScope = Set.copyOf(requestedTenantIds); + List tenantIds = List.copyOf(requestedTenantIds); List pointers = - gameplayAdmissionPointerAuthorityService.listPointers().stream() - .filter(pointer -> tenantScope.isEmpty() || tenantScope.contains(pointer.tenantId())) - .toList(); + (tenantScope.isEmpty() + ? gameplayAdmissionPointerAuthorityService.listPointers() + : gameplayAdmissionPointerAuthorityService.listPointersForTenants(tenantIds)) + .stream() + .filter( + pointer -> tenantScope.isEmpty() || tenantScope.contains(pointer.tenantId())) + .toList(); java.util.List entries = pointers.stream() .map( pointer -> { - java.util.List audit = - gameplayAdmissionPointerAuthorityService.listPointerAudit( - pointer.tenantId(), pointer.worldSlug(), pointer.realmSlug()); - if (audit.isEmpty()) { + GameplayAdmissionPointerAuditEntry latestAudit = + gameplayAdmissionPointerAuthorityService + .findLatestPointerAudit( + pointer.tenantId(), pointer.worldSlug(), pointer.realmSlug()) + .orElse(null); + if (latestAudit == null) { throw new AdmissionPointerAuditUnavailableException( "Admission pointer audit unavailable for current pointer " + pointer.tenantId() @@ -59,7 +66,6 @@ ListAdmissionPointersResponse listAdmissionPointers(List requestedTenantId + "/" + pointer.realmSlug()); } - GameplayAdmissionPointerAuditEntry latestAudit = audit.getFirst(); if (!matchesCurrentPointer(pointer, latestAudit)) { throw new AdmissionPointerAuditUnavailableException( "Admission pointer audit does not match current pointer " @@ -174,9 +180,7 @@ ExecutePreparedVersionCutoverResponse executePreparedVersionCutover( private AdmissionPointerControlPlaneEntry latestAuditEntry( long tenantId, String worldSlug, String realmSlug) { return gameplayAdmissionPointerAuthorityService - .listPointerAudit(tenantId, worldSlug, realmSlug) - .stream() - .findFirst() + .findLatestPointerAudit(tenantId, worldSlug, realmSlug) .map(this::toEntry) .orElseThrow(() -> new IllegalStateException("Admission pointer audit missing")); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java index 3a437cbafa..b09bde693b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java @@ -4,6 +4,11 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.sql.SQLException; +import java.sql.SQLNonTransientConnectionException; +import java.sql.SQLRecoverableException; +import java.sql.SQLTimeoutException; +import java.sql.SQLTransientConnectionException; import java.util.List; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.security.AdminAuthorizationException; @@ -71,6 +76,9 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.QueryTimeoutException; +import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.grpc.server.service.GrpcService; @GrpcService @@ -165,6 +173,49 @@ private ErrorDetail automationAdmissionReceiverFenceUnavailable(String operation AUTOMATION_ADMISSION_RECEIVER_FENCE_UNAVAILABLE); } + private ErrorDetail admissionPointerAuthorityUnavailableError(String operation) { + return GrpcAppErrors.error( + meterRegistry, + logger, + operation, + "AUTHORITY_UNAVAILABLE", + "Admission pointer authority unavailable"); + } + + private static boolean isPersistenceAvailabilityFailure(Throwable failure) { + Throwable cause = failure; + for (int depth = 0; cause != null && depth < 32; depth++) { + if (cause instanceof DataAccessResourceFailureException + || cause instanceof QueryTimeoutException + || cause instanceof TransientDataAccessResourceException + || cause instanceof SQLNonTransientConnectionException + || cause instanceof SQLRecoverableException + || cause instanceof SQLTimeoutException + || cause instanceof SQLTransientConnectionException) { + return true; + } + if (cause instanceof SQLException sqlException) { + String sqlState = sqlException.getSQLState(); + if (sqlState != null + && (sqlState.startsWith("08") + || "57014".equals(sqlState) + || "HYT00".equals(sqlState) + || "HYT01".equals(sqlState) + || "57P01".equals(sqlState) + || "57P02".equals(sqlState) + || "57P03".equals(sqlState))) { + return true; + } + } + Throwable next = cause.getCause(); + if (next == cause) { + break; + } + cause = next; + } + return false; + } + @Override @Timed(value = "gamesessionGrpc.controlPlane.listAdmissionPointers") public void listAdmissionPointers( @@ -192,17 +243,21 @@ public void listAdmissionPointers( logger.warn("ListAdmissionPointers authority unavailable", ex); ListAdmissionPointersResponse response = ListAdmissionPointersResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "ListAdmissionPointers", - "AUTHORITY_UNAVAILABLE", - "Admission pointer audit authority unavailable")) + .setError(admissionPointerAuthorityUnavailableError("ListAdmissionPointers")) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (Exception ex) { + if (isPersistenceAvailabilityFailure(ex)) { + logger.warn("ListAdmissionPointers persistence unavailable", ex); + ListAdmissionPointersResponse response = + ListAdmissionPointersResponse.newBuilder() + .setError(admissionPointerAuthorityUnavailableError("ListAdmissionPointers")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + return; + } logger.error("ListAdmissionPointers failed", ex); ListAdmissionPointersResponse response = ListAdmissionPointersResponse.newBuilder() @@ -262,6 +317,16 @@ public void listAdmissionPointerAudit( responseObserver.onNext(response); responseObserver.onCompleted(); } catch (Exception ex) { + if (isPersistenceAvailabilityFailure(ex)) { + logger.warn("ListAdmissionPointerAudit persistence unavailable", ex); + ListAdmissionPointerAuditResponse response = + ListAdmissionPointerAuditResponse.newBuilder() + .setError(admissionPointerAuthorityUnavailableError("ListAdmissionPointerAudit")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + return; + } logger.error("ListAdmissionPointerAudit failed", ex); ListAdmissionPointerAuditResponse response = ListAdmissionPointerAuditResponse.newBuilder() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index 3279597344..8ad17a6d47 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -8,6 +8,7 @@ import java.sql.Connection; import java.sql.DriverManager; import java.time.Instant; +import java.util.List; import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; @@ -67,6 +68,27 @@ void stableRealmAndNamespaceIdentitySurviveRuntimeReplacement() throws Exception } } + @Test + void tenantScopedPointerListExcludesOtherTenants() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-tenant-list;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + repository.save(pointer(7L, 44L, "SHARED", "production")); + repository.save(pointer(8L, 55L, "SHARED", "production")); + + var scoped = repository.findAllByTenantIdInOrderByWorldSlugAscRealmSlugAsc(List.of(8L)); + + assertEquals(1, scoped.size()); + assertEquals(8L, scoped.getFirst().getTenantId()); + assertEquals(2, repository.findAllByOrderByWorldSlugAscRealmSlugAsc().size()); + assertEquals( + List.of(), repository.findAllByTenantIdInOrderByWorldSlugAscRealmSlugAsc(List.of())); + } + } + @Test void repositoryRejectsAttemptToReplaceStableRealmIdentity() throws Exception { try (Connection connection = @@ -130,13 +152,23 @@ void pointerAuditOrdersByEventIdWhenPodTimestampMovesBackward() throws Exception GameplayAdmissionPointerEvent laterWriteWithSkewedClock = pointerEvent("2026-09-29T09:00:00Z"); GameplayAdmissionPointerEvent secondSaved = repository.save(laterWriteWithSkewedClock); + GameplayAdmissionPointerEvent otherTenantWrite = pointerEvent("2026-09-29T11:00:00Z"); + otherTenantWrite.setTenantId(8L); + repository.save(otherTenantWrite); var audit = repository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc(7L, "demo", "production"); + var latest = + repository + .findLatestByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production") + .orElseThrow(); + assertEquals(2, audit.size()); assertEquals(secondSaved.getId(), audit.getFirst().getId()); assertEquals(firstSaved.getId(), audit.get(1).getId()); assertEquals(Instant.parse("2026-09-29T09:00:00Z"), audit.getFirst().getOccurredAt()); + assertEquals(secondSaved.getId(), latest.getId()); + assertEquals(Instant.parse("2026-09-29T09:00:00Z"), latest.getOccurredAt()); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index ad3fd50c39..97e2c61136 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -358,6 +358,21 @@ void listPointerAuditExposesPersistedCatalogRevision() { assertEquals(event.getPlayableStateNamespaceId(), auditEntry.playableStateNamespaceId()); } + @Test + void listPointersForTenantsUsesScopedRepositoryQuery() { + GameplayAdmissionPointer pointer = existingPointer(); + pointer.setTenantId(2L); + when(pointerRepository.findAllByTenantIdInOrderByWorldSlugAscRealmSlugAsc(List.of(2L))) + .thenReturn(List.of(pointer)); + + var snapshots = service.listPointersForTenants(List.of(2L)); + + assertEquals(1, snapshots.size()); + assertEquals(2L, snapshots.getFirst().tenantId()); + verify(pointerRepository).findAllByTenantIdInOrderByWorldSlugAscRealmSlugAsc(List.of(2L)); + verify(pointerRepository, never()).findAllByOrderByWorldSlugAscRealmSlugAsc(); + } + @Test void listPointerAuditPreservesPreV7UnknownRevisionAndIdentity() { GameplayAdmissionPointerEvent historicalEvent = new GameplayAdmissionPointerEvent(); @@ -377,11 +392,17 @@ void listPointerAuditPreservesPreV7UnknownRevisionAndIdentity() { when(eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( 1L, "demo", "production")) .thenReturn(List.of(historicalEvent)); + when(eventRepository.findLatestByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + .thenReturn(Optional.of(historicalEvent)); var auditEntry = service.listPointerAudit(1L, "demo", "production").getFirst(); + var latestEntry = service.findLatestPointerAudit(1L, "demo", "production").orElseThrow(); assertNull(auditEntry.catalogRevision()); assertNull(auditEntry.realmId()); assertNull(auditEntry.playableStateNamespaceId()); + assertNull(latestEntry.catalogRevision()); + assertNull(latestEntry.realmId()); + assertNull(latestEntry.playableStateNamespaceId()); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java index cd5f464f0a..f2cacac32a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java @@ -10,6 +10,7 @@ import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.List; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; @@ -24,14 +25,13 @@ class GameSessionAdmissionPointerControlPlaneServiceTest { @Test - void listFiltersTenantScopeBeforeCheckingAuditHistory() { + void listQueriesTenantScopeBeforeCheckingLatestAudit() { GameplayAdmissionPointerAuthorityService authorityService = mock(GameplayAdmissionPointerAuthorityService.class); - GameplayAdmissionPointerSnapshot tenantA = pointer(1L, "tenant-a"); GameplayAdmissionPointerSnapshot tenantB = pointer(2L, "tenant-b"); - when(authorityService.listPointers()).thenReturn(List.of(tenantA, tenantB)); - when(authorityService.listPointerAudit(2L, "tenant-b", "production")) - .thenReturn(List.of(audit(tenantB))); + when(authorityService.listPointersForTenants(List.of(2L))).thenReturn(List.of(tenantB)); + when(authorityService.findLatestPointerAudit(2L, "tenant-b", "production")) + .thenReturn(Optional.of(audit(tenantB))); GameSessionAdmissionPointerControlPlaneService controlPlaneService = new GameSessionAdmissionPointerControlPlaneService( mock(GameInstanceRepository.class), @@ -42,8 +42,10 @@ void listFiltersTenantScopeBeforeCheckingAuditHistory() { assertEquals(1, response.getPointersCount()); assertEquals("2", response.getPointers(0).getTenantId()); - verify(authorityService).listPointerAudit(2L, "tenant-b", "production"); - verify(authorityService, never()).listPointerAudit(1L, "tenant-a", "production"); + verify(authorityService).listPointersForTenants(List.of(2L)); + verify(authorityService, never()).listPointers(); + verify(authorityService).findLatestPointerAudit(2L, "tenant-b", "production"); + verify(authorityService, never()).findLatestPointerAudit(1L, "tenant-a", "production"); } @Test @@ -93,9 +95,8 @@ void listRejectsRetainedPreV7AuditWithUnknownRevisionAndIdentity() { when(pointerRepository.findAllByOrderByWorldSlugAscRealmSlugAsc()) .thenReturn(List.of(currentPointer)); - when(eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( - 1L, "demo", "production")) - .thenReturn(List.of(retainedPreV7Event)); + when(eventRepository.findLatestByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + .thenReturn(Optional.of(retainedPreV7Event)); DatabaseGameplayAdmissionPointerAuthorityService authorityService = new DatabaseGameplayAdmissionPointerAuthorityService(pointerRepository, eventRepository); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 42caa859cb..0c041b2e6d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -1769,12 +1769,11 @@ void listAdmissionPointersAllowsScopedCallerOnlyForRequestedTenantBeforeAuditVal SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - GameplayAdmissionPointerSnapshot inaccessiblePointer = scopedAdmissionPointer(1L, "tenant-a"); GameplayAdmissionPointerSnapshot requestedPointer = scopedAdmissionPointer(2L, "tenant-b"); - Mockito.when(authorityService.listPointers()) - .thenReturn(List.of(inaccessiblePointer, requestedPointer)); - Mockito.when(authorityService.listPointerAudit(2L, "tenant-b", "production")) - .thenReturn(List.of(scopedAdmissionPointerAudit(requestedPointer))); + Mockito.when(authorityService.listPointersForTenants(List.of(2L))) + .thenReturn(List.of(requestedPointer)); + Mockito.when(authorityService.findLatestPointerAudit(2L, "tenant-b", "production")) + .thenReturn(Optional.of(scopedAdmissionPointerAudit(requestedPointer))); GameSessionControlPlaneGrpcService service = admissionPointerControlPlaneService(authorityService); @@ -1791,9 +1790,11 @@ public void onNext(ListAdmissionPointersResponse value) { assertEquals("", responseRef.get().getError().getCode()); assertEquals(1, responseRef.get().getPointersCount()); assertEquals("2", responseRef.get().getPointers(0).getTenantId()); - Mockito.verify(authorityService).listPointerAudit(2L, "tenant-b", "production"); + Mockito.verify(authorityService).listPointersForTenants(List.of(2L)); + Mockito.verify(authorityService, Mockito.never()).listPointers(); + Mockito.verify(authorityService).findLatestPointerAudit(2L, "tenant-b", "production"); Mockito.verify(authorityService, Mockito.never()) - .listPointerAudit(1L, "tenant-a", "production"); + .findLatestPointerAudit(1L, "tenant-a", "production"); } @Test @@ -1889,9 +1890,10 @@ void listAdmissionPointersFailsClosedForMissingAuditInRequestedTenant() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot requestedPointer = scopedAdmissionPointer(2L, "tenant-b"); - Mockito.when(authorityService.listPointers()).thenReturn(List.of(requestedPointer)); - Mockito.when(authorityService.listPointerAudit(2L, "tenant-b", "production")) - .thenReturn(List.of()); + Mockito.when(authorityService.listPointersForTenants(List.of(2L))) + .thenReturn(List.of(requestedPointer)); + Mockito.when(authorityService.findLatestPointerAudit(2L, "tenant-b", "production")) + .thenReturn(Optional.empty()); GameSessionControlPlaneGrpcService service = admissionPointerControlPlaneService(authorityService); AtomicReference responseRef = new AtomicReference<>(); @@ -1930,7 +1932,8 @@ void listAdmissionPointersFailsClosedWhenCurrentPointerHasNoAuditHistory() { "SHARED", "ALLOW_NEW", 2L))); - Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")).thenReturn(List.of()); + Mockito.when(authorityService.findLatestPointerAudit(1L, "demo", "production")) + .thenReturn(Optional.empty()); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( @@ -1980,9 +1983,9 @@ void listAdmissionPointersFailsClosedWhenLatestAuditHasNoCatalogRevision() { 6L, UUID.fromString("11111111-1111-1111-1111-111111111111"), UUID.fromString("22222222-2222-2222-2222-222222222222")))); - Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) + Mockito.when(authorityService.findLatestPointerAudit(1L, "demo", "production")) .thenReturn( - List.of( + Optional.of( new GameplayAdmissionPointerAuditEntry( "demo", "production", @@ -2053,9 +2056,9 @@ void listAdmissionPointersFailsClosedWhenLatestAuditDoesNotMatchCurrentPointer() 6L, UUID.fromString("11111111-1111-1111-1111-111111111111"), UUID.fromString("22222222-2222-2222-2222-222222222222")))); - Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) + Mockito.when(authorityService.findLatestPointerAudit(1L, "demo", "production")) .thenReturn( - List.of( + Optional.of( new GameplayAdmissionPointerAuditEntry( "demo", "production", @@ -2126,9 +2129,9 @@ void listAdmissionPointersExposesDurableIdentityFromAuditEntry() { 6L, UUID.fromString("11111111-1111-1111-1111-111111111111"), UUID.fromString("22222222-2222-2222-2222-222222222222")))); - Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) + Mockito.when(authorityService.findLatestPointerAudit(1L, "demo", "production")) .thenReturn( - List.of( + Optional.of( new GameplayAdmissionPointerAuditEntry( "demo", "production", @@ -2178,55 +2181,114 @@ public void onNext(ListAdmissionPointersResponse value) { "22222222-2222-2222-2222-222222222222", responseRef.get().getPointers(0).getPlayableStateNamespaceId()); assertEquals(6L, responseRef.get().getPointers(0).getCatalogRevision()); + Mockito.verify(authorityService).listPointers(); + Mockito.verify(authorityService, Mockito.never()).listPointersForTenants(Mockito.anyList()); + Mockito.verify(authorityService).findLatestPointerAudit(1L, "demo", "production"); + } + + @Test + void listAdmissionPointersReturnsAuthorityUnavailableForDatabaseShutdownStates() { + for (String sqlState : List.of("08006", "57P01", "57P02", "57P03")) { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(authorityService.listPointers()) + .thenReturn(List.of(scopedAdmissionPointer(1L, "demo"))); + Mockito.when(authorityService.findLatestPointerAudit(1L, "demo", "production")) + .thenThrow( + new org.jooq.exception.DataAccessException( + "audit database unavailable", + new java.sql.SQLException("database unavailable", sqlState))); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + + AtomicReference responseRef = new AtomicReference<>(); + service.listAdmissionPointers( + ListAdmissionPointersRequest.getDefaultInstance(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertNotNull(responseRef.get(), sqlState); + assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode(), sqlState); + assertEquals(0, responseRef.get().getPointersCount(), sqlState); + } } @Test - void listAdmissionPointersReturnsInternalForUnrelatedIllegalStateFailure() { - GameplayAdmissionPointerAuthorityService authorityService = - Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - Mockito.when(authorityService.listPointers()) - .thenReturn( - List.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo World", - "production", - "Live Realm", - 1L, - 7L, - 3L, - true, - true, - false, - "SHARED", - "ALLOW_NEW", - 2L))); - Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) - .thenThrow(new IllegalStateException("audit store failed")); - SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); - GameSessionControlPlaneGrpcService service = - controlPlaneService( - Mockito.mock(GameInstanceRepository.class), - Mockito.mock(GameplayCommandRepository.class), - Mockito.mock(RuntimeRegionStatusRepository.class), - authorityService, - Mockito.mock(InstanceCutoverCompatibilityService.class), - Mockito.mock(VersionUpgradePreparationService.class), - Mockito.mock(TickService.class), - new SimpleMeterRegistry()); - - AtomicReference responseRef = new AtomicReference<>(); - service.listAdmissionPointers( - ListAdmissionPointersRequest.getDefaultInstance(), - new NoopObserver<>() { - @Override - public void onNext(ListAdmissionPointersResponse value) { - responseRef.set(value); - } - }); + void listAdmissionPointersKeepsUnexpectedFailuresInternal() { + List unexpectedFailures = + List.of( + new IllegalStateException("audit mapper failed"), + new org.jooq.exception.DataAccessException( + "integrity failure", new java.sql.SQLException("unique violation", "23505")), + new org.jooq.exception.DataAccessException( + "query failure", new java.sql.SQLException("malformed query", "42601"))); + + for (RuntimeException failure : unexpectedFailures) { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(authorityService.listPointers()) + .thenReturn(List.of(scopedAdmissionPointer(1L, "demo"))); + Mockito.when(authorityService.findLatestPointerAudit(1L, "demo", "production")) + .thenThrow(failure); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + + AtomicReference responseRef = new AtomicReference<>(); + service.listAdmissionPointers( + ListAdmissionPointersRequest.getDefaultInstance(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertNotNull(responseRef.get()); + assertEquals("INTERNAL", responseRef.get().getError().getCode()); + assertEquals(0, responseRef.get().getPointersCount()); + } + } - assertEquals("INTERNAL", responseRef.get().getError().getCode()); - assertEquals(0, responseRef.get().getPointersCount()); + @Test + void listAdmissionPointerAuditReturnsAuthorityUnavailableForTimeoutAndResourceFailures() { + List unavailableFailures = + List.of( + new org.springframework.dao.QueryTimeoutException("audit query timed out"), + new org.springframework.dao.TransientDataAccessResourceException( + "audit connection unavailable")); + + for (RuntimeException failure : unavailableFailures) { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")).thenThrow(failure); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + + AtomicReference responseRef = new AtomicReference<>(); + service.listAdmissionPointerAudit( + ListAdmissionPointerAuditRequest.newBuilder() + .setTenantId("1") + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointerAuditResponse value) { + responseRef.set(value); + } + }); + + assertNotNull(responseRef.get()); + assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); + assertEquals(0, responseRef.get().getAuditCount()); + } } @Test From 2e785b36bbe9250f0caeb9d6cb26ab28f20369f3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 20:19:58 +1300 Subject: [PATCH 58/75] Align runtime and audit availability with their public read contracts --- .../GameSessionControlPlaneGrpcService.java | 10 ++ ...ameSessionControlPlaneGrpcServiceTest.java | 94 +++++++++++++++++++ .../src/main/resources/openapi.yaml | 8 ++ .../AdmissionPointerControllerTest.java | 34 ++++++- 4 files changed, 145 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java index b09bde693b..1f4a942ea0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java @@ -915,6 +915,16 @@ public void getGameInstanceRuntimeState( responseObserver.onNext(response); responseObserver.onCompleted(); } catch (Exception ex) { + if (isPersistenceAvailabilityFailure(ex)) { + logger.warn("GetGameInstanceRuntimeState persistence unavailable", ex); + GetGameInstanceRuntimeStateResponse response = + GetGameInstanceRuntimeStateResponse.newBuilder() + .setError(admissionPointerAuthorityUnavailableError("GetGameInstanceRuntimeState")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + return; + } logger.error("GetGameInstanceRuntimeState failed", ex); GetGameInstanceRuntimeStateResponse response = GetGameInstanceRuntimeStateResponse.newBuilder() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 0c041b2e6d..ecea8ad842 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -941,6 +941,100 @@ public void onNext(GetGameInstanceRuntimeStateResponse value) { assertFalse(responseRef.get().hasRuntimeState()); } + @Test + void getGameInstanceRuntimeStateReturnsAuthorityUnavailableForPersistenceAvailabilityFailures() { + List unavailableFailures = + List.of( + new org.jooq.exception.DataAccessException( + "runtime database unavailable", + new java.sql.SQLException("connection lost", "08006")), + new org.springframework.dao.QueryTimeoutException("runtime query timed out")); + + for (RuntimeException failure : unavailableFailures) { + RuntimeRegionStatusRepository runtimeRepository = + Mockito.mock(RuntimeRegionStatusRepository.class); + Mockito.when(runtimeRepository.findByTenantIdAndRegionId(1L, "region-7")).thenThrow(failure); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + controlPlaneService( + Mockito.mock(GameInstanceRepository.class), + Mockito.mock(GameplayCommandRepository.class), + runtimeRepository, + Mockito.mock(GameplayAdmissionPointerAuthorityService.class), + Mockito.mock(InstanceCutoverCompatibilityService.class), + Mockito.mock(VersionUpgradePreparationService.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + + AtomicReference responseRef = new AtomicReference<>(); + service.getGameInstanceRuntimeState( + GetGameInstanceRuntimeStateRequest.newBuilder() + .setTenantId("1") + .setGameInstanceId("7") + .setRegionId("region-7") + .build(), + new NoopObserver<>() { + @Override + public void onNext(GetGameInstanceRuntimeStateResponse value) { + responseRef.set(value); + } + }); + + assertNotNull(responseRef.get()); + assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); + assertFalse(responseRef.get().hasRuntimeState()); + Mockito.verify(runtimeRepository).findByTenantIdAndRegionId(1L, "region-7"); + } + } + + @Test + void getGameInstanceRuntimeStateKeepsUnexpectedPersistenceFailuresInternal() { + List unexpectedFailures = + List.of( + new IllegalStateException("runtime state mapper failed"), + new org.jooq.exception.DataAccessException( + "runtime integrity failure", + new java.sql.SQLException("unique violation", "23505")), + new org.jooq.exception.DataAccessException( + "runtime query failure", new java.sql.SQLException("malformed query", "42601"))); + + for (RuntimeException failure : unexpectedFailures) { + RuntimeRegionStatusRepository runtimeRepository = + Mockito.mock(RuntimeRegionStatusRepository.class); + Mockito.when(runtimeRepository.findByTenantIdAndRegionId(1L, "region-7")).thenThrow(failure); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + controlPlaneService( + Mockito.mock(GameInstanceRepository.class), + Mockito.mock(GameplayCommandRepository.class), + runtimeRepository, + Mockito.mock(GameplayAdmissionPointerAuthorityService.class), + Mockito.mock(InstanceCutoverCompatibilityService.class), + Mockito.mock(VersionUpgradePreparationService.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + + AtomicReference responseRef = new AtomicReference<>(); + service.getGameInstanceRuntimeState( + GetGameInstanceRuntimeStateRequest.newBuilder() + .setTenantId("1") + .setGameInstanceId("7") + .setRegionId("region-7") + .build(), + new NoopObserver<>() { + @Override + public void onNext(GetGameInstanceRuntimeStateResponse value) { + responseRef.set(value); + } + }); + + assertNotNull(responseRef.get()); + assertEquals("INTERNAL", responseRef.get().getError().getCode()); + assertFalse(responseRef.get().hasRuntimeState()); + Mockito.verify(runtimeRepository).findByTenantIdAndRegionId(1L, "region-7"); + } + } + @Test void getGameInstanceRuntimeStateRejectsZeroGameInstanceId() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); diff --git a/services/logging-admin-service/src/main/resources/openapi.yaml b/services/logging-admin-service/src/main/resources/openapi.yaml index 1c2db29a1e..0aa7b8f048 100644 --- a/services/logging-admin-service/src/main/resources/openapi.yaml +++ b/services/logging-admin-service/src/main/resources/openapi.yaml @@ -1242,8 +1242,10 @@ components: type: integer pointerVersion: type: integer + format: int64 catalogRevision: type: integer + format: int64 nullable: true realmId: type: string @@ -1736,6 +1738,12 @@ paths: $ref: '#/components/schemas/AdmissionPointerDto' error: $ref: '#/components/schemas/ErrorDetail' + '503': + description: Admission-pointer audit authority is unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponseError' /admission-pointers/runtime-state/{tenantId}/{gameInstanceId}: get: summary: Read canonical current runtime state diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java index aaaa69cb51..89dba1c2c6 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java @@ -110,7 +110,7 @@ void listPointersMapsUnavailableCurrentAuthorityToServiceUnavailable() throws Ex } @Test - void openApiDocumentsAdmissionPointerRead503Responses() throws Exception { + void openApiDocumentsAdmissionPointerReadContracts() throws Exception { Map document; try (var input = getClass().getResourceAsStream("/openapi.yaml")) { assertNotNull(input); @@ -121,6 +121,7 @@ void openApiDocumentsAdmissionPointerRead503Responses() throws Exception { for (String path : List.of( "/admission-pointers", + "/admission-pointers/{tenantId}/{worldSlug}/{realmSlug}/audit", "/admission-pointers/runtime-state/{tenantId}/{gameInstanceId}")) { Map admissionPointers = (Map) paths.get(path); Map getOperation = (Map) admissionPointers.get("get"); @@ -138,6 +139,17 @@ void openApiDocumentsAdmissionPointerRead503Responses() throws Exception { assertEquals("#/components/schemas/ApiResponseError", unavailableSchema.get("$ref")); assertEquals("object", successSchema.get("type")); } + + Map components = (Map) document.get("components"); + Map schemas = (Map) components.get("schemas"); + Map pointer = (Map) schemas.get("AdmissionPointerDto"); + Map properties = (Map) pointer.get("properties"); + for (String revision : List.of("pointerVersion", "catalogRevision")) { + Map revisionSchema = (Map) properties.get(revision); + assertEquals("integer", revisionSchema.get("type")); + assertEquals("int64", revisionSchema.get("format")); + } + assertEquals(true, ((Map) properties.get("catalogRevision")).get("nullable")); } @Test @@ -182,6 +194,26 @@ void auditReturnsEntries() throws Exception { .value("22222222-2222-2222-2222-222222222222")); } + @Test + void auditMapsUnavailableAuthorityToServiceUnavailable() throws Exception { + when(admissionPointerService.listPointerAudit(2L, "demo", "production")) + .thenThrow( + new ResponseStatusException( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + "admission-pointer audit authority unavailable")); + SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); + String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + + mockMvc + .perform( + get("/admission-pointers/2/demo/production/audit") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.error.code").value("SERVICE_UNAVAILABLE")) + .andExpect( + jsonPath("$.error.message").value("admission-pointer audit authority unavailable")); + } + @Test void auditRejectsCrossTenantScopedAdmin() throws Exception { SessionContext.setContext("user", List.of(), Map.of("8", List.of("tenantAdmin"))); From 17779252a59fe2e6018655830f2e20fe218befd6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 21:11:27 +1300 Subject: [PATCH 59/75] Correct typed audit ingress capability status --- .../shared-runtime-contracts-and-persistence.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index 2d4754a5a6..7d457b392a 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -119,7 +119,7 @@ The [gRPC outcome and transport classification](../../architecture/system-archit ### Audit, Moderation, and Authority Boundaries -Logging & Admin exposes dedicated non-destructive `CreateLogEvent` ingress, but account-creation audit delivery remains partial: it is still a post-commit best-effort effect rather than the target owner-local outbox and receiver contract. The normative receiver contract is [Account Audit Ingress and Receipt](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt); see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for the producer's current implementation, proof, and gap status. Account logging for payment uses the existing RPC and `LogEvent` persistence path; it does not fabricate moderation fields, delete accounts, or stop sessions. Moderation mutation remains a separate explicit operator/admin operation. Focused tests prove the current log-event behavior and the absence of destructive account/session effects. +Logging & Admin's typed `CreateLogEvent` RPC is present but currently returns gRPC `UNIMPLEMENTED` without invoking the legacy generic `log_events` writer, so it is not an available ingress. Target account-audit receipt/readback persistence and focused receiver proof remain unimplemented; the normative receiver contract is [Account Audit Ingress and Receipt](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Account-creation audit delivery remains partial: the producer is still a post-commit best-effort effect rather than the target owner-local outbox, and it does not establish receiver durability or receipt confirmation; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for its current implementation, proof, and gap status. Account logging for payment uses the separate existing `LogEvent` RPC and persistence path; it does not fabricate moderation fields, delete accounts, or stop sessions. Moderation mutation remains a separate explicit operator/admin operation. Current status only: Logging & Admin exposes the non-destructive `EvaluateModerationPolicy` read and a gated/unavailable moderation-action seam; current focused proof is partial and covers bounded read, denied, and validation paths only. It does not cover target mutation or appeal workflows, or focused `CHAT_SEND` stale/unavailable dependency and owner-read failure cases. The remaining implementation and proof gaps are tracked against [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md) and [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md). From 3e9c9f72780d0c2a553f5b2980a4a4b88eedbae4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 00:22:49 +1300 Subject: [PATCH 60/75] Preserve event-ID audit readback and closed mutation diagnostics --- .../DatabaseInitialAdmissionBindOwnerService.java | 2 +- ...meplayAdmissionPointerEventRepositoryTest.java | 15 +++++++-------- .../GameSessionControlPlaneGrpcServiceTest.java | 2 +- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java index 81526a7066..55758189af 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java @@ -322,7 +322,7 @@ private InitialAdmissionBindOwnerProof readCommittedProof( GameplayAdmissionPointer pointer = maybePointer.get(); Optional maybeAudit = eventRepository - .findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc( + .findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( attempt.tenantId(), catalog.worldSlug(), catalog.realmSlug()) .stream() .filter(event -> Objects.equals(event.getId(), attempt.auditEventId())) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java index 6636c2b259..dda817c340 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java @@ -37,16 +37,15 @@ void savesCatalogRevisionAndStableIdentityAndKeepsUnknownValuesNull() throws Exc repository.save(historical); List events = - repository.findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc( - 9L, "demo", "production"); + repository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc(9L, "demo", "production"); assertEquals(2, events.size()); - assertEquals(12L, events.get(0).getCatalogRevision()); - assertEquals(realmId, events.get(0).getRealmId()); - assertEquals(namespaceId, events.get(0).getPlayableStateNamespaceId()); - assertNull(events.get(1).getCatalogRevision()); - assertNull(events.get(1).getRealmId()); - assertNull(events.get(1).getPlayableStateNamespaceId()); + assertNull(events.get(0).getCatalogRevision()); + assertNull(events.get(0).getRealmId()); + assertNull(events.get(0).getPlayableStateNamespaceId()); + assertEquals(12L, events.get(1).getCatalogRevision()); + assertEquals(realmId, events.get(1).getRealmId()); + assertEquals(namespaceId, events.get(1).getPlayableStateNamespaceId()); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index d9cefbada4..3626a44dfd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -1453,7 +1453,7 @@ public void onNext(SetAdmissionPointerResponse value) { } }); - assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); + assertEquals("FAILED_PRECONDITION", responseRef.get().getError().getCode()); assertEquals( "admission-pointer updates are temporarily disabled until catalog revision " + "preconditions are supported", From 8c906ac2e48fd5b9ea1594cb950315e06441e401 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 00:54:59 +1300 Subject: [PATCH 61/75] Align scoped tenant RPC identifiers and dual-revision CAS contract --- .../game-session-service/api-contracts.md | 2 + design/grpc-docs/grpc-api.md | 92 ++++++++++++++++++- .../v1/game_session_service.proto | 6 +- .../GameSessionControlPlaneGrpcService.java | 4 +- ...ameSessionControlPlaneGrpcServiceTest.java | 44 ++++++++- .../client/GameSessionControlPlaneClient.java | 5 +- .../GameSessionControlPlaneClientTest.java | 85 +++++++++++++++++ 7 files changed, 227 insertions(+), 11 deletions(-) create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClientTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 477970bf8c..2482628028 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -117,6 +117,8 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay **Target state:** Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent or `INACTIVE` under [Account's explicit membership lifecycle](../../decisions/adr-0025-explicit-open-enrollment-membership.md#decision). A public-production policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`; unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. **Current implementation:** text `PLAY` also returns `JOIN_REQUIRED` when a membership exists but `gameplayAdmissionAllowed=false`. It enforces the current non-public realm grant, while current connect-token issuance does not validate that grant; target connect-token issuance adds the same fresh grant gate. +- **Admission-pointer CAS inputs:** existing-row writes compare the exact `expectedPointerVersion` and `expectedCatalogRevision` pair. The current owner-local no-record insert uses `0/0` only as its database CAS precondition; it is not proof of realm/catalog initialization or permission to create a pointer. The `SetAdmissionPointer` and `ExecutePreparedVersionCutover` control-plane RPCs remain fail-closed until their complete owner contracts are supported. Initial admission still requires the separate World lifecycle, canonical realm/catalog identity, pointer/audit transaction, and exact owner-readback proof described in [Initial admission bind](#initial-admission-bind). + ### ADR-0048 operator-write contract **Target state:** every mutating operator RPC listed above (`StartSession`, `StopSession`, `RestartSession`, `ToggleFeatureFlag`, `PauseTicksForScope`, `ResumeTicksForScope`, `SetAdmissionPointer`, `ExecutePreparedVersionCutover`, and `PrepareVersionUpgrade`) requires the same durable request identity: `controlPlaneRequestId` plus the canonical `mutationDigest`. Account binds both values into the bounded operator authorization reference, and Game Session recomputes and validates the digest before execution. The owner durably records the request before execution and records a terminal result only after owner-specific commit proof; PostgreSQL-owned mutations commit domain state and result atomically, while Redis-backed projections use the durable claim, fenced mutation marker, and reconciliation contract in ADR 0048. A duplicate request carrying the same digest returns the previously committed result, while the same request identifier with a different digest returns `IDEMPOTENCY_CONFLICT` without applying either payload. A timeout must not create a new request identifier; Logging & Admin may use that identifier only for owner result lookup until the exact operation is reconciled. `FENCE_REJECTED` is non-rearmable and prohibits mutation redelivery. A retry against a current owner or fence is permitted only after the owner has durably recorded terminal `NOT_EXECUTED` proof for the original attempt; it uses a new `ownerMutationId` and a newly fenced attempt while retaining the external request tuple. After authorization expiry, reconciliation is read-only. diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 4a98b410d0..f103dc58ae 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -598,6 +598,8 @@ for conventions on schema evolution and error handling. See each service's - [TcpProxyService](#tcp_proxy-v1-TcpProxyService) - [world-management/v1/world_management_service.proto](#world-management_v1_world_management_service-proto) + - [AcquireInitialAdmissionBindHoldRequest](#world_management-v1-AcquireInitialAdmissionBindHoldRequest) + - [AcquireInitialAdmissionBindHoldResponse](#world_management-v1-AcquireInitialAdmissionBindHoldResponse) - [ActivatePreparedWorldInstanceRequest](#world_management-v1-ActivatePreparedWorldInstanceRequest) - [ActivatePreparedWorldInstanceResponse](#world_management-v1-ActivatePreparedWorldInstanceResponse) - [ApplyRoomAmbientStatePatchRequest](#world_management-v1-ApplyRoomAmbientStatePatchRequest) @@ -620,6 +622,7 @@ for conventions on schema evolution and error handling. See each service's - [GetWorldInstanceLifecycleRequest](#world_management-v1-GetWorldInstanceLifecycleRequest) - [GetWorldInstanceLifecycleResponse](#world_management-v1-GetWorldInstanceLifecycleResponse) - [HazardAmbientState](#world_management-v1-HazardAmbientState) + - [InitialAdmissionBindHold](#world_management-v1-InitialAdmissionBindHold) - [ListRoomOccupantsRequest](#world_management-v1-ListRoomOccupantsRequest) - [ListRoomOccupantsResponse](#world_management-v1-ListRoomOccupantsResponse) - [PingRequest](#world_management-v1-PingRequest) @@ -647,6 +650,7 @@ for conventions on schema evolution and error handling. See each service's - [DoorState](#world_management-v1-DoorState) - [EntityTemplateReferenceType](#world_management-v1-EntityTemplateReferenceType) - [HazardState](#world_management-v1-HazardState) + - [InitialAdmissionBindHoldStatus](#world_management-v1-InitialAdmissionBindHoldStatus) - [RoomOccupantType](#world_management-v1-RoomOccupantType) - [UpgradeValidationResult](#world_management-v1-UpgradeValidationResult) - [WorldDesignAggregateType](#world_management-v1-WorldDesignAggregateType) @@ -8092,7 +8096,7 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_ids | [int64](#int64) | repeated | Empty requires a global privileged caller for the all-tenant read. Non-empty IDs must be positive and individually authorized by the forwarded caller context. | +| tenant_ids | [string](#string) | repeated | Empty requires a global privileged caller for the all-tenant read. Current authority accepts only positive decimal values; UUID-form tenant IDs remain unsupported until owner storage migrates to the canonical UUID-string tenantId. Each current numeric ID must be individually authorized by the forwarded caller context. | @@ -11089,6 +11093,47 @@ Semantics and failure expectations: - Events may be delivered more than once; th + + +### AcquireInitialAdmissionBindHoldRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| version_id | [string](#string) | | | +| expected_active_lifecycle_epoch | [int64](#int64) | | | +| initial_admission_request_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| realm_uuid | [string](#string) | | | +| playable_state_namespace_uuid | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| expected_no_prior_pointer | [bool](#bool) | | | +| expected_catalog_revision | [int64](#int64) | | | + + + + + + + + +### AcquireInitialAdmissionBindHoldResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| hold | [InitialAdmissionBindHold](#world_management-v1-InitialAdmissionBindHold) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + ### ActivatePreparedWorldInstanceRequest @@ -11493,6 +11538,35 @@ Semantics and failure expectations: - Events may be delivered more than once; th + + +### InitialAdmissionBindHold + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| hold_id | [string](#string) | | | +| hold_fence | [string](#string) | | | +| tenant_id | [string](#string) | | | +| realm_uuid | [string](#string) | | | +| playable_state_namespace_uuid | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| game_instance_id | [string](#string) | | | +| version_id | [string](#string) | | | +| active_lifecycle_epoch | [int64](#int64) | | | +| initial_admission_request_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| expected_no_prior_pointer | [bool](#bool) | | | +| expected_catalog_revision | [int64](#int64) | | | +| status | [InitialAdmissionBindHoldStatus](#world_management-v1-InitialAdmissionBindHoldStatus) | | | +| diagnostic_expires_at_epoch_millis | [int64](#int64) | | | + + + + + + ### ListRoomOccupantsRequest @@ -11972,6 +12046,21 @@ Semantics and failure expectations: - Events may be delivered more than once; th + + +### InitialAdmissionBindHoldStatus + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| INITIAL_ADMISSION_BIND_HOLD_STATUS_UNSPECIFIED | 0 | | +| INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING | 1 | | +| INITIAL_ADMISSION_BIND_HOLD_STATUS_RECONCILIATION_REQUIRED | 2 | | +| INITIAL_ADMISSION_BIND_HOLD_STATUS_COMMITTED | 3 | | +| INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED | 4 | | + + + ### RoomOccupantType @@ -12103,6 +12192,7 @@ Semantics and failure expectations: - Events may be delivered more than once; th | ActivatePreparedWorldInstance | [ActivatePreparedWorldInstanceRequest](#world_management-v1-ActivatePreparedWorldInstanceRequest) | [ActivatePreparedWorldInstanceResponse](#world_management-v1-ActivatePreparedWorldInstanceResponse) | | | FailPreparedWorldInstance | [FailPreparedWorldInstanceRequest](#world_management-v1-FailPreparedWorldInstanceRequest) | [FailPreparedWorldInstanceResponse](#world_management-v1-FailPreparedWorldInstanceResponse) | | | GetWorldInstanceLifecycle | [GetWorldInstanceLifecycleRequest](#world_management-v1-GetWorldInstanceLifecycleRequest) | [GetWorldInstanceLifecycleResponse](#world_management-v1-GetWorldInstanceLifecycleResponse) | | +| AcquireInitialAdmissionBindHold | [AcquireInitialAdmissionBindHoldRequest](#world_management-v1-AcquireInitialAdmissionBindHoldRequest) | [AcquireInitialAdmissionBindHoldResponse](#world_management-v1-AcquireInitialAdmissionBindHoldResponse) | | | TerminateWorldInstance | [TerminateWorldInstanceRequest](#world_management-v1-TerminateWorldInstanceRequest) | [TerminateWorldInstanceResponse](#world_management-v1-TerminateWorldInstanceResponse) | | | GetRoom | [GetRoomRequest](#world_management-v1-GetRoomRequest) | [GetRoomResponse](#world_management-v1-GetRoomResponse) | | | GetRoomSnapshot | [GetRoomSnapshotRequest](#world_management-v1-GetRoomSnapshotRequest) | [GetRoomSnapshotResponse](#world_management-v1-GetRoomSnapshotResponse) | | diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index 34805ae962..40e4fe1961 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -425,8 +425,10 @@ message AdmissionPointerControlPlaneEntry { message ListAdmissionPointersRequest { // Empty requires a global privileged caller for the all-tenant read. - // Non-empty IDs must be positive and individually authorized by the forwarded caller context. - repeated int64 tenant_ids = 1; + // Current authority accepts only positive decimal values; UUID-form tenant IDs remain + // unsupported until owner storage migrates to the canonical UUID-string tenantId. + // Each current numeric ID must be individually authorized by the forwarded caller context. + repeated string tenant_ids = 1; } message ListAdmissionPointersResponse { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java index df6c70a823..39401f4940 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java @@ -269,7 +269,7 @@ public void listAdmissionPointers( } } - private List validateAdmissionPointerListScope(List tenantIds) { + private List validateAdmissionPointerListScope(List tenantIds) { if (tenantIds.isEmpty()) { requireAdminRole(); return List.of(); @@ -277,7 +277,7 @@ private List validateAdmissionPointerListScope(List tenantIds) { List validatedTenantIds = tenantIds.stream() - .map(tenantId -> ControlPlaneRequestParser.requirePositive(tenantId, "tenant_ids")) + .map(tenantId -> ControlPlaneRequestParser.parsePositiveLong(tenantId, "tenant_ids")) .toList(); for (long tenantId : validatedTenantIds) { if (!SessionContext.hasTenantAccess(tenantId)) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 3626a44dfd..45bacb0d93 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -1934,7 +1934,7 @@ void listAdmissionPointersAllowsScopedCallerOnlyForRequestedTenantBeforeAuditVal AtomicReference responseRef = new AtomicReference<>(); service.listAdmissionPointers( - ListAdmissionPointersRequest.newBuilder().addTenantIds(2L).build(), + ListAdmissionPointersRequest.newBuilder().addTenantIds("2").build(), new NoopObserver<>() { @Override public void onNext(ListAdmissionPointersResponse value) { @@ -1962,7 +1962,7 @@ void listAdmissionPointersRejectsScopedCallerRequestingAnotherTenant() { AtomicReference responseRef = new AtomicReference<>(); service.listAdmissionPointers( - ListAdmissionPointersRequest.newBuilder().addTenantIds(1L).build(), + ListAdmissionPointersRequest.newBuilder().addTenantIds("1").build(), new NoopObserver<>() { @Override public void onNext(ListAdmissionPointersResponse value) { @@ -2005,7 +2005,7 @@ void listAdmissionPointersRejectsMissingCallerContext() { AtomicReference responseRef = new AtomicReference<>(); service.listAdmissionPointers( - ListAdmissionPointersRequest.newBuilder().addTenantIds(2L).build(), + ListAdmissionPointersRequest.newBuilder().addTenantIds("2").build(), new NoopObserver<>() { @Override public void onNext(ListAdmissionPointersResponse value) { @@ -2027,7 +2027,7 @@ void listAdmissionPointersRejectsNonPositiveTenantScopeBeforeAuthorityLookup() { AtomicReference responseRef = new AtomicReference<>(); service.listAdmissionPointers( - ListAdmissionPointersRequest.newBuilder().addTenantIds(0L).build(), + ListAdmissionPointersRequest.newBuilder().addTenantIds("0").build(), new NoopObserver<>() { @Override public void onNext(ListAdmissionPointersResponse value) { @@ -2039,6 +2039,40 @@ public void onNext(ListAdmissionPointersResponse value) { Mockito.verifyNoInteractions(authorityService); } + @Test + void listAdmissionPointersRejectsMalformedTenantScopeBeforeAuthorityLookup() { + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + for (String tenantId : + List.of( + "", + " ", + "not-a-number", + "-1", + "9223372036854775808", + "550e8400-e29b-41d4-a716-446655440000")) { + responseRef.set(null); + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds(tenantId).build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertNotNull(responseRef.get()); + assertEquals("INVALID_ARGUMENT", responseRef.get().getError().getCode()); + } + + Mockito.verifyNoInteractions(authorityService); + } + @Test void listAdmissionPointersFailsClosedForMissingAuditInRequestedTenant() { SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); @@ -2054,7 +2088,7 @@ void listAdmissionPointersFailsClosedForMissingAuditInRequestedTenant() { AtomicReference responseRef = new AtomicReference<>(); service.listAdmissionPointers( - ListAdmissionPointersRequest.newBuilder().addTenantIds(2L).build(), + ListAdmissionPointersRequest.newBuilder().addTenantIds("2").build(), new NoopObserver<>() { @Override public void onNext(ListAdmissionPointersResponse value) { diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClient.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClient.java index 179f8f25c9..2d76ae0c4b 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClient.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClient.java @@ -87,7 +87,10 @@ protected GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlock public ListAdmissionPointersResponse listAdmissionPointers(List tenantIds) { return stub() .listAdmissionPointers( - ListAdmissionPointersRequest.newBuilder().addAllTenantIds(tenantIds).build()); + ListAdmissionPointersRequest.newBuilder() + .addAllTenantIds( + tenantIds.stream().map(tenantId -> Long.toString(tenantId)).toList()) + .build()); } public ListAdmissionPointerAuditResponse listAdmissionPointerAudit( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClientTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClientTest.java new file mode 100644 index 0000000000..7834e15fe6 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClientTest.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.loggingadmin.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.util.List; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ListAdmissionPointersRequest; +import net.firedevops.firemud.gamesession.v1.ListAdmissionPointersResponse; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class GameSessionControlPlaneClientTest { + + @Test + void listAdmissionPointersSendsTenantIdsAsDecimalStrings() throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + CommonGrpcClientProperties grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + ManagedChannel channel = mock(ManagedChannel.class); + GrpcChannelFactory channelFactory = + new GrpcChannelFactory() { + @Override + public ManagedChannel buildChannel( + String target, + int defaultPort, + CommonGrpcClientProperties properties, + boolean keepAlive) { + return channel; + } + }; + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub stub = + mock(GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub.class); + when(stub.listAdmissionPointers(any(ListAdmissionPointersRequest.class))) + .thenReturn(ListAdmissionPointersResponse.getDefaultInstance()); + TestGameSessionControlPlaneClient client = + new TestGameSessionControlPlaneClient(endpoints, grpc, channelFactory, stub); + + try { + client.initialize(); + client.listAdmissionPointers(List.of(2L, Long.MAX_VALUE)); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(ListAdmissionPointersRequest.class); + verify(stub).listAdmissionPointers(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getTenantIdsList()) + .containsExactly("2", Long.toString(Long.MAX_VALUE)); + } finally { + client.close(); + } + } + + private static final class TestGameSessionControlPlaneClient + extends GameSessionControlPlaneClient { + private final GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub + stub; + + private TestGameSessionControlPlaneClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub stub) { + super(endpoints, tlsProps, channelFactory, BlockingGrpcStubCustomizer.noop()); + this.stub = stub; + } + + private void initialize() throws Exception { + initReloadingClient(); + } + + @Override + protected GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub + buildStub(ManagedChannel channel) { + return applyStubCustomizer(stub); + } + } +} From f107f42f98190717779723004e6d01745ecb93eb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:39:10 +1300 Subject: [PATCH 62/75] Preserve prepared-proof availability and clarify owner CAS boundaries --- .../game-session-service/api-contracts.md | 2 +- .../logging-admin-service/api-contracts.md | 2 + .../logging-admin-service/runtime-and-data.md | 2 +- .../GameSessionControlPlaneGrpcService.java | 10 ++++ ...ameSessionControlPlaneGrpcServiceTest.java | 49 +++++++++++++++++++ .../src/main/resources/openapi.yaml | 6 +++ .../AdmissionPointerControllerTest.java | 24 ++++++++- .../impl/AdmissionPointerServiceImplTest.java | 27 ++++++++++ 8 files changed, 119 insertions(+), 3 deletions(-) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 2482628028..794f499de8 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -117,7 +117,7 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay **Target state:** Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent or `INACTIVE` under [Account's explicit membership lifecycle](../../decisions/adr-0025-explicit-open-enrollment-membership.md#decision). A public-production policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`; unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. **Current implementation:** text `PLAY` also returns `JOIN_REQUIRED` when a membership exists but `gameplayAdmissionAllowed=false`. It enforces the current non-public realm grant, while current connect-token issuance does not validate that grant; target connect-token issuance adds the same fresh grant gate. -- **Admission-pointer CAS inputs:** existing-row writes compare the exact `expectedPointerVersion` and `expectedCatalogRevision` pair. The current owner-local no-record insert uses `0/0` only as its database CAS precondition; it is not proof of realm/catalog initialization or permission to create a pointer. The `SetAdmissionPointer` and `ExecutePreparedVersionCutover` control-plane RPCs remain fail-closed until their complete owner contracts are supported. Initial admission still requires the separate World lifecycle, canonical realm/catalog identity, pointer/audit transaction, and exact owner-readback proof described in [Initial admission bind](#initial-admission-bind). +- **Admission-pointer CAS inputs:** existing-row writes compare the exact `expectedPointerVersion` and `expectedCatalogRevision` pair. The current owner-local no-record insert requires `0/0` as its expected-absent precondition; because no row exists to version-check, insert-race safety comes from runtime-target locking and database uniqueness constraints, not a row-version CAS. Neither condition is proof of realm/catalog initialization or permission to create a pointer. The `SetAdmissionPointer` and `ExecutePreparedVersionCutover` control-plane RPCs remain fail-closed until their complete owner contracts are supported. Initial admission still requires the separate World lifecycle, canonical realm/catalog identity, pointer/audit transaction, and exact owner-readback proof described in [Initial admission bind](#initial-admission-bind). ### ADR-0048 operator-write contract diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 7565974d15..b1bf8487ed 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -109,6 +109,8 @@ For every forwarded owner mutation, excluding the separate local `/moderation/ac The internal admission-pointer service/owner paths represent exactly one of two same-target Game Session control-plane operations for `{tenantId, worldSlug, realmSlug}`. These CAS operations and version-upgrade preparation are not public HTTP or OpenAPI capabilities; the supported public boundary is limited to admission-pointer reads, audit, and prepared-upgrade proof reads. +The current internal `SetAdmissionPointer` and `ExecutePreparedVersionCutover` request adapters carry both `expectedPointerVersion` and `expectedCatalogRevision`, forwarding the pair to Game Session. Game Session owns the exact comparison and expected-absent semantics; see the admission-pointer CAS inputs in its [gRPC contract](../game-session-service/api-contracts.md#grpc-apis). This request shape does not make either mutation available at public HTTP ingress or enable the complete owner write contracts. + - `OpenAdmissionPointer` performs `CLOSED -> OPEN(target)`. The target must exist, belong to `tenantId`, and be the prepared/active runtime for the same world and realm. It must pass current runtime lifecycle and entitlement/admission checks; display names, slugs, or a caller-supplied instance id are not proof of that relationship. If validation is unavailable or ambiguous, the operation fails closed. `preparedVersionUpgradeId` is forbidden because this operation cannot replace an already open target. - `CloseAdmissionPointer` performs `OPEN(target) -> CLOSED`. Game Session first checks the idempotency record for `controlPlaneRequestId`: an exact completed duplicate replays its original successful response and audit identity before current pointer-state validation. For a new request ID, the request must identify the exact currently open `gameInstanceId`; a missing pointer, already closed pointer, or different current target fails without mutation. Reusing a completed request ID with a different digest conflicts. Closing is a safety operation and therefore does not require the target to remain lifecycle- or entitlement-admissible. It cannot select a replacement target, and `preparedVersionUpgradeId` is forbidden. The resulting pointer makes no `gameInstanceId` gameplay-admissible while preserving the former target in audit evidence. - Both requests carry the complete routing identity, target `gameInstanceId`, expected route version (`expectedPointerVersion`), reason, and idempotent `controlPlaneRequestId`. The schema does not accept a client-supplied actor: the actor is derived server-side from the authenticated operator session or workload. The response and audit record expose that actor and the resulting monotonic `pointerVersion`. `pointerVersion` is the route version and CAS token for exactly `{tenantId, worldSlug, realmSlug}`. The write succeeds only when the stored version equals the expected version; otherwise it returns a conflict and leaves the route unchanged. An absent route record uses `expectedPointerVersion=0` for the first open rather than an unscoped blind write. diff --git a/design/architecture/microservices/logging-admin-service/runtime-and-data.md b/design/architecture/microservices/logging-admin-service/runtime-and-data.md index f58464631b..52a4809b29 100644 --- a/design/architecture/microservices/logging-admin-service/runtime-and-data.md +++ b/design/architecture/microservices/logging-admin-service/runtime-and-data.md @@ -31,7 +31,7 @@ The current shipped scope is narrower than this target contract: - The service exposes core admin investigation reads, saga inspection of Logging & Admin-local rows only, coordination-health reads, and a narrow log query whose current implementation reads only the service-owned PostgreSQL `log_events` table for an exact tenant plus case-insensitive message containment. Saga inspection does not aggregate adopter-local state; target cross-owner visibility requires owner read APIs plus a bounded aggregation/read model and must distinguish an unknown or unavailable adopter from an empty result. Moderation policy-input and report-persistence paths are only unsupported legacy transport/internal seams that hard fail closed or remain authorization-unproved; they are not exposed current capabilities. The service does not implement the target profile-aware indexed or console/journal query integrations, Kibana/Grafana clients, embedded dashboards, separate admin UI, or the complete target control-plane workflow for every recovery, regional, or aggregate operation. - The moderation policy-input and audit persistence mutation has present legacy transport stubs through `POST /moderation/actions` and the internal `ApplyModerationAction` gRPC ingress; after narrow tenant/admin checks they hard fail closed with HTTP `503 Service Unavailable` or an application-level gRPC `UNAVAILABLE` error, without dispatch or persistence. They are unsupported, nonconformant implementation drift and must not be wired or called as available mutations. They do not provide the target fixed-category policy-input/audit record or Account, Game Session, or Social & Groups enforcement state. Current execution performs no Account authorization-reference issuance or redemption, owner forwarding, or owner enforcement. Once its action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and Logging & Admin receiving-boundary validation/redemption are complete, Logging & Admin redeems the separate intent-persistence reference exactly once at its receiving boundary; that reference is never forwarded or reused and the path does not require owner-side authorization-reference redemption or enforcement. Any future owner-enforcement command uses a separately issued reference redeemed once by its receiving owner. The separate `EvaluateModerationPolicy` compatibility read remains live at the owner enforcement boundaries and carries no mutation authorization reference. Public administrative report persistence at `POST /admin/reports` is unavailable: the HTTP controller and Gateway route were removed because canonical authorization and live reference validation are not implemented. The internal `CreateReport` gRPC ingress is not public; its interim receiver guard requires an internal-service JWT naming `social-groups-service`, which the Social & Groups client emits, while certificate-derived exact workload/method authorization remains unproved. The reserved player-bootstrap `POST /reports` submission route is separate and also unavailable until its caller-bound subject and live tenant-membership checks exist. -- Admission-pointer reads, audit, and prepared-upgrade proof reads are implemented and live. Internal admission-pointer mutation, version-upgrade preparation, and prepared-cutover owner paths have implementation-participating surfaces, but the current pointer writer is read-then-write/nonconformant; the target atomic open/close CAS and prepared cutover remain unimplemented and externally unavailable behind internal trust boundaries, with public HTTP/Gateway write support unavailable and no current UI control. Target-only absent is reserved for operations with no executable owner path at all, such as quota-override mutations or future named typed recovery actions whose owner contracts do not yet exist. +- Admission-pointer reads, audit, and prepared-upgrade proof reads are implemented and live. Game Session's owner-local pointer persistence primitive now uses a row-locked dual-revision CAS and atomically persists the pointer and audit event. This primitive does not establish the complete operator write contracts: the `SetAdmissionPointer` and `ExecutePreparedVersionCutover` control-plane RPCs remain fail-closed, the target atomic open/close workflow and prepared cutover remain unsupported, and public HTTP/Gateway write support and UI controls remain unavailable. Version-upgrade preparation remains an internal owner path, not a public HTTP capability. Target-only absent is reserved for operations with no executable owner path at all, such as quota-override mutations or future named typed recovery actions whose owner contracts do not yet exist. - **Implemented but externally gated:** The per-instance tick pause/resume ingress is declared at the `` boundary, not a claim of live admin UI or automation, and no Logging & Admin forwarding method is callable. Its minimum schema/authorization gate is the action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and exact owner-side redemption/authentication and scope binding. That minimum gate only establishes that a typed request can be authorized for admission; it is not the complete execution contract. A forwarded tick mutation also remains unavailable until ADR 0048's complete durable, phase-qualified intent and authorization record, canonical `postAuthorizationExecutionTuple`, owner durable idempotency/result record, current owner/gameplay fence, and fenced no-accept/no-commit reconciliation proof are implemented and proved. Regional pause/resume and named regional recovery actions remain target-only behavior, with no claim that the target instance contract implicitly expands to a region or aggregate scope; they are tracked in [Game Session runtime and tick coordination](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#capability-status). - Logging & Admin consumes Game Session health and requests Game Session-owned control APIs; it does not directly mutate Redis or runtime coordination state. - Moderation policy intent, fixed-category case/audit data, bounded appeal cases/evidence, and operator history remain owned here, while Account, Game Session, and Social & Groups enforce their respective local restriction state. Active [ADR 0146](../../decisions/adr-0146-owner-local-moderation-enforcement.md) (mapped from reviewed archive record `archive-ADR-0133`) is the owner-local authority outcome: one typed digest-bound command reaches the enforcement owner, which commits monotonic local state, and routine boundary reads do not call Logging & Admin. Quota/limit override is hypothetical target UX only; no current Account owner mutation route exists. The legacy policy-input/audit transport stubs now hard fail closed before dispatch or persistence; they do not persist target fixed-category policy input or audit evidence, represent a domain-owner enforcement mutation, or provide target proof. Current execution performs no Account authorization-reference redemption. The current `EvaluateModerationPolicy` read is an implementation compatibility seam, not target authority; target owner commands and bounded appeal outcomes follow [Moderation Policies](./moderation-policies.md). Once the target persistence gate is complete, Logging & Admin validates and redeems its one separate intent-persistence reference exactly once for its own persistence path; it never forwards or reuses that reference. Future receiving enforcement owners redeem separately issued command-bound Account references and retain their own state. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java index 39401f4940..06bd5356e5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java @@ -1165,6 +1165,16 @@ public void getPreparedVersionUpgrade( responseObserver.onNext(response); responseObserver.onCompleted(); } catch (Exception ex) { + if (isPersistenceAvailabilityFailure(ex)) { + logger.warn("GetPreparedVersionUpgrade persistence unavailable", ex); + GetPreparedVersionUpgradeResponse response = + GetPreparedVersionUpgradeResponse.newBuilder() + .setError(admissionPointerAuthorityUnavailableError("GetPreparedVersionUpgrade")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + return; + } logger.error("GetPreparedVersionUpgrade failed", ex); GetPreparedVersionUpgradeResponse response = GetPreparedVersionUpgradeResponse.newBuilder() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 45bacb0d93..60ebc44767 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -9171,6 +9171,55 @@ public void onNext(GetPreparedVersionUpgradeResponse value) { } } + @Test + void getPreparedVersionUpgradeMapsRecognizedPersistenceAvailabilityFailures() { + List unavailableFailures = + List.of( + new org.jooq.exception.DataAccessException( + "prepared proof database unavailable", + new java.sql.SQLException("connection lost", "08006")), + new RuntimeException( + "wrapped prepared proof timeout", + new org.springframework.dao.QueryTimeoutException("query timed out"))); + + for (RuntimeException failure : unavailableFailures) { + AdmissionReadProofFixture fixture = admissionReadProofFixture(); + Mockito.when(fixture.preparationService().getPreparedVersionUpgrade(1L, "pvu-1")) + .thenThrow(failure); + SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); + + assertEquals( + "AUTHORITY_UNAVAILABLE", + invokeAdmissionReadProof( + fixture.service(), AdmissionReadProofOperation.PREPARED_VERSION, "1", "pvu-1")); + } + } + + @Test + void getPreparedVersionUpgradeKeepsUnexpectedPersistenceFailuresInternal() { + List unexpectedFailures = + List.of( + new IllegalStateException("prepared proof mapper failed"), + new org.jooq.exception.DataAccessException( + "prepared proof integrity failure", + new java.sql.SQLException("unique violation", "23505")), + new org.jooq.exception.DataAccessException( + "prepared proof query failure", + new java.sql.SQLException("malformed query", "42601"))); + + for (RuntimeException failure : unexpectedFailures) { + AdmissionReadProofFixture fixture = admissionReadProofFixture(); + Mockito.when(fixture.preparationService().getPreparedVersionUpgrade(1L, "pvu-1")) + .thenThrow(failure); + SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); + + assertEquals( + "INTERNAL", + invokeAdmissionReadProof( + fixture.service(), AdmissionReadProofOperation.PREPARED_VERSION, "1", "pvu-1")); + } + } + private static GameSessionControlPlaneGrpcService newService(GameInstanceRepository repository) { return newService(repository, new SimpleMeterRegistry()); } diff --git a/services/logging-admin-service/src/main/resources/openapi.yaml b/services/logging-admin-service/src/main/resources/openapi.yaml index 0aa7b8f048..c27b3af5a6 100644 --- a/services/logging-admin-service/src/main/resources/openapi.yaml +++ b/services/logging-admin-service/src/main/resources/openapi.yaml @@ -1810,6 +1810,12 @@ paths: $ref: '#/components/schemas/PreparedVersionUpgradeDto' error: $ref: '#/components/schemas/ErrorDetail' + '503': + description: Prepared version-upgrade proof authority is unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponseError' /admission-pointers/version-upgrades/{tenantId}/{sourceGameInstanceId}/compatibility/{targetVersionId}: get: summary: Read version cutover compatibility for one source instance and target version diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java index 89dba1c2c6..120fd6c603 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java @@ -122,7 +122,8 @@ void openApiDocumentsAdmissionPointerReadContracts() throws Exception { List.of( "/admission-pointers", "/admission-pointers/{tenantId}/{worldSlug}/{realmSlug}/audit", - "/admission-pointers/runtime-state/{tenantId}/{gameInstanceId}")) { + "/admission-pointers/runtime-state/{tenantId}/{gameInstanceId}", + "/admission-pointers/version-upgrades/{tenantId}/{preparationId}")) { Map admissionPointers = (Map) paths.get(path); Map getOperation = (Map) admissionPointers.get("get"); Map responses = (Map) getOperation.get("responses"); @@ -260,6 +261,27 @@ void getRuntimeStateReturnsCanonicalRuntimeState() throws Exception { .andExpect(jsonPath("$.data.currentAdmissionPointers[0].realmSlug").value("production")); } + @Test + void getPreparedVersionUpgradeMapsUnavailableAuthorityToServiceUnavailable() throws Exception { + when(admissionPointerService.getPreparedVersionUpgrade(2L, "pvu-1")) + .thenThrow( + new ResponseStatusException( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + "prepared version-upgrade proof authority unavailable")); + SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); + String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + + mockMvc + .perform( + get("/admission-pointers/version-upgrades/2/pvu-1") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.error.code").value("SERVICE_UNAVAILABLE")) + .andExpect( + jsonPath("$.error.message") + .value("prepared version-upgrade proof authority unavailable")); + } + @Test void getRuntimeStateRejectsCrossTenantScopedAdmin() throws Exception { SessionContext.setContext("user", List.of(), Map.of("8", List.of("tenantAdmin"))); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java index c42733f088..1bf7714885 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java @@ -486,6 +486,33 @@ void getPreparedVersionUpgradeRequiresAccessibleTenant() { ResponseStatusException.class, () -> service.getPreparedVersionUpgrade(8L, "pvu-1")); } + @Test + void getPreparedVersionUpgradeMapsUnavailableAuthorityToServiceUnavailable() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + when(gameSessionControlPlaneClient.getPreparedVersionUpgrade(any())) + .thenReturn( + GetPreparedVersionUpgradeResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("AUTHORITY_UNAVAILABLE") + .setMessage("prepared version-upgrade proof authority unavailable") + .build()) + .build()); + + ResponseStatusException ex = + assertThrows( + ResponseStatusException.class, () -> service.getPreparedVersionUpgrade(2L, "pvu-1")); + + assertEquals(503, ex.getStatusCode().value()); + assertEquals("prepared version-upgrade proof authority unavailable", ex.getReason()); + verify(gameSessionControlPlaneClient) + .getPreparedVersionUpgrade( + org.mockito.ArgumentMatchers.argThat( + request -> + request.getTenantId().equals("2") + && request.getPreparationId().equals("pvu-1"))); + } + @Test void validateInstanceCutoverCompatibilityReturnsCanonicalControlPlaneProof() { SessionContext.setContext("42", List.of("platformAdmin"), Map.of()); From 5cbea7012cbd327a9a02f845c64ad7e0f1a0fd65 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:19:49 +1300 Subject: [PATCH 63/75] Align admission CAS status and add PostgreSQL transaction proof --- .../service-responsibility-matrix.md | 6 +- .../system-architecture-authz-route-matrix.md | 2 +- .../system-architecture-overview.md | 2 +- .../system-architecture-versioning-runtime.md | 2 +- .../realm-routing-and-playable-state.md | 6 +- ...sionPointerCasPostgresIntegrationTest.java | 296 ++++++++++++++++++ 6 files changed, 305 insertions(+), 9 deletions(-) create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java diff --git a/design/architecture/service-responsibility-matrix.md b/design/architecture/service-responsibility-matrix.md index 95ba5eaa98..111aa4d999 100644 --- a/design/architecture/service-responsibility-matrix.md +++ b/design/architecture/service-responsibility-matrix.md @@ -12,7 +12,7 @@ The matrix below is the target participation and ownership contract. `Authoritat - Live external operator availability includes the Gateway edge plus Logging & Admin domain ingress for reads, investigation, admission-pointer reads/audit, and prepared-upgrade proof reads. TCP Proxy does not participate in this HTTP operator read/proof-read path. `EvaluateModerationPolicy` is a separate live internal owner-boundary read consumed by Game Session and Social & Groups, not external operator availability. The target mutation rows below are normative contracts, not claims that every listed mutation is currently routable. - The service-local `/moderation/actions` and `ApplyModerationAction` paths are present legacy transport stubs that hard fail closed after narrow tenant/admin checks, without dispatch or persistence; they are unavailable at external Gateway ingress, persist no separate fixed-category audit evidence, and perform no owner-side enforcement. The target path remains gated pending the action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and Logging & Admin receiving-service validation/redemption. Synchronous `EvaluateModerationPolicy` consumption at `GAMEPLAY_ADMISSION` and `CHAT_SEND` remains a separate live owner-boundary read for Game Session and Social & Groups; those services own gameplay/chat enforcement, while Logging & Admin retains policy-input responsibility rather than consuming those enforcement decisions. -- Feature-flag overrides and scoped per-instance tick pause/resume are implemented-but-externally-gated ingress stubs pending their action-family schemas, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance/redemption flow and, where applicable, the target-only `privileged_control` issuance flow. That minimum gate is necessary but not sufficient for live success: supported owner execution also requires the complete durable, idempotent, fenced contract in [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md). Version-upgrade preparation and admission-pointer CAS/cutover have internal implementation-participating, nonconformant preparation/read-then-write/prepared-cutover seams, but their public HTTP/operator mutation paths are target-only absent because no public route or Gateway write forwarding exists; the target atomic open/close CAS and prepared cutover remain unimplemented. Broader guarded tick enumeration, regional mutation, and reset/remediate orchestration remain target-only. +- Feature-flag overrides and scoped per-instance tick pause/resume are implemented-but-externally-gated ingress stubs pending their action-family schemas, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance/redemption flow and, where applicable, the target-only `privileged_control` issuance flow. That minimum gate is necessary but not sufficient for live success: supported owner execution also requires the complete durable, idempotent, fenced contract in [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md). Version-upgrade preparation and admission-pointer CAS/cutover have internal implementation-participating seams; the pointer persistence primitive now checks both expected revisions under a row lock and commits pointer plus audit atomically, but public HTTP/operator mutation paths remain unavailable because no public route or Gateway write forwarding exists. Full prepared-cutover execution and target open/close behavior remain unimplemented; see the [Realm Routing implementation tracker](../project-management/implementation-tracking/realm-routing-and-playable-state.md). Broader guarded tick enumeration, regional mutation, and reset/remediate orchestration remain target-only. - Game Session `/sessions*` routes are current owner-local hooks; direct owner edge exposure is denied. The target external lifecycle ingress is `Gateway -> Logging & Admin -> Game Session` owner RPCs, but lifecycle forwarding is target-only and non-routable until its owner contract, minimum schema/authorization gate, and [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md)'s complete durable, idempotent, fenced owner-execution contract exist. No complete current external `/sessions*` family is claimed. - Versioned moderation propagation, hypothetical quota overrides, and broader tick remediation remain target-only/non-routable coverage without current executable owner routes. They cannot be exposed through Gateway or treated as Logging & Admin forwarding routes until the owning service contract and minimum schema/authorization gate exist, together with [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md)'s complete durable, idempotent, fenced owner-execution contract for any family that forwards to an owner. The currently supported ingress remains limited to the live reads, investigation, admission-pointer reads/audit, prepared-upgrade proof reads, and internal owner-boundary moderation evaluation listed above; this target-only status does not remove or widen those current paths. - The causal-read fence/composite room-view row is target-state only: current proto/request paths remain floor-free, and implementation/proof are unimplemented. See [ADR 0059](./decisions/adr-0059-causal-floor-cross-service-presentation-reads.md) and the [world-runtime-and-movement tracker](../project-management/implementation-tracking/world-runtime-and-movement.md) for current status. The accepted responsibility split remains Game Session allocation, Game Logic composition, and World Management/Entity Management participant provision. @@ -91,7 +91,7 @@ The matrix below is the target participation and ownership contract. `Authoritat | Authoritative owner: `versionStateEpoch` CAS enforcement | ✔ | | | | | | | | | | | | Version-state CAS API invocation for activation/rollback (`versionStateEpoch`) | ✔ | | | ✔ | | | | | ✔ | | | | Live admission-pointer reads/audit and prepared-upgrade proof reads (non-mutating; Account participates only in external read authorization, Gateway provides the edge, Logging & Admin provides domain ingress, and Game Session supplies owner state; mutation action-family schemas, `mutationDigest/v1` vectors, authorization references, and ADR 0048 owner execution are not prerequisites for these reads) | | | ✔ | ✔ | | | | | ✔ | | ✔ | -| Authoritative owner: Game Session internal version-upgrade preparation, read-then-write admission-pointer update, and prepared-cutover execution seams (nonconformant and externally gated; an action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account-issued authorization references with receiving-owner redemption, and the complete durable, idempotent, fenced owner-execution contract in [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md) are required before any supported preparation or write execution); target atomic open/close `pointerVersion` CAS and atomic prepared-cutover commit remain unimplemented and externally unavailable | | | | ✔ | | | | | | | | +| Authoritative owner: Game Session internal version-upgrade preparation, dual-revision conditional pointer update with atomic pointer/audit persistence, and prepared-cutover execution seams (publicly unavailable; an action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account-issued authorization references with receiving-owner redemption, and the complete durable, idempotent, fenced owner-execution contract in [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md) are required before supported external execution); target open/close `pointerVersion` CAS and atomic prepared-cutover commit remain unimplemented and externally unavailable | | | | ✔ | | | | | | | | | External version-upgrade preparation and admission-pointer open/close or prepared-cutover mutation ingress (target-only absent; the action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account-issued authorization reference and receiving-owner redemption, and complete ADR 0048 owner execution are mandatory before support; Gateway and Logging & Admin participation is target-state only, and all current mutation ingress remains unavailable) | | | ✔ | ✔ | | | | | ✔ | | ✔ | | Runtime feature-flag truth and override participation (Game Session owns runtime truth) | | | | ✔ | | | | | ✔ | | | | Tick & coordination health metrics (diagnostic scope: ``) | | | | ✔ | | | | | | | | @@ -176,7 +176,7 @@ The moderation policy-intent row assigns target `POST /moderation/actions` polic ## Notes on Redis Ownership and Participation -- **Independent version and admission CAS domains** – Game Design Service owns the version lifecycle state and `versionStateEpoch` CAS contract used for activation and rollback. Game Session and Logging & Admin may invoke that typed lifecycle API through their documented control-plane paths, but neither owns the version epoch. Game Session owns the admission-pointer read/preparation implementation and internal pointer-write/prepared-cutover surfaces for `{tenantId, worldSlug, realmSlug}`; the current writer is read-then-write/nonconformant, while the target atomic open/close `pointerVersion` CAS and prepared cutover remain unimplemented and externally unavailable. Gateway participates at the edge for operator/proof reads and write ingress, while Logging & Admin is the domain ingress for the gated target operation. Neither edge participation nor operator ingress transfers authority from Game Session. The two CAS tokens are independent and must not be substituted for one another. +- **Independent version and admission CAS domains** – Game Design Service owns the version lifecycle state and `versionStateEpoch` CAS contract used for activation and rollback. Game Session and Logging & Admin may invoke that typed lifecycle API through their documented control-plane paths, but neither owns the version epoch. Game Session owns admission-pointer reads/preparation and the internal pointer persistence primitive for `{tenantId, worldSlug, realmSlug}`; that primitive checks both expected revisions under a row lock and commits pointer plus audit atomically, but it does not provide public open/close or complete prepared-cutover support. Canonical realm-ID addressing, explicit `CLOSED`, World hold/lifecycle fencing, and bounded drain remain gaps; see the [Realm Routing implementation tracker](../project-management/implementation-tracking/realm-routing-and-playable-state.md). Gateway participates at the edge for operator/proof reads and write ingress, while Logging & Admin is the domain ingress for the gated target operation. Neither edge participation nor operator ingress transfers authority from Game Session. The two CAS tokens are independent and must not be substituted for one another. - **Authoritative owner: Coordination Redis gameplay sessions (`session:game:*`)** – Game Session Service owns gameplay session bindings, lifecycle, and reset scope expectations for these keys. Other services participate only through documented shared helper libraries and key contracts; they do not introduce new gameplay session prefixes or modify TTLs/payload semantics without Game Session ownership and Redis design review. - **Authoritative owner: Coordination Redis gameplay coordination keys (`tick:*`, generic `timer:*`, `retry:*`, `tick-executor-lease:*`, and the target-only, once-implemented Game Session-produced `tick-events:{tenantRegionTag}` stream)** – Game Session Service owns gameplay coordination schema and lifecycle for these prefixes. Generic `timer:*` excludes Automation's `automation:timer:*` and `script-scheduler:*` families. Other services participate only through documented shared helper libraries and key contracts; they do not introduce new gameplay coordination prefixes or modify TTLs/payload semantics without Game Session ownership and Redis design review. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 16bd938db0..25a18328a2 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -229,7 +229,7 @@ For every first public-production text entry, the target command sequence is `LO | Logging & Admin | `POST /feature-flags/toggle`, `POST /tick-remediation/pause`, `POST /tick-remediation/resume` | `tenant_regular` operator ingress | **Target; not currently routable.** Exact `control-ui` profile and current operator role. Tenant-role branches require live membership and membership-generation freshness; privileged global-role branches require live `current_global_role` and `role_appropriate_assurance`, while the global `platformAdmin` branch uses target-tenant generation without target membership. Each mutation also requires its action schema, shared `mutationDigest/v1` golden vectors, and Account authorization-reference issuance/redemption before enablement. | | Logging & Admin | `POST /moderation/actions` | `tenant_regular` operator ingress for `gameplay_ban`, `chat_mute`, and `chat_ban`; `account_scoped` platform-jurisdiction ingress for `platform_access_ban` | **Target; unavailable/gated.** The closed `action` selector selects exactly one matrix variant and rejects `account_security_lock`, unknown, and legacy values before branch authorization. Tenant-scoped categories retain the `tenant_regular` branch: `moderator`, `tenantAdmin`, and `platformAdmin` use the existing tenant membership/tenant-generation or global target-tenant-generation consequences. `platform_access_ban` uses the separate `account_scoped` branch: only global `platformAdmin` with `privileged_control`, explicit global target-account binding and platform scope, no `tenantId`, no tenant billing generation, and no membership or tenant-generation checks. Both variants link the root moderation policy-intent authorization contract: Logging & Admin redeems the local Account reference at its receiving boundary; any later owner-enforcement command uses a distinct identity/digest/reference/fingerprint and is redeemed by the selected owner. Target mutation contract: `durable_intent_then_moderation_record_idempotency`. Account remains the enforcement owner for the global restriction; target Game Session and Social & Groups enforcement reads the applicable owner-local durable restriction state or projection. **Current compatibility drift:** both consumers instead call the live `EvaluateModerationPolicy` read at their enforcement boundaries; that read is not a second target moderation authority. Owner-enforcement command coverage remains a recorded gap. | | Logging & Admin | `POST /reports` | `player_bootstrap_tenant` | **Target-only; not currently routable.** Accepts caller-bound `player-bootstrap`, derives `tenantId` and `reporterAccountId` from the authenticated caller and live membership, applies `moderation_report_policy`, and writes a caller-bound durable report record. | -| Logging & Admin | `CreateLogEvent` | `internal_workload` Account audit ingress | **Target-only; receiver and proof unavailable.** The target accepts only the exact Account Service workload mTLS identity (`spiffe://firemud/ns/{namespace}/sa/account-service`), with no bearer token or operator role. The current placeholder retains `AdminRoleGuard` denial ordering and returns `UNAVAILABLE` for authorized callers without dispatching or writing a receipt; the target receiver, PostgreSQL runtime, and direct end-to-end proof remain unavailable. | +| Logging & Admin | `CreateLogEvent` | `internal_workload` Account audit ingress | **Target-only; receiver and proof unavailable.** The target accepts only the exact Account Service workload mTLS identity (`spiffe://firemud/ns/{namespace}/sa/account-service`), with no bearer token or operator role. The current handler returns gRPC `UNIMPLEMENTED` before request validation, dispatch, or receipt writing; it does not implement the target typed Account receipt capability. The target receiver, PostgreSQL runtime, and direct end-to-end proof remain unavailable. | | Logging & Admin | `ReadLogEventReceipt` | `internal_workload` Account audit receipt readback | **Target-only; handler and proof unavailable.** The target uses the same exact Account Service mTLS-only caller boundary and no bearer token or operator role, then reads the receipt by the complete immutable envelope tuple. The current service has no read handler and returns gRPC `UNIMPLEMENTED`; receipt readback, PostgreSQL runtime, and direct end-to-end proof remain unavailable. | | Logging & Admin | `POST /admission-pointers`, `POST /admission-pointers/cutover`, `POST /admission-pointers/version-upgrades` | `tenant_regular` operator ingress | **Target; not currently routable.** This is a target inventory row only: the public OpenAPI surface no longer exposes the admission-pointer open/close/cutover mutations, and the remaining controller/owner paths are implementation drift. The `GET` read/audit/proof-read routes remain live; the `POST` preparation operation is separately gated. Exact `control-ui` profile and current operator role are required for any future ingress. Tenant-role branches require live membership and membership-generation freshness; privileged global-role branches require live `current_global_role` and `role_appropriate_assurance`, while the global `platformAdmin` branch uses target-tenant generation without target membership. Action schemas, shared `mutationDigest/v1` vectors, and Account authorization-reference issuance/redemption are required before external support; the global branch additionally requires target-only `privileged_control`. | | Game Session Service | `ToggleFeatureFlag`, `PauseTicksForScope`, `ResumeTicksForScope`, `SetAdmissionPointer`, `PrepareVersionUpgrade`, `ExecutePreparedVersionCutover` | `internal_workload` mirrored owner RPCs | **Target; not currently routable.** Exact Logging & Admin mTLS workload identity plus an Account-redeemed bounded operator authorization reference; no end-user JWT. These owner RPCs cannot be enabled until the corresponding action schema, shared `mutationDigest/v1` golden vectors, and Account authorization-reference issuance/redemption flow exist. | diff --git a/design/architecture/system-architecture-overview.md b/design/architecture/system-architecture-overview.md index 24d7824cf3..437e7a628c 100644 --- a/design/architecture/system-architecture-overview.md +++ b/design/architecture/system-architecture-overview.md @@ -15,7 +15,7 @@ Replacement and authoring boundaries are likewise explicit: durable playable sta This overview is target-state canonical; implementation coverage is partial and must not be inferred from the target tables alone. The current operator-control boundary is: - Runtime feature-flag overrides and scoped tick `PauseTicks`/`ResumeTicks` have implemented Logging & Admin ingress stubs that hard fail closed; the former Logging & Admin forwarding clients/methods are removed, so no forwarding path is currently callable. Game Session retains runtime and coordination mutation authority. These owner mutations are not canonically supportable or externally enableable until the minimum schema/authorization gate and the complete durable, idempotent, fenced owner-execution contract in [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md) exist and are consumed and proved by every participant. -- Admission-pointer reads and audit have implemented Logging & Admin paths. Live prepared-upgrade proof reads are distinct from the internal Game Session preparation handlers (`PrepareVersionUpgrade` and `ValidateInstanceCutoverCompatibility`); neither read nor preparation handler is an admission-pointer CAS/cutover mutation. Separate internal pointer-write and prepared-cutover implementation-participating surfaces exist behind internal trust boundaries but remain nonconformant and externally unavailable: the current writer is a read-then-write/separate-repository path rather than the target atomic boundary. The target atomic admission-pointer open/close CAS and prepared cutover, including explicit `CLOSED` handling, remain unimplemented and must not be read as a current external support claim. See [Versioning & Runtime Configuration](./system-architecture-versioning-runtime.md) for the canonical owner contract. +- Admission-pointer reads and audit have implemented Logging & Admin paths. Live prepared-upgrade proof reads are distinct from the internal Game Session preparation handlers (`PrepareVersionUpgrade` and `ValidateInstanceCutoverCompatibility`); neither read nor preparation handler is an admission-pointer CAS/cutover mutation. The owner-local pointer persistence primitive now checks the expected `{pointerVersion, catalogRevision}` under a row lock, conditionally updates against both prior values, and commits the pointer with its audit event in one transaction. This does not enable external pointer mutation or prove full prepared cutover: those paths remain fail-closed/unavailable, the current route remains positive-target-only rather than supporting explicit `CLOSED`, and canonical `{tenantId, realmId}` addressing plus World hold, lifecycle fencing, and bounded source drain remain gaps. See the [Realm Routing implementation tracker](../project-management/implementation-tracking/realm-routing-and-playable-state.md) for current status and [Versioning & Runtime Configuration](./system-architecture-versioning-runtime.md) for the owner contract. - Public administrative report persistence is currently unavailable. The unsafe Logging & Admin HTTP controller and `/api/admin/reports/**` Gateway route were removed because canonical authorization and live reference-validation checks are not implemented. The internal report gRPC contract remains separate behind its existing workload boundary; the target player-bootstrap submission route is also unavailable. - Moderation action persistence and audit are currently gated/unavailable: `POST /moderation/actions` and `ApplyModerationAction` are present legacy transport stubs that hard fail closed after narrow tenant/admin checks, without dispatch or persistence; separate fixed-category audit evidence and owner-side enforcement are absent, and no Gateway moderation route exposes this local REST/gRPC path. The separate `EvaluateModerationPolicy` read remains live at the Game Session and Social & Groups owner boundaries (`GAMEPLAY_ADMISSION` and `CHAT_SEND`), with applicable high-risk decisions failing closed when fresh policy evidence is unavailable. That compatibility seam is a legacy, deny-only lookup over generic action rows ordered by recency; it is nonconformant with ADR 0141's broadest-effect response precedence (`platform_access_ban` over `account_security_lock`, `chat_ban` over `chat_mute`) and does not implement or prove all five fixed categories or their independent lifecycles. For chat, that current fail-closed seam covers only new sends: the current effect replay can return before the policy read and lacks authenticated-caller and request-digest binding, so chat retry/replay remains an explicit implementation gap. Target state uses the fixed categories and owner-local durable enforcement commands defined in [Moderation Policies](./microservices/logging-admin-service/moderation-policies.md) and active [ADR 0146](./decisions/adr-0146-owner-local-moderation-enforcement.md) (mapped from reviewed archive record `archive-ADR-0133`), with lifecycle rules from [ADR 0141](./decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md) and appeals from [ADR 0142](./decisions/adr-0142-bounded-moderation-appeal-cases.md); complete persistence, owner command delivery, enforcement, and appeal handling remain missing. - Quota override is a hypothetical target overlay on Account entitlements; no current OpenAPI route or Account owner mutation contract exists. diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index 883588f441..b14e4f8fd0 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -12,7 +12,7 @@ FireMUD's target state treats versioned publishing, release attestation, runtime ## Implementation Status -The versioned publish and replacement-cutover substrate is partially implemented, including durable cutover preparation and execution records. The current admission-pointer writer performs a read-then-write version check and persists pointer, audit, and prepared-upgrade execution changes through separate repository calls; it does not yet prove the target single-transaction compare-and-set boundary described below. Current cutover implementation drift is also explicit: it clears active bindings rather than preserving them through the target bounded source-drain sequence of a persisted deadline, World Management lifecycle fence with confirmed command rejection, one bounded notice attempt after that fence, unconditional socket closure, and terminal `InstanceTermination` workflow. Notice failure never keeps source sockets open or delays termination. Current Game Session pin reads and the live `EnqueueAutomationCommandIfAbsent` handoff now carry the script patch, positive epoch, and owner request evidence; Game Session rejects incomplete or stale tuples at handoff, while current Automation instance-bound ingress, timer, and work-item admission paths also reject same-version work from an older epoch. Append-only request-idempotent rollout history, complete source/target command identity, and remote final-effect fencing remain implementation/proof gaps; Automation rollout rows/events remain synthetic, non-authoritative projections. The target sections that follow are normative design, not proof that the current runtime already satisfies those effects. +The versioned publish and replacement-cutover substrate is partially implemented, including durable cutover preparation and execution records. The current Game Session admission-pointer persistence primitive checks the expected `{pointerVersion, catalogRevision}` under a row lock, performs an existing-row conditional update against both prior values, and commits the pointer and audit event in one transaction. This owner-local pointer/audit boundary does not make public `SetAdmissionPointer` or `ExecutePreparedVersionCutover` callable, and prepared-upgrade execution is still recorded outside the pointer transaction; the full target prepared-cutover boundary is not proved. Explicit `CLOSED`, canonical `{tenantId, realmId}` addressing, World Management hold/lifecycle fencing, and bounded source drain remain gaps. Current cutover implementation drift is also explicit: it clears active bindings rather than preserving them through the target bounded source-drain sequence of a persisted deadline, World Management lifecycle fence with confirmed command rejection, one bounded notice attempt after that fence, unconditional socket closure, and terminal `InstanceTermination` workflow. Notice failure never keeps source sockets open or delays termination. Current Game Session pin reads and the live `EnqueueAutomationCommandIfAbsent` handoff now carry the script patch, positive epoch, and owner request evidence; Game Session rejects incomplete or stale tuples at handoff, while current Automation instance-bound ingress, timer, and work-item admission paths also reject same-version work from an older epoch. Append-only request-idempotent rollout history, complete source/target command identity, and remote final-effect fencing remain implementation/proof gaps; Automation rollout rows/events remain synthetic, non-authoritative projections. The target sections that follow are normative design, not proof that the current runtime already satisfies those effects. Historical Game Design migration status is also unresolved: `V5__update_version_table.sql` dropped the legacy `version.revision_ids` relationship, and `V17__revision_version_scope.sql` later assigned each tenant's revisions to its latest version. The current lineage therefore cannot prove immutable revision/version history. This is a retained-data deployment blocker: an affected deployment must first record either a verified no-data boundary or an explicit retained-row disposition/mapping, with exact readback and revision/version lineage evidence. No recovery is implied for already-dropped arrays; future migration/proof remediation remains required, and this status does not invent a replacement lineage design. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 8ba8f6173d..312b47c08c 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for realm routing and playable st ## Current Status -The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) remains target-only and unimplemented; Account issuance/validation and Game Session transport-local scope retention, retry, terminal-outcome, and expiry behavior still need implementation and proof. The complete routing boundary remains partial: persisted routes cannot represent explicit `CLOSED`, catalog and route revisions are combined, the key is not tenant-qualified, version checking is not an atomic database CAS, prepared-cutover execution is recorded after the pointer transaction, and active bindings are invalidated from current pointer state rather than ending through the target bounded drain. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. +The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) remains target-only and unimplemented; Account issuance/validation and Game Session transport-local scope retention, retry, terminal-outcome, and expiry behavior still need implementation and proof. The complete routing boundary remains partial: persisted routes require a positive runtime target and cannot represent explicit `CLOSED`; the current proto/repository key remains `{tenantId, worldSlug, realmSlug}` rather than canonical `{tenantId, realmId}`; public pointer mutation and prepared-cutover RPCs remain fail-closed; and pointer-plus-audit persistence does not establish the full prepared execution/cutover boundary. World hold, source drain, lifecycle fencing, and the target bounded active-session drain remain gaps; current active bindings are invalidated from pointer state. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. ## Packet 4 Status and Proof Gaps @@ -35,9 +35,9 @@ These links add decision provenance only; they do not upgrade routing or playabl ### Authority and Pointer Contract -Players address a visible `{tenantId, worldSlug, realmSlug}` realm, never a raw `gameInstanceId`. Game Session persists `gameplay_admission_pointer` rows and append-only audit events. The current row always requires one positive runtime target and cannot yet express the target `CLOSED` state. It combines runtime target, visibility/public-production classification, display metadata, `stateScope`, character-selection requirements, and character-creation policy under one `pointerVersion`; the target separates catalog revision from runtime routing. +Players address a visible `{tenantId, worldSlug, realmSlug}` realm, never a raw `gameInstanceId`. Game Session persists `gameplay_admission_pointer` rows and append-only audit events. The current row always requires one positive runtime target and cannot yet express the target `CLOSED` state. `pointerVersion` tracks runtime-target changes while `catalogRevision` tracks catalog/policy changes; see the [Versioning & Runtime Configuration owner status](../../architecture/system-architecture-versioning-runtime.md#implementation-status) for the current persistence boundary and remaining cutover gaps. -Selectors resolve to a tenant-local durable `realmId` before direct pointer authority is read. The target canonical singular key is `{tenantId, realmId}`; `GetAdmissionPointer(tenantId, realmId)` reads direct pointer authority using that key and does not reconstruct authority through browse projection. The current Game Session proto and `GameplayAdmissionPointerAuthorityService` still use `{tenantId, worldSlug, realmSlug}` slug lookup; realm-ID lookup and caller support remain implementation drift and are not claimed as live. Target Account bootstrap admission, public-production membership creation, prepared cutover validation, live admission, and operator audit reads use the same resolved realm identity. Membership join and connect-token issuance have separate idempotency contracts: each binds its own `requestId` to its operation, caller, verified discovery scope, and resolved target digest, and the two request IDs are not interchangeable. Current pointer writes use a tenant-qualified slug lookup and may compare `expectedPointerVersion` after that read, but the repository then updates by row ID without a version predicate. This is not an atomic CAS under concurrent writers. The baseline migration also defines the unique pointer index as `(world_slug, realm_slug)` without `tenant_id`, so persistence has not converged with the target `{tenantId, realmId}` key. +Selectors resolve to a tenant-local durable `realmId` before direct pointer authority is read. The target canonical singular key is `{tenantId, realmId}`; `GetAdmissionPointer(tenantId, realmId)` reads direct pointer authority using that key and does not reconstruct authority through browse projection. The current Game Session proto and `GameplayAdmissionPointerAuthorityService` still use `{tenantId, worldSlug, realmSlug}` slug lookup; realm-ID lookup and caller support remain implementation drift and are not claimed as live. Target Account bootstrap admission, public-production membership creation, prepared cutover validation, live admission, and operator audit reads use the same resolved realm identity. Membership join and connect-token issuance have separate idempotency contracts: each binds its own `requestId` to its operation, caller, verified discovery scope, and resolved target digest, and the two request IDs are not interchangeable. The current persistence primitive checks the expected `{pointerVersion, catalogRevision}` under a row lock, conditionally updates an existing row against both prior values, and commits the pointer with its audit event in one transaction. This is owner-local persistence proof, not public mutation or full prepared-cutover support; see the [Versioning & Runtime Configuration owner status](../../architecture/system-architecture-versioning-runtime.md#implementation-status). V2 enforces tenant-local selector uniqueness, but persistence has not converged on canonical `{tenantId, realmId}` addressing or retained catalog-to-realm mapping. Startup seeds pointers only when the persisted store is empty, using dedicated bootstrap pointer-seed properties. After seeding, runtime reads and mutations use persisted pointer authority. `GameplayCatalogProperties` is not production routing authority: Game Session's production catalog projection is pointer-backed, Account Service no longer ships the old local catalog config, and property-to-catalog construction remains only in explicit test support. diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java new file mode 100644 index 0000000000..dd90558f13 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java @@ -0,0 +1,296 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.service.impl.DatabaseGameplayAdmissionPointerAuthorityService; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameplayAdmissionPointerCasPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final long TENANT_ID = 419L; + private static final long INITIAL_GAME_INSTANCE_ID = 8201L; + private static final String WORLD_SLUG = "cas-world"; + private static final String REALM_SLUG = "cas-realm"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @BeforeEach + void migrateIsolatedContainerSchema() { + DriverManagerDataSource dataSource = dataSource(); + Flyway flyway = + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .cleanDisabled(false) + .load(); + flyway.clean(); + flyway.migrate(); + } + + @Test + void competingWritersWithSamePositiveVersionPairCommitOnePointerAndAudit() throws Exception { + Fixture fixture = fixture(); + GameplayAdmissionPointerSnapshot initial = + fixture + .transactionTemplate() + .execute( + status -> + fixture + .service() + .upsertPointer( + mutation( + "Initial World", + INITIAL_GAME_INSTANCE_ID, + 0L, + 0L, + "initial-pointer"))); + assertThat(initial).isNotNull(); + assertThat(initial.pointerVersion()).isEqualTo(1L); + assertThat(initial.catalogRevision()).isEqualTo(1L); + assertThat(fixture.service().listPointerAudit(TENANT_ID, WORLD_SLUG, REALM_SLUG)).hasSize(1); + + CountDownLatch transactionsReady = new CountDownLatch(2); + CountDownLatch startWriters = new CountDownLatch(1); + ExecutorService executor = + Executors.newFixedThreadPool( + 2, + task -> { + Thread thread = new Thread(task, "admission-pointer-cas-test"); + thread.setDaemon(true); + return thread; + }); + Future first = + submitMutation( + executor, + fixture, + transactionsReady, + startWriters, + mutation("Concurrent World A", INITIAL_GAME_INSTANCE_ID, 1L, 1L, "writer-a")); + Future second = + submitMutation( + executor, + fixture, + transactionsReady, + startWriters, + mutation("Concurrent World B", INITIAL_GAME_INSTANCE_ID, 1L, 1L, "writer-b")); + + try { + assertThat(transactionsReady.await(10, TimeUnit.SECONDS)).isTrue(); + startWriters.countDown(); + + List attempts = + List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); + List winners = attempts.stream().filter(MutationAttempt::succeeded).toList(); + List conflicts = + attempts.stream().filter(attempt -> !attempt.succeeded()).toList(); + + assertThat(winners).hasSize(1); + assertThat(conflicts).hasSize(1); + assertThat(conflicts.get(0).failure()) + .isInstanceOf(AdmissionPointerVersionMismatchException.class); + + GameplayAdmissionPointerSnapshot current = + fixture.service().findPointer(TENANT_ID, WORLD_SLUG, REALM_SLUG).orElseThrow(); + assertThat(current.pointerVersion()).isEqualTo(initial.pointerVersion()); + assertThat(current.catalogRevision()).isEqualTo(initial.catalogRevision() + 1L); + assertThat(current.worldDisplayName()).isIn("Concurrent World A", "Concurrent World B"); + + List audit = + fixture.service().listPointerAudit(TENANT_ID, WORLD_SLUG, REALM_SLUG); + assertThat(audit).hasSize(2); + assertThat(audit.get(0).catalogRevision()).isEqualTo(current.catalogRevision()); + assertThat(audit.get(0).worldDisplayName()).isEqualTo(current.worldDisplayName()); + } finally { + startWriters.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void auditInsertFailureRollsBackPointerRevisionAndRuntimeTarget() { + Fixture fixture = fixture(); + GameplayAdmissionPointerSnapshot initial = + fixture + .transactionTemplate() + .execute( + status -> + fixture + .service() + .upsertPointer( + mutation( + "Initial World", + INITIAL_GAME_INSTANCE_ID, + 0L, + 0L, + "initial-pointer"))); + assertThat(initial).isNotNull(); + List initialAudit = + fixture.service().listPointerAudit(TENANT_ID, WORLD_SLUG, REALM_SLUG); + assertThat(initialAudit).hasSize(1); + + fixture + .dsl() + .execute( + "CREATE FUNCTION reject_gameplay_admission_audit() RETURNS trigger LANGUAGE plpgsql " + + "AS $$ BEGIN RAISE EXCEPTION 'forced admission audit insert failure'; " + + "END; $$"); + fixture + .dsl() + .execute( + "CREATE TRIGGER reject_gameplay_admission_audit BEFORE INSERT ON " + + "gameplay_admission_pointer_event FOR EACH ROW EXECUTE FUNCTION " + + "reject_gameplay_admission_audit()"); + + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> + fixture + .service() + .upsertPointer( + mutation( + "Initial World", + INITIAL_GAME_INSTANCE_ID + 1L, + initial.pointerVersion(), + initial.catalogRevision(), + "failed-audit")))) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("forced admission audit insert failure"); + + GameplayAdmissionPointerSnapshot current = + fixture.service().findPointer(TENANT_ID, WORLD_SLUG, REALM_SLUG).orElseThrow(); + assertThat(current.pointerVersion()).isEqualTo(initial.pointerVersion()); + assertThat(current.catalogRevision()).isEqualTo(initial.catalogRevision()); + assertThat(current.gameInstanceId()).isEqualTo(initial.gameInstanceId()); + assertThat(current.worldDisplayName()).isEqualTo(initial.worldDisplayName()); + assertThat(fixture.service().listPointerAudit(TENANT_ID, WORLD_SLUG, REALM_SLUG)) + .containsExactlyElementsOf(initialAudit); + } + + private static Future submitMutation( + ExecutorService executor, + Fixture fixture, + CountDownLatch transactionsReady, + CountDownLatch startWriters, + GameplayAdmissionPointerMutation mutation) { + return executor.submit( + () -> { + try { + GameplayAdmissionPointerSnapshot snapshot = + fixture + .transactionTemplate() + .execute( + status -> { + fixture.dsl().execute("SET LOCAL statement_timeout = '10000ms'"); + transactionsReady.countDown(); + awaitWriterStart(startWriters); + return fixture.service().upsertPointer(mutation); + }); + return new MutationAttempt(snapshot, null); + } catch (AdmissionPointerVersionMismatchException exception) { + return new MutationAttempt(null, exception); + } + }); + } + + private static void awaitWriterStart(CountDownLatch startWriters) { + try { + if (!startWriters.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for competing pointer writers to start"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting to start pointer writer", exception); + } + } + + private static Fixture fixture() { + DriverManagerDataSource dataSource = dataSource(); + TransactionAwareDataSourceProxy transactionAwareDataSource = + new TransactionAwareDataSourceProxy(dataSource); + DSLContext dsl = DSL.using(transactionAwareDataSource, SQLDialect.POSTGRES); + TransactionTemplate transactionTemplate = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + DatabaseGameplayAdmissionPointerAuthorityService service = + new DatabaseGameplayAdmissionPointerAuthorityService( + new GameplayAdmissionPointerRepository(dsl), + new GameplayAdmissionPointerEventRepository(dsl)); + return new Fixture(dsl, transactionTemplate, service); + } + + private static DriverManagerDataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static GameplayAdmissionPointerMutation mutation( + String worldDisplayName, + long gameInstanceId, + long expectedPointerVersion, + long expectedCatalogRevision, + String requestId) { + return new GameplayAdmissionPointerMutation( + WORLD_SLUG, + worldDisplayName, + REALM_SLUG, + "CAS Realm", + TENANT_ID, + gameInstanceId, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "postgres-integration-test", + "verify pointer CAS transaction", + requestId, + expectedPointerVersion, + expectedCatalogRevision, + null); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transactionTemplate, + DatabaseGameplayAdmissionPointerAuthorityService service) {} + + private record MutationAttempt(GameplayAdmissionPointerSnapshot snapshot, Throwable failure) { + private boolean succeeded() { + return failure == null; + } + } +} From a804fa33d0b7595e1012118fb56d579ee2e3060f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 04:37:36 +1300 Subject: [PATCH 64/75] fix: address admission CAS and operator projection review findings --- .../GameSessionControlPlaneGrpcService.java | 1 + .../service/impl/GameSessionGrpcService.java | 2 +- .../V7__audit_gameplay_catalog_revision.sql | 1 - ...sionPointerCasPostgresIntegrationTest.java | 168 +++++++++++++----- ...ameSessionControlPlaneGrpcServiceTest.java | 76 ++++++++ .../impl/GameSessionGrpcServiceTest.java | 16 ++ .../impl/AdmissionPointerServiceImpl.java | 3 +- .../src/main/resources/openapi.yaml | 2 + .../AdmissionPointerControllerTest.java | 9 +- .../impl/AdmissionPointerServiceImplTest.java | 51 ++++++ .../impl/LoggingAdminGrpcServiceAuthTest.java | 3 +- 11 files changed, 277 insertions(+), 55 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java index 06bd5356e5..3d193fec3e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java @@ -278,6 +278,7 @@ private List validateAdmissionPointerListScope(List tenantIds) { List validatedTenantIds = tenantIds.stream() .map(tenantId -> ControlPlaneRequestParser.parsePositiveLong(tenantId, "tenant_ids")) + .distinct() .toList(); for (long tenantId : validatedTenantIds) { if (!SessionContext.hasTenantAccess(tenantId)) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index c5afa60a49..4958b54d4b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -846,7 +846,7 @@ private static String requireWorldSelector(String worldSelector) { if (!trimmed.matches("[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*")) { throw new IllegalArgumentException("worldSlug must be a valid selector"); } - return worldSelector; + return trimmed; } private static String requireIdentity(java.util.UUID identity, String fieldName) { diff --git a/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql b/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql index 9eff6e4d00..f310583acc 100644 --- a/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql +++ b/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql @@ -6,4 +6,3 @@ ALTER TABLE gameplay_admission_pointer_event CHECK (catalog_revision IS NULL OR catalog_revision > 0), ADD CONSTRAINT gameplay_admission_pointer_event_identity_pair_complete CHECK ((realm_id IS NULL) = (playable_state_namespace_id IS NULL)); - diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java index dd90558f13..d9e56017ed 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java @@ -5,11 +5,13 @@ import java.nio.file.Path; import java.util.List; +import java.util.Objects; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.impl.DatabaseGameplayAdmissionPointerAuthorityService; @@ -75,8 +77,11 @@ void competingWritersWithSamePositiveVersionPairCommitOnePointerAndAudit() throw assertThat(initial.catalogRevision()).isEqualTo(1L); assertThat(fixture.service().listPointerAudit(TENANT_ID, WORLD_SLUG, REALM_SLUG)).hasSize(1); - CountDownLatch transactionsReady = new CountDownLatch(2); - CountDownLatch startWriters = new CountDownLatch(1); + CountDownLatch winningTransactionReady = new CountDownLatch(1); + CountDownLatch releaseWinningTransaction = new CountDownLatch(1); + CountDownLatch competingTransactionReady = new CountDownLatch(1); + AtomicInteger winningBackendPid = new AtomicInteger(); + AtomicInteger competingBackendPid = new AtomicInteger(); ExecutorService executor = Executors.newFixedThreadPool( 2, @@ -86,23 +91,90 @@ void competingWritersWithSamePositiveVersionPairCommitOnePointerAndAudit() throw return thread; }); Future first = - submitMutation( - executor, - fixture, - transactionsReady, - startWriters, - mutation("Concurrent World A", INITIAL_GAME_INSTANCE_ID, 1L, 1L, "writer-a")); + executor.submit( + () -> { + try { + GameplayAdmissionPointerSnapshot snapshot = + fixture + .transactionTemplate() + .execute( + status -> { + fixture.dsl().execute("SET LOCAL statement_timeout = '30000ms'"); + var backendPidRecord = + Objects.requireNonNull( + fixture.dsl().fetchOne("select pg_backend_pid()"), + "Winning backend PID query returned no row"); + winningBackendPid.set( + Objects.requireNonNull( + backendPidRecord.get(0, Integer.class), + "Winning backend PID query returned no value")); + GameplayAdmissionPointerSnapshot updated = + fixture + .service() + .upsertPointer( + mutation( + "Concurrent World A", + INITIAL_GAME_INSTANCE_ID, + 1L, + 1L, + "writer-a")); + winningTransactionReady.countDown(); + awaitLatch( + releaseWinningTransaction, + "release of winning pointer transaction"); + return updated; + }); + return new MutationAttempt(snapshot, null); + } catch (Throwable failure) { + return new MutationAttempt(null, failure); + } + }); Future second = - submitMutation( - executor, - fixture, - transactionsReady, - startWriters, - mutation("Concurrent World B", INITIAL_GAME_INSTANCE_ID, 1L, 1L, "writer-b")); + executor.submit( + () -> { + try { + GameplayAdmissionPointerSnapshot snapshot = + fixture + .transactionTemplate() + .execute( + status -> { + fixture.dsl().execute("SET LOCAL statement_timeout = '30000ms'"); + var backendPidRecord = + Objects.requireNonNull( + fixture.dsl().fetchOne("select pg_backend_pid()"), + "Competing backend PID query returned no row"); + competingBackendPid.set( + Objects.requireNonNull( + backendPidRecord.get(0, Integer.class), + "Competing backend PID query returned no value")); + competingTransactionReady.countDown(); + awaitLatch( + winningTransactionReady, + "winning pointer transaction to acquire and hold its row lock"); + return fixture + .service() + .upsertPointer( + mutation( + "Concurrent World B", + INITIAL_GAME_INSTANCE_ID, + 1L, + 1L, + "writer-b")); + }); + return new MutationAttempt(snapshot, null); + } catch (Throwable failure) { + return new MutationAttempt(null, failure); + } + }); try { - assertThat(transactionsReady.await(10, TimeUnit.SECONDS)).isTrue(); - startWriters.countDown(); + assertThat(winningTransactionReady.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(competingTransactionReady.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(winningBackendPid.get()).isPositive(); + assertThat(competingBackendPid.get()).isPositive(); + assertThat(competingBackendPid.get()).isNotEqualTo(winningBackendPid.get()); + awaitPostgresRowLockWait(fixture.dsl(), competingBackendPid.get(), winningBackendPid.get()); + releaseWinningTransaction.countDown(); List attempts = List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); @@ -127,7 +199,7 @@ void competingWritersWithSamePositiveVersionPairCommitOnePointerAndAudit() throw assertThat(audit.get(0).catalogRevision()).isEqualTo(current.catalogRevision()); assertThat(audit.get(0).worldDisplayName()).isEqualTo(current.worldDisplayName()); } finally { - startWriters.countDown(); + releaseWinningTransaction.countDown(); executor.shutdownNow(); assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); } @@ -196,41 +268,45 @@ void auditInsertFailureRollsBackPointerRevisionAndRuntimeTarget() { .containsExactlyElementsOf(initialAudit); } - private static Future submitMutation( - ExecutorService executor, - Fixture fixture, - CountDownLatch transactionsReady, - CountDownLatch startWriters, - GameplayAdmissionPointerMutation mutation) { - return executor.submit( - () -> { - try { - GameplayAdmissionPointerSnapshot snapshot = - fixture - .transactionTemplate() - .execute( - status -> { - fixture.dsl().execute("SET LOCAL statement_timeout = '10000ms'"); - transactionsReady.countDown(); - awaitWriterStart(startWriters); - return fixture.service().upsertPointer(mutation); - }); - return new MutationAttempt(snapshot, null); - } catch (AdmissionPointerVersionMismatchException exception) { - return new MutationAttempt(null, exception); - } - }); + private static void awaitPostgresRowLockWait(DSLContext dsl, int waiterPid, int blockerPid) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + boolean blockedByWinner = false; + while (System.nanoTime() < deadline) { + var lockWaitRecord = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid = ? " + + "AND wait_event_type = 'Lock' AND query ILIKE '%FOR UPDATE%' " + + "AND ? = ANY(pg_blocking_pids(pid)))", + waiterPid, blockerPid), + "PostgreSQL lock-wait query returned no row"); + blockedByWinner = + Objects.requireNonNull( + lockWaitRecord.get(0, Boolean.class), "PostgreSQL lock-wait query returned no value"); + if (blockedByWinner) { + break; + } + try { + Thread.sleep(10L); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while observing PostgreSQL row lock wait", exception); + } + } + assertThat(blockedByWinner) + .as("competing backend waits on a PostgreSQL lock held by the winning transaction") + .isTrue(); } - private static void awaitWriterStart(CountDownLatch startWriters) { + private static void awaitLatch(CountDownLatch latch, String awaitedState) { try { - if (!startWriters.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Timed out waiting for competing pointer writers to start"); + if (!latch.await(30, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for " + awaitedState); } } catch (InterruptedException exception) { Thread.currentThread().interrupt(); - throw new IllegalStateException( - "Interrupted while waiting to start pointer writer", exception); + throw new IllegalStateException("Interrupted while waiting for " + awaitedState, exception); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 60ebc44767..e8fe544788 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -1919,6 +1919,31 @@ public void onNext(ListAdmissionPointersResponse value) { assertEquals("PERMISSION_DENIED", responseRef.get().getError().getCode()); } + @Test + void listAdmissionPointersKeepsEmptyListAsAdminAllTenantRequest() { + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(authorityService.listPointers()).thenReturn(List.of()); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.getDefaultInstance(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("", responseRef.get().getError().getCode()); + assertEquals(0, responseRef.get().getPointersCount()); + Mockito.verify(authorityService).listPointers(); + Mockito.verify(authorityService, Mockito.never()).listPointersForTenants(Mockito.anyList()); + } + @Test void listAdmissionPointersAllowsScopedCallerOnlyForRequestedTenantBeforeAuditValidation() { SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); @@ -1952,6 +1977,35 @@ public void onNext(ListAdmissionPointersResponse value) { .findLatestPointerAudit(1L, "tenant-a", "production"); } + @Test + void listAdmissionPointersDeduplicatesTenantIdsBeforeDispatch() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot requestedPointer = scopedAdmissionPointer(2L, "tenant-b"); + Mockito.when(authorityService.listPointersForTenants(List.of(2L))) + .thenReturn(List.of(requestedPointer)); + Mockito.when(authorityService.findLatestPointerAudit(2L, "tenant-b", "production")) + .thenReturn(Optional.of(scopedAdmissionPointerAudit(requestedPointer))); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds("2").addTenantIds("2").build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("", responseRef.get().getError().getCode()); + assertEquals(1, responseRef.get().getPointersCount()); + Mockito.verify(authorityService).listPointersForTenants(List.of(2L)); + Mockito.verify(authorityService).findLatestPointerAudit(2L, "tenant-b", "production"); + } + @Test void listAdmissionPointersRejectsScopedCallerRequestingAnotherTenant() { SessionContext.setContext("7", List.of(), Map.of("2", List.of("moderator"))); @@ -1974,6 +2028,28 @@ public void onNext(ListAdmissionPointersResponse value) { Mockito.verifyNoInteractions(authorityService); } + @Test + void listAdmissionPointersRejectsUnauthorizedTenantEvenWhenDuplicated() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds("1").addTenantIds("1").build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("PERMISSION_DENIED", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + } + @Test void listAdmissionPointersRejectsScopedCallerUsingEmptyAllTenantRequest() { SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 9574f1426b..f38cf9df79 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -1174,6 +1174,22 @@ void malformedWorldSelectorRemainsInvalidArgument() { assertEquals(0, response.getRealmsCount()); } + @Test + void listGameplayRealmsTrimsWorldSelectorBeforeAuthorityResolution() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn(List.of(authorityPointer("alpha", "live", 7L, 44L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + ListGameplayRealmsResponse response = listGameplayRealms(service, " alpha "); + + assertEquals("", response.getError().getCode()); + assertEquals(1, response.getRealmsCount()); + assertEquals("live", response.getRealms(0).getRealmSlug()); + Mockito.verify(pointerAuthorityService).listPointers(); + } + @Test void listGameplayRealmsMapsUnexpectedDependencyFailureToInternalAndCompletes() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java index a20b795eca..0816ee7720 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java @@ -300,7 +300,8 @@ private UUID parseOptionalUuid(String value, String fieldName) { try { return UUID.fromString(value); } catch (IllegalArgumentException ex) { - throw new IllegalArgumentException(fieldName + " must be a UUID", ex); + throw new ResponseStatusException( + HttpStatus.INTERNAL_SERVER_ERROR, fieldName + " from Game Session must be a UUID", ex); } } diff --git a/services/logging-admin-service/src/main/resources/openapi.yaml b/services/logging-admin-service/src/main/resources/openapi.yaml index c27b3af5a6..08d306c559 100644 --- a/services/logging-admin-service/src/main/resources/openapi.yaml +++ b/services/logging-admin-service/src/main/resources/openapi.yaml @@ -1238,8 +1238,10 @@ components: type: string tenantId: type: integer + format: int64 gameInstanceId: type: integer + format: int64 pointerVersion: type: integer format: int64 diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java index 120fd6c603..ce2a806be5 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java @@ -145,10 +145,11 @@ void openApiDocumentsAdmissionPointerReadContracts() throws Exception { Map schemas = (Map) components.get("schemas"); Map pointer = (Map) schemas.get("AdmissionPointerDto"); Map properties = (Map) pointer.get("properties"); - for (String revision : List.of("pointerVersion", "catalogRevision")) { - Map revisionSchema = (Map) properties.get(revision); - assertEquals("integer", revisionSchema.get("type")); - assertEquals("int64", revisionSchema.get("format")); + for (String field : + List.of("tenantId", "gameInstanceId", "pointerVersion", "catalogRevision")) { + Map fieldSchema = (Map) properties.get(field); + assertEquals("integer", fieldSchema.get("type")); + assertEquals("int64", fieldSchema.get("format")); } assertEquals(true, ((Map) properties.get("catalogRevision")).get("nullable")); } diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java index 1bf7714885..1da50d55ab 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java @@ -107,6 +107,57 @@ void globalListPointersUsesAllTenantRequest() { verify(gameSessionControlPlaneClient).listAdmissionPointers(List.of()); } + @Test + void listPointersRejectsMalformedRealmIdAsUpstreamFailure() { + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + AdmissionPointerControlPlaneEntry entry = + pointerEntry("demo", "production", 2L, 7L, 3L).toBuilder().setRealmId("invalid").build(); + when(gameSessionControlPlaneClient.listAdmissionPointers(List.of())) + .thenReturn(ListAdmissionPointersResponse.newBuilder().addPointers(entry).build()); + + ResponseStatusException ex = + assertThrows(ResponseStatusException.class, () -> service.listPointers()); + + assertEquals(500, ex.getStatusCode().value()); + assertEquals("realm_id from Game Session must be a UUID", ex.getReason()); + assertEquals(IllegalArgumentException.class, ex.getCause().getClass()); + } + + @Test + void listPointersRejectsMalformedPlayableStateNamespaceIdAsUpstreamFailure() { + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + AdmissionPointerControlPlaneEntry entry = + pointerEntry("demo", "production", 2L, 7L, 3L).toBuilder() + .setPlayableStateNamespaceId("invalid") + .build(); + when(gameSessionControlPlaneClient.listAdmissionPointers(List.of())) + .thenReturn(ListAdmissionPointersResponse.newBuilder().addPointers(entry).build()); + + ResponseStatusException ex = + assertThrows(ResponseStatusException.class, () -> service.listPointers()); + + assertEquals(500, ex.getStatusCode().value()); + assertEquals("playable_state_namespace_id from Game Session must be a UUID", ex.getReason()); + assertEquals(IllegalArgumentException.class, ex.getCause().getClass()); + } + + @Test + void listPointersMapsBlankOptionalIdentityFieldsToNull() { + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + AdmissionPointerControlPlaneEntry entry = + pointerEntry("demo", "production", 2L, 7L, 3L).toBuilder() + .setRealmId(" ") + .setPlayableStateNamespaceId("") + .build(); + when(gameSessionControlPlaneClient.listAdmissionPointers(List.of())) + .thenReturn(ListAdmissionPointersResponse.newBuilder().addPointers(entry).build()); + + AdmissionPointerDto result = service.listPointers().getFirst(); + + assertNull(result.realmId()); + assertNull(result.playableStateNamespaceId()); + } + @Test void listPointersMapsUnavailableAuthorityToServiceUnavailable() { SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index 1c9e79af5f..aa761d936b 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -610,8 +610,7 @@ private static CreateLogEventRequest validCreateLogEventRequest() { ByteString payload = ByteString.copyFromUtf8("{}"); return CreateLogEventRequest.newBuilder() .setScope( - net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) - .setTenantId("1") + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM) .setAuditEventId("d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3") .setProducerService("account-service") .setEventType("ACCOUNT_REGISTERED") From f6010f10098dda9c2189fdfb8e0f1d2e0889f2aa Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 05:23:29 +1300 Subject: [PATCH 65/75] test(game-session): reconcile locked mutation and isolated tenant fixtures --- .../GameplayAdmissionPointerRepositoryTest.java | 4 ++-- ...GameplayAdmissionPointerAuthorityServiceTest.java | 12 ++++++++---- .../support/MutableDefaultDemoCatalogTest.java | 4 +--- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index b604353c16..a9aa71e28d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -24,7 +24,7 @@ class GameplayAdmissionPointerRepositoryTest { void tenantScopedListFiltersRowsInTheDatabaseBeforeMapping() throws Exception { try (Connection connection = DriverManager.getConnection( - "jdbc:h2:mem:gameplay-pointer-tenant-list;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + "jdbc:h2:mem:gameplay-pointer-tenant-list-by-tenant;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { DSLContext dsl = DSL.using(connection, SQLDialect.H2); createSchema(dsl); GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); @@ -90,7 +90,7 @@ void stableRealmAndNamespaceIdentitySurviveRuntimeReplacement() throws Exception void tenantScopedPointerListExcludesOtherTenants() throws Exception { try (Connection connection = DriverManager.getConnection( - "jdbc:h2:mem:gameplay-pointer-tenant-list;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + "jdbc:h2:mem:gameplay-pointer-tenant-list-in;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { DSLContext dsl = DSL.using(connection, SQLDialect.H2); createSchema(dsl); GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index be855344ae..336885aef5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -220,7 +220,8 @@ void upsertPointerAdvancesCatalogRevisionWithoutAdvancingPointerVersion() { @Test void upsertPointerRuntimeTargetChangeAdvancesPointerVersionWithoutCatalogRevision() { GameplayAdmissionPointer existing = existingPointer(); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); when(pointerRepository.updateExisting(any(GameplayAdmissionPointer.class), any(), any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -516,7 +517,8 @@ void listPointerAuditPreservesCatalogIdentityAndHistoricalAbsence() { void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { java.util.concurrent.atomic.AtomicReference currentPointer = new java.util.concurrent.atomic.AtomicReference<>(); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 7L, "demo", "production")) .thenAnswer(invocation -> Optional.ofNullable(currentPointer.get())); when(pointerRepository.save(any(GameplayAdmissionPointer.class))) .thenAnswer( @@ -557,7 +559,8 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { void concurrentSameTransitionWinnerPreventsDuplicateAuditForStaleExpectedRevisions() { GameplayAdmissionPointer winnerRead = existingPointerForTenant(7L); GameplayAdmissionPointer staleRead = existingPointerForTenant(7L); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 7L, "demo", "production")) .thenReturn(Optional.of(winnerRead), Optional.of(staleRead)); java.util.concurrent.atomic.AtomicReference current = new java.util.concurrent.atomic.AtomicReference<>(existingPointerForTenant(7L)); @@ -604,7 +607,8 @@ void concurrentSameTransitionWinnerPreventsDuplicateAuditForStaleExpectedRevisio void existingPointerMutationRequiresMatchingCatalogRevisionEvenForNoOp() { GameplayAdmissionPointer existing = existingPointer(); existing.setTenantId(7L); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 7L, "demo", "production")) .thenReturn(Optional.of(existing)); assertThrows( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java index 108e98bc80..05d48cb492 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java @@ -171,9 +171,7 @@ public List listPointers() { @Override public List listPointersForTenants(List tenantIds) { - return pointers.stream() - .filter(pointer -> tenantIds.contains(pointer.tenantId())) - .toList(); + return pointers.stream().filter(pointer -> tenantIds.contains(pointer.tenantId())).toList(); } @Override From dc466d93644667991f1cb01a1ad1568d73048ea2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 05:38:21 +1300 Subject: [PATCH 66/75] docs: align admission pointer persistence and startup status --- design/architecture/service-responsibility-matrix.md | 4 ++-- .../realm-routing-and-playable-state.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/design/architecture/service-responsibility-matrix.md b/design/architecture/service-responsibility-matrix.md index 111aa4d999..963e91409b 100644 --- a/design/architecture/service-responsibility-matrix.md +++ b/design/architecture/service-responsibility-matrix.md @@ -167,7 +167,7 @@ Route-review procedure: 1. Classify the proposed route using the [canonical route-review examples and traffic split](./system-architecture-overview.md#external-admin-traffic-split-canonical). 2. Confirm the matching participation and ingress rows below; participation alone does not authorize a direct external mutation. -- The exact current matrix rows are **External operator read/proof-read ingress** and **External operator write ingress**; their current availability and drift are recorded in **Implementation Status**, while the rows remain the canonical participation contract. Version-upgrade preparation is a mutation and belongs only to the gated write-ingress row; the read row covers proof reads, not preparation writes. Admission-pointer control has internal implementation-participating read-then-write and prepared-cutover surfaces, but the target atomic open/close CAS and prepared cutover remain unimplemented and externally unavailable; its ownership row must not be read as current external support or as an absent owner contract. +- The exact current matrix rows are **External operator read/proof-read ingress** and **External operator write ingress**; their current availability and drift are recorded in **Implementation Status**, while the rows remain the canonical participation contract. Version-upgrade preparation is a mutation and belongs only to the gated write-ingress row; the read row covers proof reads, not preparation writes. Internally, the admission-pointer persistence primitive applies a row-locked conditional update against the expected pointer/catalog revision pair and commits pointer plus audit atomically. Public open/close mutation and full prepared cutover remain unavailable; see the [canonical Game Session owner contract](./microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary) and [Realm Routing implementation status](../project-management/implementation-tracking/realm-routing-and-playable-state.md). - Proposed route: `POST /api/session/game-sessions/{id}/feature-flags/{flagKey}:toggle`. Matrix check: `Game Session` participates in `Admin/creator API participation`, but the **External operator write ingress** row routes this workflow through `Logging & Admin`, so the direct external Game Session route is not allowed without a design update; current availability is governed by **Implementation Status**. - Proposed route: `POST /api/design/templates`. Matrix check: `Game Design` participates in `Admin/creator API participation`, and `Bypass-safe Game Design creator writes for tenant-scoped assets and templates` delegates this domain-local creator write to the Game Design service contract, so the route may be edge-routable when Game Design documents tenant access, validation, and audit behavior. - Proposed route: `GET /api/account/accounts/{id}`. Matrix check: `Account Service` participates in `Admin/creator API participation`, and the request is an external admin read rather than an operator mutation covered by the **External operator write ingress** row, so the route may be edge-routable when the owning service documents it as a bypass-safe read contract. @@ -176,7 +176,7 @@ The moderation policy-intent row assigns target `POST /moderation/actions` polic ## Notes on Redis Ownership and Participation -- **Independent version and admission CAS domains** – Game Design Service owns the version lifecycle state and `versionStateEpoch` CAS contract used for activation and rollback. Game Session and Logging & Admin may invoke that typed lifecycle API through their documented control-plane paths, but neither owns the version epoch. Game Session owns admission-pointer reads/preparation and the internal pointer persistence primitive for `{tenantId, worldSlug, realmSlug}`; that primitive checks both expected revisions under a row lock and commits pointer plus audit atomically, but it does not provide public open/close or complete prepared-cutover support. Canonical realm-ID addressing, explicit `CLOSED`, World hold/lifecycle fencing, and bounded drain remain gaps; see the [Realm Routing implementation tracker](../project-management/implementation-tracking/realm-routing-and-playable-state.md). Gateway participates at the edge for operator/proof reads and write ingress, while Logging & Admin is the domain ingress for the gated target operation. Neither edge participation nor operator ingress transfers authority from Game Session. The two CAS tokens are independent and must not be substituted for one another. +- **Independent version and admission CAS domains** – Game Design Service owns the version lifecycle state and `versionStateEpoch` CAS contract used for activation and rollback. Game Session and Logging & Admin may invoke that typed lifecycle API through their documented control-plane paths, but neither owns the version epoch. Game Session owns admission-pointer reads, preparation, and internal persistence. Canonical realm-ID addressing, explicit `CLOSED`, World hold/lifecycle fencing, and bounded drain remain gaps; see the [Realm Routing implementation tracker](../project-management/implementation-tracking/realm-routing-and-playable-state.md) and [Game Session owner contract](./microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Gateway participates at the edge for operator/proof reads and write ingress, while Logging & Admin is the domain ingress for the gated target operation. Neither edge participation nor operator ingress transfers authority from Game Session. The two CAS tokens are independent and must not be substituted for one another. - **Authoritative owner: Coordination Redis gameplay sessions (`session:game:*`)** – Game Session Service owns gameplay session bindings, lifecycle, and reset scope expectations for these keys. Other services participate only through documented shared helper libraries and key contracts; they do not introduce new gameplay session prefixes or modify TTLs/payload semantics without Game Session ownership and Redis design review. - **Authoritative owner: Coordination Redis gameplay coordination keys (`tick:*`, generic `timer:*`, `retry:*`, `tick-executor-lease:*`, and the target-only, once-implemented Game Session-produced `tick-events:{tenantRegionTag}` stream)** – Game Session Service owns gameplay coordination schema and lifecycle for these prefixes. Generic `timer:*` excludes Automation's `automation:timer:*` and `script-scheduler:*` families. Other services participate only through documented shared helper libraries and key contracts; they do not introduce new gameplay coordination prefixes or modify TTLs/payload semantics without Game Session ownership and Redis design review. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 312b47c08c..f908fd1ee5 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -39,7 +39,7 @@ Players address a visible `{tenantId, worldSlug, realmSlug}` realm, never a raw Selectors resolve to a tenant-local durable `realmId` before direct pointer authority is read. The target canonical singular key is `{tenantId, realmId}`; `GetAdmissionPointer(tenantId, realmId)` reads direct pointer authority using that key and does not reconstruct authority through browse projection. The current Game Session proto and `GameplayAdmissionPointerAuthorityService` still use `{tenantId, worldSlug, realmSlug}` slug lookup; realm-ID lookup and caller support remain implementation drift and are not claimed as live. Target Account bootstrap admission, public-production membership creation, prepared cutover validation, live admission, and operator audit reads use the same resolved realm identity. Membership join and connect-token issuance have separate idempotency contracts: each binds its own `requestId` to its operation, caller, verified discovery scope, and resolved target digest, and the two request IDs are not interchangeable. The current persistence primitive checks the expected `{pointerVersion, catalogRevision}` under a row lock, conditionally updates an existing row against both prior values, and commits the pointer with its audit event in one transaction. This is owner-local persistence proof, not public mutation or full prepared-cutover support; see the [Versioning & Runtime Configuration owner status](../../architecture/system-architecture-versioning-runtime.md#implementation-status). V2 enforces tenant-local selector uniqueness, but persistence has not converged on canonical `{tenantId, realmId}` addressing or retained catalog-to-realm mapping. -Startup seeds pointers only when the persisted store is empty, using dedicated bootstrap pointer-seed properties. After seeding, runtime reads and mutations use persisted pointer authority. `GameplayCatalogProperties` is not production routing authority: Game Session's production catalog projection is pointer-backed, Account Service no longer ships the old local catalog config, and property-to-catalog construction remains only in explicit test support. +Configured bootstrap pointer seeds are validated but not published automatically: startup creates no authority rows without World-owned lifecycle proof, and an empty store remains closed. `GameplayCatalogProperties` is not production routing authority: Game Session's production catalog projection is pointer-backed, Account Service no longer ships the old local catalog config, and property-to-catalog construction remains only in explicit test support. See the canonical [World Lifecycle and Admission Boundary](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary) and the [Game Session runtime tracker](./game-session-runtime-and-tick-coordination.md) for current implementation and proof status. Game Session exposes canonical world, realm, and pointer reads plus pointer list, audit, runtime-state, prepared-upgrade, and cutover control-plane surfaces. The public selector-shaped singular helper and preferred runtime-target lookup have been removed; reverse runtime-target consumers use `listByRuntimeTarget(...)` so multiplicity is observable. Logging & Admin is an operator ingress over these contracts, not a second routing owner. Its audit route is `GET /admission-pointers/{tenantId}/{worldSlug}/{realmSlug}/audit`; authenticated tenant access is checked before the call, response tenant mismatches fail closed, and operator pointer mutation derives `actorPrincipal` from the authenticated session rather than caller input. From 2cb75446f5b99d81d6883e54a47ee5f83d16a9cf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 05:52:44 +1300 Subject: [PATCH 67/75] refactor(gameplay): simplify guarded CAS and distinguish fixture requests --- design/architecture/system-architecture-multi-tenancy.md | 2 ++ ...DatabaseGameplayAdmissionPointerAuthorityService.java | 8 ++------ .../service/impl/GameSessionGrpcServiceTest.java | 9 ++++++++- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index e1148fd109..3600838220 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -14,6 +14,8 @@ The complete playtest initialization and lifecycle contract is owned by [ADR 013 ## Implementation Status +Implementation status and execution evidence belong in the owning tracker or PR, following the [validation and runtime proof workflow](../developer-workflows/validation-and-runtime-proof.md). + The realm-catalog, admission-pointer, realm-local character, explicit first-join, and quota-boundary contracts below are normative target behavior. Current runtime proof is partial: `IssueConnectToken` and text `PLAY` consume the current Account membership adapter evidence `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the membership and admission flags are true. Text `PLAY` validates the applicable private/playtest realm grant; `IssueConnectToken` checks the selected pointer/visibility and membership inputs but does not yet validate that applicable grant, so token grant validation remains an incomplete implementation/proof gap. The adapter has no lifecycle-state field. The obsolete implicit membership-writer surface has been removed; the membership-generation live reread at connect-token issuance is not implemented; Game Session stores a positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId` with pointer/audit rows, locks existing pointer rows, compares both pointer version and catalog revision, applies a conditional update, and commits pointer plus audit together. Initial-admission binding is wired only for the opt-in local Compose fixture, not general `StartSession`, strict `JOIN`, or production startup (see the [Game Session runtime status](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md)); external pointer-mutation and cutover control-plane RPCs remain fail-closed, and explicit `CLOSED`, full prepared-execution/hold/drain atomicity, and canonical `{tenantId, realmId}` persistence remain gaps (see the [realm-routing implementation status](../project-management/implementation-tracking/realm-routing-and-playable-state.md)); scoped-role population and tenant switching are not fully implemented/proved; authoritative entitlement freshness plus complete owning-service quota enforcement remain incomplete; and broader authority-generation claims, durable projections, and enforcement remain incomplete across issuer, account, tenant, and membership scopes. Explicit `JOIN`/`Join & Play` remains unimplemented, so the first-join flow remains target-state only. Playtest fork creation, reset, expiry automation, owner manifests, and lifecycle routes are also not implemented or end-to-end proved; this status does not weaken the target namespace and isolation rules above. Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. Required focused proof covers distinct-tenant separation, same-tenant stability across process restart with the persisted assignment/version, concurrent first allocation returning one assignment, rejection of a tag collision across allocation versions, and rejection of an active-binding `bindingRef` whose tenant differs from the requested tenant. No end-to-end proof yet demonstrates these target invariants. The remaining gaps do not change the distinct stable `tenantSlug` and tenant-scoped authored-world `worldSlug` selectors, tenant-local `realmSlug` to durable `realmId` resolution, exact-tenant quota binding, or required `GetAdmissionPointer(tenantId, realmId)` contract. --- diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index abb129c7f3..b09070c9b6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -293,13 +293,9 @@ private void enforceExpectedVersions( return; } long currentPointerVersion = - pointer.getId() == null - ? 0L - : pointer.getPointerVersion() == null ? -1L : pointer.getPointerVersion(); + pointer.getPointerVersion() == null ? -1L : pointer.getPointerVersion(); long currentCatalogRevision = - pointer.getId() == null - ? 0L - : pointer.getCatalogRevision() == null ? -1L : pointer.getCatalogRevision(); + pointer.getCatalogRevision() == null ? -1L : pointer.getCatalogRevision(); if (!isPositive(expectedPointerVersion) || !isPositive(expectedCatalogRevision) || currentPointerVersion != expectedPointerVersion diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index d3652b5452..87458ebba9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -1379,7 +1379,14 @@ private static GameplayAdmissionPointerMutation pointerMutation( "ALLOW_NEW", "test", "catalog revision test", - "catalog-revision-test-" + expectedPointerVersion, + "catalog-revision-test-" + + gameInstanceId + + "-" + + publicProductionRealm + + "-" + + expectedPointerVersion + + "-" + + expectedCatalogRevision, expectedPointerVersion, expectedCatalogRevision, null); From 74593942ee3f3f0d156b38de17449aebee7a0470 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 05:56:11 +1300 Subject: [PATCH 68/75] docs: record agent-scoped native process wait limitation --- design/project-management/ai-observations.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 599779a134..386ab596de 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -28,3 +28,9 @@ Entry format: - Expected pattern: alongside the code change, restrict privileged GitHub environments to the trusted deployment branch and clear or rotate credentials exposed by old runner state; verify the live environment policies before declaring the trust boundary effective. - Current status: The live `trusted-hosted-cluster` Environment allows only `develop`; its environment-scoped secret-name list is empty, while repository secrets still include legacy `PREVIEW_KUBECONFIG`. The scoped credential bootstrap/finalization, token rotation, legacy binding removal, and old-identity RBAC denial proof remain unverified. - Reconsideration trigger: before the next privileged deployment or declaring cutover complete, an authorized operator should provision and verify the canonical scoped credentials, finalize removal and revocation of the legacy credential and binding, and prove the old identity cannot read Secrets, create CertificateRequests, or change an Issuer. Secret-name presence or absence alone is not rotation or RBAC proof. + +- `2026-10-03`: Native process handles may be scoped to the launching agent + - Context: Gameplay tried to transfer an already-running full CLI command's native process handle to a read-only sentinel. + - Observation: the sentinel received `Unknown process id`, while the launching agent could still read the same live process. Shared filesystem access did not imply shared process-handle access; the review was neither restarted nor canceled. + - Expected pattern: retain an existing native process wait in its launching agent. For delegated external waits, let the sentinel launch its own canonical read-only waiter for the exact durable trigger or CI run; never retry the evidence-producing operation merely because a handle is unavailable in another agent. + - Current status: the launching Gameplay agent retained the live CLI wait. Whether cross-agent process handles are supported in other execution environments is unverified. From 3117a0b5530a7d3bc69f02182f4713f2567093c6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 06:05:16 +1300 Subject: [PATCH 69/75] test(gameplay): consolidate revision proof and reach audit guard --- ...yAdmissionPointerAuthorityServiceTest.java | 9 +- ...ameSessionControlPlaneGrpcServiceTest.java | 18 +--- .../impl/GameSessionGrpcServiceTest.java | 87 ------------------- 3 files changed, 10 insertions(+), 104 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index 336885aef5..c1a716266d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -645,7 +645,14 @@ private static GameplayAdmissionPointerMutation pointerMutation( publicProductionRealm, expectedPointerVersion, expectedCatalogRevision, - "catalog-revision-test-" + expectedPointerVersion); + "catalog-revision-test-" + + gameInstanceId + + "-" + + publicProductionRealm + + "-" + + expectedPointerVersion + + "-" + + expectedCatalogRevision); } private static GameplayAdmissionPointerMutation pointerMutation( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index cba0a8e4c5..28f1300fc5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -2186,22 +2186,7 @@ void listAdmissionPointersFailsClosedWhenCurrentPointerHasNoAuditHistory() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(authorityService.listPointers()) - .thenReturn( - List.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo World", - "production", - "Live Realm", - 1L, - 7L, - 3L, - true, - true, - false, - "SHARED", - "ALLOW_NEW", - 2L))); + .thenReturn(List.of(scopedAdmissionPointer(1L, "demo"))); Mockito.when(authorityService.findLatestPointerAudit(1L, "demo", "production")) .thenReturn(Optional.empty()); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); @@ -2228,6 +2213,7 @@ public void onNext(ListAdmissionPointersResponse value) { assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); assertEquals(0, responseRef.get().getPointersCount()); + Mockito.verify(authorityService).findLatestPointerAudit(1L, "demo", "production"); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 87458ebba9..1db89fc77a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -20,18 +20,13 @@ import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; -import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; -import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; -import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; -import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.AccountPresenceSnapshot; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.FeatureFlagService; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; import net.firedevops.firemud.gamesession.service.PingService; @@ -1310,88 +1305,6 @@ public void onCompleted() { assertEquals(0, response.get().getRealmsCount()); } - @Test - void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { - GameplayAdmissionPointerRepository pointerRepository = - Mockito.mock(GameplayAdmissionPointerRepository.class); - GameplayAdmissionPointerEventRepository eventRepository = - Mockito.mock(GameplayAdmissionPointerEventRepository.class); - AtomicReference currentPointer = new AtomicReference<>(); - Mockito.when( - pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( - 7L, "demo", "production")) - .thenAnswer(invocation -> java.util.Optional.ofNullable(currentPointer.get())); - Mockito.when(pointerRepository.save(Mockito.any(GameplayAdmissionPointer.class))) - .thenAnswer( - invocation -> { - GameplayAdmissionPointer pointer = invocation.getArgument(0); - if (pointer.getId() == null) { - pointer.setId(11L); - } - currentPointer.set(pointer); - return pointer; - }); - Mockito.when( - pointerRepository.updateExisting( - Mockito.any(GameplayAdmissionPointer.class), Mockito.any(), Mockito.any())) - .thenAnswer( - invocation -> { - GameplayAdmissionPointer pointer = invocation.getArgument(0); - currentPointer.set(pointer); - return pointer; - }); - Mockito.when(eventRepository.save(Mockito.any(GameplayAdmissionPointerEvent.class))) - .thenAnswer(invocation -> invocation.getArgument(0)); - DatabaseGameplayAdmissionPointerAuthorityService authorityService = - new DatabaseGameplayAdmissionPointerAuthorityService(pointerRepository, eventRepository); - - GameplayAdmissionPointerSnapshot created = - authorityService.upsertPointer(pointerMutation(44L, true, 0L, 0L)); - GameplayAdmissionPointerSnapshot policyChanged = - authorityService.upsertPointer(pointerMutation(44L, false, 1L, 1L)); - GameplayAdmissionPointerSnapshot routeChanged = - authorityService.upsertPointer(pointerMutation(45L, false, 1L, 2L)); - - assertEquals(1L, created.catalogRevision()); - assertEquals(1L, created.pointerVersion()); - assertEquals(2L, policyChanged.catalogRevision()); - assertEquals(1L, policyChanged.pointerVersion()); - assertEquals(2L, routeChanged.catalogRevision()); - assertEquals(2L, routeChanged.pointerVersion()); - } - - private static GameplayAdmissionPointerMutation pointerMutation( - long gameInstanceId, - boolean publicProductionRealm, - Long expectedPointerVersion, - Long expectedCatalogRevision) { - return new GameplayAdmissionPointerMutation( - "demo", - "Demo World", - "production", - "Live Realm", - 7L, - gameInstanceId, - true, - publicProductionRealm, - false, - "SHARED", - "ALLOW_NEW", - "test", - "catalog revision test", - "catalog-revision-test-" - + gameInstanceId - + "-" - + publicProductionRealm - + "-" - + expectedPointerVersion - + "-" - + expectedCatalogRevision, - expectedPointerVersion, - expectedCatalogRevision, - null); - } - @Test void getAdmissionPointerRuntimeFailureReturnsInternalErrorDetail() { PingService pingService = Mockito.mock(PingService.class); From 79c8bcd70e1b00272cde00ed8fdf9c9e1572dedb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 06:48:50 +1300 Subject: [PATCH 70/75] Batch scoped pointer audits and clarify authority responses --- design/grpc-docs/grpc-api.md | 90 ++++++++++++++- .../v1/game_session_service.proto | 8 ++ ...meplayAdmissionPointerEventRepository.java | 31 ++++++ ...eplayAdmissionPointerAuthorityService.java | 6 + ...eplayAdmissionPointerAuthorityService.java | 19 ++++ ...onAdmissionPointerControlPlaneService.java | 21 +++- .../GameSessionControlPlaneGrpcService.java | 20 ++-- ...ayAdmissionPointerEventRepositoryTest.java | 51 +++++++++ ...missionPointerControlPlaneServiceTest.java | 80 +++++++++++-- ...ameSessionControlPlaneGrpcServiceTest.java | 105 ++++++++++++------ .../MutableDefaultDemoCatalogTest.java | 8 ++ 11 files changed, 379 insertions(+), 60 deletions(-) diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index f103dc58ae..798879e1ce 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -413,6 +413,8 @@ for conventions on schema evolution and error handling. See each service's - [GetGameSessionPinConvergenceResponse](#game_session-v1-GetGameSessionPinConvergenceResponse) - [GetGameplayCommandStatusRequest](#game_session-v1-GetGameplayCommandStatusRequest) - [GetGameplayCommandStatusResponse](#game_session-v1-GetGameplayCommandStatusResponse) + - [GetInitialAdmissionBindProofRequest](#game_session-v1-GetInitialAdmissionBindProofRequest) + - [GetInitialAdmissionBindProofResponse](#game_session-v1-GetInitialAdmissionBindProofResponse) - [GetPinnedScriptPatchVersionRequest](#game_session-v1-GetPinnedScriptPatchVersionRequest) - [GetPinnedScriptPatchVersionResponse](#game_session-v1-GetPinnedScriptPatchVersionResponse) - [GetPreparedVersionUpgradeRequest](#game_session-v1-GetPreparedVersionUpgradeRequest) @@ -493,6 +495,7 @@ for conventions on schema evolution and error handling. See each service's - [AccountRecentPresenceDisposition](#game_session-v1-AccountRecentPresenceDisposition) - [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) - [ExpectedCurrentPin.Kind](#game_session-v1-ExpectedCurrentPin-Kind) + - [InitialAdmissionBindOwnerProofOutcome](#game_session-v1-InitialAdmissionBindOwnerProofOutcome) - [TickStatus](#game_session-v1-TickStatus) - [GameSessionControlPlaneService](#game_session-v1-GameSessionControlPlaneService) @@ -7434,8 +7437,8 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo | actor_principal | [string](#string) | | | | reason | [string](#string) | | | | control_plane_request_id | [string](#string) | | | -| expected_pointer_version | [int64](#int64) | optional | | -| expected_catalog_revision | [int64](#int64) | optional | | +| expected_pointer_version | [int64](#int64) | optional | Existing-row mutations require both expected revisions to match the current row. Creating a missing row is supported only with both fields explicitly present as zero. Optional presence does not enable the currently disabled public mutation RPC or imply valid mutation semantics. | +| expected_catalog_revision | [int64](#int64) | optional | Must be supplied with expected_pointer_version under the same existing-row or creation rules. | @@ -7831,6 +7834,67 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo + + +### GetInitialAdmissionBindProofRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| hold_id | [string](#string) | | | +| hold_fence | [string](#string) | | | +| tenant_id | [string](#string) | | | +| realm_uuid | [string](#string) | | | +| playable_state_namespace_uuid | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| game_instance_id | [string](#string) | | | +| version_id | [string](#string) | | | +| active_lifecycle_epoch | [int64](#int64) | | | +| initial_admission_request_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| expected_no_prior_pointer | [bool](#bool) | | | +| expected_catalog_revision | [int64](#int64) | | | + + + + + + + + +### GetInitialAdmissionBindProofResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| hold_id | [string](#string) | | Echoes the complete request tuple so World can reject proof for another hold or target. | +| hold_fence | [string](#string) | | | +| tenant_id | [string](#string) | | | +| realm_uuid | [string](#string) | | | +| playable_state_namespace_uuid | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| game_instance_id | [string](#string) | | | +| version_id | [string](#string) | | | +| active_lifecycle_epoch | [int64](#int64) | | | +| initial_admission_request_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| expected_no_prior_pointer | [bool](#bool) | | | +| expected_catalog_revision | [int64](#int64) | | | +| outcome | [InitialAdmissionBindOwnerProofOutcome](#game_session-v1-InitialAdmissionBindOwnerProofOutcome) | | | +| owner_proof_id | [string](#string) | | | +| pointer_audit_id | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| pointer_audit_request_digest | [string](#string) | | | +| future_commit_prevented | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + ### GetPinnedScriptPatchVersionRequest @@ -9293,10 +9357,10 @@ Resume ticks after an authorized maintenance workflow completes. | actor_principal | [string](#string) | | | | reason | [string](#string) | | | | control_plane_request_id | [string](#string) | | | -| expected_pointer_version | [int64](#int64) | optional | | +| expected_pointer_version | [int64](#int64) | optional | Existing-row mutations require both expected revisions to match the current row. Creating a missing row is supported only with both fields explicitly present as zero. Optional presence does not enable the currently disabled public mutation RPC or imply valid mutation semantics. | | prepared_version_upgrade_id | [string](#string) | | | | public_production_realm | [bool](#bool) | | | -| expected_catalog_revision | [int64](#int64) | optional | | +| expected_catalog_revision | [int64](#int64) | optional | Must be supplied with expected_pointer_version under the same existing-row or creation rules. | @@ -9587,6 +9651,23 @@ Resume ticks after an authorized maintenance workflow completes. + + +### InitialAdmissionBindOwnerProofOutcome + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_UNSPECIFIED | 0 | | +| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_COMMITTED | 1 | | +| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_ABORTED | 2 | | +| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_NOT_FOUND | 3 | | +| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_PENDING | 4 | | +| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_UNAVAILABLE | 5 | | +| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_ERROR | 6 | | + + + ### TickStatus @@ -9615,6 +9696,7 @@ plus scoped tick pause/resume used for rollback safety. | GetPinnedScriptPatchVersion | [GetPinnedScriptPatchVersionRequest](#game_session-v1-GetPinnedScriptPatchVersionRequest) | [GetPinnedScriptPatchVersionResponse](#game_session-v1-GetPinnedScriptPatchVersionResponse) | | | GetGameSessionPinConvergence | [GetGameSessionPinConvergenceRequest](#game_session-v1-GetGameSessionPinConvergenceRequest) | [GetGameSessionPinConvergenceResponse](#game_session-v1-GetGameSessionPinConvergenceResponse) | | | GetGameInstanceRuntimeState | [GetGameInstanceRuntimeStateRequest](#game_session-v1-GetGameInstanceRuntimeStateRequest) | [GetGameInstanceRuntimeStateResponse](#game_session-v1-GetGameInstanceRuntimeStateResponse) | | +| GetInitialAdmissionBindProof | [GetInitialAdmissionBindProofRequest](#game_session-v1-GetInitialAdmissionBindProofRequest) | [GetInitialAdmissionBindProofResponse](#game_session-v1-GetInitialAdmissionBindProofResponse) | Read exact durable owner proof for a World-owned initial-admission hold. | | ValidateBuiltInCommandAlias | [ValidateBuiltInCommandAliasRequest](#game_session-v1-ValidateBuiltInCommandAliasRequest) | [ValidateBuiltInCommandAliasResponse](#game_session-v1-ValidateBuiltInCommandAliasResponse) | | | ListAdmissionPointers | [ListAdmissionPointersRequest](#game_session-v1-ListAdmissionPointersRequest) | [ListAdmissionPointersResponse](#game_session-v1-ListAdmissionPointersResponse) | | | ListAdmissionPointerAudit | [ListAdmissionPointerAuditRequest](#game_session-v1-ListAdmissionPointerAuditRequest) | [ListAdmissionPointerAuditResponse](#game_session-v1-ListAdmissionPointerAuditResponse) | | diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index 9f77ca7920..adf1810f08 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -1158,9 +1158,13 @@ message SetAdmissionPointerRequest { string actor_principal = 11; string reason = 12; string control_plane_request_id = 13; + // Existing-row mutations require both expected revisions to match the current row. Creating a + // missing row is supported only with both fields explicitly present as zero. Optional presence + // does not enable the currently disabled public mutation RPC or imply valid mutation semantics. optional int64 expected_pointer_version = 14; string prepared_version_upgrade_id = 15; bool public_production_realm = 16; + // Must be supplied with expected_pointer_version under the same existing-row or creation rules. optional int64 expected_catalog_revision = 17; } @@ -1178,7 +1182,11 @@ message ExecutePreparedVersionCutoverRequest { string actor_principal = 6; string reason = 7; string control_plane_request_id = 8; + // Existing-row mutations require both expected revisions to match the current row. Creating a + // missing row is supported only with both fields explicitly present as zero. Optional presence + // does not enable the currently disabled public mutation RPC or imply valid mutation semantics. optional int64 expected_pointer_version = 9; + // Must be supplied with expected_pointer_version under the same existing-row or creation rules. optional int64 expected_catalog_revision = 10; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java index e0f171c876..427c7a7e6d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java @@ -9,8 +9,11 @@ import java.util.Optional; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayAdmissionPointerEventRecord; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; +import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @Repository @@ -63,6 +66,34 @@ public Optional findLatestByTenantIdAndWorldSlugA .fetchOptional(this::toEntity); } + public List findLatestByPointerKeys(List keys) { + if (keys.isEmpty()) { + return List.of(); + } + Condition selectedKeys = DSL.falseCondition(); + for (PointerAuditKey key : keys) { + selectedKeys = + selectedKeys.or( + GAMEPLAY_ADMISSION_POINTER_EVENT + .TENANT_ID + .eq(key.tenantId()) + .and(GAMEPLAY_ADMISSION_POINTER_EVENT.WORLD_SLUG.eq(key.worldSlug())) + .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(key.realmSlug()))); + } + var latestIds = + dsl.select(DSL.max(GAMEPLAY_ADMISSION_POINTER_EVENT.ID)) + .from(GAMEPLAY_ADMISSION_POINTER_EVENT) + .where(selectedKeys) + .groupBy( + GAMEPLAY_ADMISSION_POINTER_EVENT.TENANT_ID, + GAMEPLAY_ADMISSION_POINTER_EVENT.WORLD_SLUG, + GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG); + return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER_EVENT) + .where(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.in(latestIds)) + .orderBy(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.asc()) + .fetch(this::toEntity); + } + public GameplayAdmissionPointerEvent save(GameplayAdmissionPointerEvent entity) { if (entity.getId() == null) { GameplayAdmissionPointerEventRecord record = dsl.newRecord(GAMEPLAY_ADMISSION_POINTER_EVENT); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java index 50823ecc6f..1bd9e0eade 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java @@ -1,9 +1,12 @@ package net.firedevops.firemud.gamesession.service; import java.util.List; +import java.util.Map; import java.util.Optional; public interface GameplayAdmissionPointerAuthorityService { + record PointerAuditKey(long tenantId, String worldSlug, String realmSlug) {} + List listPointers(); List listPointersForTenants(List tenantIds); @@ -22,4 +25,7 @@ List listPointerAudit( Optional findLatestPointerAudit( long tenantId, String worldSlug, String realmSlug); + + Map findLatestPointerAudits( + List keys); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index b09070c9b6..851d2af4d9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -3,8 +3,10 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.stream.Collectors; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; @@ -13,6 +15,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionCatalogPolicy; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import org.springframework.stereotype.Service; @@ -190,6 +193,22 @@ public Optional findLatestPointerAudit( .map(this::toAuditEntry); } + @Override + @Transactional(readOnly = true) + public Map findLatestPointerAudits( + List keys) { + if (keys.isEmpty()) { + return Map.of(); + } + return eventRepository.findLatestByPointerKeys(keys).stream() + .collect( + Collectors.toMap( + event -> + new PointerAuditKey( + event.getTenantId(), event.getWorldSlug(), event.getRealmSlug()), + this::toAuditEntry)); + } + private GameplayAdmissionPointerAuditEntry toAuditEntry(GameplayAdmissionPointerEvent event) { return new GameplayAdmissionPointerAuditEntry( event.getWorldSlug(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java index c2f7ac840f..6a7e1ab8ca 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java @@ -2,10 +2,12 @@ import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Set; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.v1.AdmissionPointerControlPlaneEntry; import net.firedevops.firemud.gamesession.v1.ExecutePreparedVersionCutoverRequest; @@ -43,15 +45,24 @@ ListAdmissionPointersResponse listAdmissionPointers(List requestedTenantId .filter( pointer -> tenantScope.isEmpty() || tenantScope.contains(pointer.tenantId())) .toList(); + List auditKeys = + pointers.stream() + .map( + pointer -> + new PointerAuditKey( + pointer.tenantId(), pointer.worldSlug(), pointer.realmSlug())) + .distinct() + .toList(); + Map latestAudits = + gameplayAdmissionPointerAuthorityService.findLatestPointerAudits(auditKeys); List entries = pointers.stream() .map( pointer -> { - GameplayAdmissionPointerAuditEntry latestAudit = - gameplayAdmissionPointerAuthorityService - .findLatestPointerAudit( - pointer.tenantId(), pointer.worldSlug(), pointer.realmSlug()) - .orElse(null); + PointerAuditKey key = + new PointerAuditKey( + pointer.tenantId(), pointer.worldSlug(), pointer.realmSlug()); + GameplayAdmissionPointerAuditEntry latestAudit = latestAudits.get(key); if (latestAudit == null) { throw new AdmissionPointerAuditUnavailableException( "Admission pointer audit unavailable for current pointer " diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java index 4a5030f854..bfe78ed281 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java @@ -197,12 +197,11 @@ private ErrorDetail automationAdmissionReceiverFenceUnavailable(String operation } private ErrorDetail admissionPointerAuthorityUnavailableError(String operation) { - return GrpcAppErrors.error( - meterRegistry, - logger, - operation, - "AUTHORITY_UNAVAILABLE", - "Admission pointer authority unavailable"); + return authorityUnavailableError(operation, "Admission pointer authority unavailable"); + } + + private ErrorDetail authorityUnavailableError(String operation, String message) { + return GrpcAppErrors.error(meterRegistry, logger, operation, "AUTHORITY_UNAVAILABLE", message); } private static boolean isPersistenceAvailabilityFailure(Throwable failure) { @@ -1120,7 +1119,9 @@ public void getGameInstanceRuntimeState( logger.warn("GetGameInstanceRuntimeState persistence unavailable", ex); GetGameInstanceRuntimeStateResponse response = GetGameInstanceRuntimeStateResponse.newBuilder() - .setError(admissionPointerAuthorityUnavailableError("GetGameInstanceRuntimeState")) + .setError( + authorityUnavailableError( + "GetGameInstanceRuntimeState", "Runtime state authority unavailable")) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); @@ -1355,7 +1356,10 @@ public void getPreparedVersionUpgrade( logger.warn("GetPreparedVersionUpgrade persistence unavailable", ex); GetPreparedVersionUpgradeResponse response = GetPreparedVersionUpgradeResponse.newBuilder() - .setError(admissionPointerAuthorityUnavailableError("GetPreparedVersionUpgrade")) + .setError( + authorityUnavailableError( + "GetPreparedVersionUpgrade", + "Prepared version upgrade authority unavailable")) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java index dda817c340..0ed9ee5223 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -49,6 +50,56 @@ void savesCatalogRevisionAndStableIdentityAndKeepsUnknownValuesNull() throws Exc } } + @Test + void findsLatestAuditByIdForExactMixedTenantPointerKeys() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-event-latest-batch;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerEventRepository repository = + new GameplayAdmissionPointerEventRepository(dsl); + + GameplayAdmissionPointerEvent newestTenantNine = event("2026-09-10T00:00:00Z"); + repository.save(newestTenantNine); + GameplayAdmissionPointerEvent tenantTen = event("2026-09-08T00:00:00Z"); + tenantTen.setTenantId(10L); + repository.save(tenantTen); + GameplayAdmissionPointerEvent otherRealm = event("2026-09-07T00:00:00Z"); + otherRealm.setRealmSlug("playtest"); + repository.save(otherRealm); + GameplayAdmissionPointerEvent latestById = event("2026-09-01T00:00:00Z"); + repository.save(latestById); + GameplayAdmissionPointerEvent outsideSelection = event("2026-09-11T00:00:00Z"); + outsideSelection.setTenantId(11L); + repository.save(outsideSelection); + + List latest = + repository.findLatestByPointerKeys( + List.of( + new PointerAuditKey(9L, "demo", "production"), + new PointerAuditKey(10L, "demo", "production"), + new PointerAuditKey(9L, "demo", "playtest"))); + var byKey = + latest.stream() + .collect( + java.util.stream.Collectors.toMap( + audit -> + new PointerAuditKey( + audit.getTenantId(), audit.getWorldSlug(), audit.getRealmSlug()), + GameplayAdmissionPointerEvent::getControlPlaneRequestId)); + + assertEquals(3, latest.size()); + assertEquals( + "request-2026-09-01T00:00:00Z", byKey.get(new PointerAuditKey(9L, "demo", "production"))); + assertEquals( + "request-2026-09-08T00:00:00Z", + byKey.get(new PointerAuditKey(10L, "demo", "production"))); + assertEquals( + "request-2026-09-07T00:00:00Z", byKey.get(new PointerAuditKey(9L, "demo", "playtest"))); + } + } + private static GameplayAdmissionPointerEvent event(String occurredAt) { GameplayAdmissionPointerEvent event = new GameplayAdmissionPointerEvent(); event.setWorldSlug("demo"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java index 3363d311a3..77b53aa1c5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java @@ -2,6 +2,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -10,7 +12,7 @@ import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.List; -import java.util.Optional; +import java.util.Map; import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; @@ -18,18 +20,22 @@ import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import org.junit.jupiter.api.Test; class GameSessionAdmissionPointerControlPlaneServiceTest { @Test - void listQueriesTenantScopeBeforeCheckingLatestAudit() { + void listQueriesTenantScopeBeforeBatchingExactLatestAuditKeys() { GameplayAdmissionPointerAuthorityService authorityService = mock(GameplayAdmissionPointerAuthorityService.class); - GameplayAdmissionPointerSnapshot tenantB = pointer(2L, "tenant-b"); - when(authorityService.listPointersForTenants(List.of(2L))).thenReturn(List.of(tenantB)); - when(authorityService.findLatestPointerAudit(2L, "tenant-b", "production")) - .thenReturn(Optional.of(audit(tenantB))); + GameplayAdmissionPointerSnapshot tenantA = pointer(1L, "demo"); + GameplayAdmissionPointerSnapshot tenantB = pointer(2L, "demo"); + PointerAuditKey tenantBKey = new PointerAuditKey(2L, "demo", "production"); + when(authorityService.listPointersForTenants(List.of(2L))) + .thenReturn(List.of(tenantA, tenantB)); + when(authorityService.findLatestPointerAudits(List.of(tenantBKey))) + .thenReturn(Map.of(tenantBKey, audit(tenantB))); GameSessionAdmissionPointerControlPlaneService controlPlaneService = new GameSessionAdmissionPointerControlPlaneService(authorityService); @@ -39,8 +45,54 @@ void listQueriesTenantScopeBeforeCheckingLatestAudit() { assertEquals("2", response.getPointers(0).getTenantId()); verify(authorityService).listPointersForTenants(List.of(2L)); verify(authorityService, never()).listPointers(); - verify(authorityService).findLatestPointerAudit(2L, "tenant-b", "production"); - verify(authorityService, never()).findLatestPointerAudit(1L, "tenant-a", "production"); + verify(authorityService).findLatestPointerAudits(List.of(tenantBKey)); + verify(authorityService, never()).findLatestPointerAudit(anyLong(), anyString(), anyString()); + } + + @Test + void listBatchesMixedTenantAuditKeysWithSameWorldSlug() { + GameplayAdmissionPointerAuthorityService authorityService = + mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot tenantA = pointer(1L, "demo"); + GameplayAdmissionPointerSnapshot tenantB = pointer(2L, "demo"); + PointerAuditKey tenantAKey = new PointerAuditKey(1L, "demo", "production"); + PointerAuditKey tenantBKey = new PointerAuditKey(2L, "demo", "production"); + when(authorityService.listPointers()).thenReturn(List.of(tenantA, tenantB)); + when(authorityService.findLatestPointerAudits(List.of(tenantAKey, tenantBKey))) + .thenReturn(Map.of(tenantAKey, audit(tenantA), tenantBKey, audit(tenantB))); + GameSessionAdmissionPointerControlPlaneService controlPlaneService = + new GameSessionAdmissionPointerControlPlaneService(authorityService); + + var response = controlPlaneService.listAdmissionPointers(List.of()); + + assertEquals(2, response.getPointersCount()); + assertEquals("1", response.getPointers(0).getTenantId()); + assertEquals("2", response.getPointers(1).getTenantId()); + verify(authorityService).findLatestPointerAudits(List.of(tenantAKey, tenantBKey)); + verify(authorityService, never()).findLatestPointerAudit(anyLong(), anyString(), anyString()); + } + + @Test + void listFailsClosedWhenBatchAuditIsMissingOrDoesNotMatchCurrentPointer() { + GameplayAdmissionPointerAuthorityService authorityService = + mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot currentPointer = pointer(2L, "tenant-b"); + PointerAuditKey key = new PointerAuditKey(2L, "tenant-b", "production"); + when(authorityService.listPointers()).thenReturn(List.of(currentPointer)); + GameSessionAdmissionPointerControlPlaneService controlPlaneService = + new GameSessionAdmissionPointerControlPlaneService(authorityService); + + when(authorityService.findLatestPointerAudits(List.of(key))).thenReturn(Map.of()); + assertThrows( + AdmissionPointerAuditUnavailableException.class, + () -> controlPlaneService.listAdmissionPointers(List.of())); + + when(authorityService.findLatestPointerAudits(List.of(key))) + .thenReturn(Map.of(key, audit(currentPointer, currentPointer.pointerVersion() + 1L))); + assertThrows( + AdmissionPointerAuditUnavailableException.class, + () -> controlPlaneService.listAdmissionPointers(List.of())); + verify(authorityService, never()).findLatestPointerAudit(anyLong(), anyString(), anyString()); } @Test @@ -90,8 +142,9 @@ void listRejectsRetainedPreV7AuditWithUnknownRevisionAndIdentity() { when(pointerRepository.findAllByOrderByWorldSlugAscRealmSlugAsc()) .thenReturn(List.of(currentPointer)); - when(eventRepository.findLatestByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) - .thenReturn(Optional.of(retainedPreV7Event)); + when(eventRepository.findLatestByPointerKeys( + List.of(new PointerAuditKey(1L, "demo", "production")))) + .thenReturn(List.of(retainedPreV7Event)); DatabaseGameplayAdmissionPointerAuthorityService authorityService = new DatabaseGameplayAdmissionPointerAuthorityService(pointerRepository, eventRepository); @@ -127,6 +180,11 @@ private static GameplayAdmissionPointerSnapshot pointer(long tenantId, String wo private static GameplayAdmissionPointerAuditEntry audit( GameplayAdmissionPointerSnapshot pointer) { + return audit(pointer, pointer.pointerVersion()); + } + + private static GameplayAdmissionPointerAuditEntry audit( + GameplayAdmissionPointerSnapshot pointer, long pointerVersion) { return new GameplayAdmissionPointerAuditEntry( pointer.worldSlug(), pointer.realmSlug(), @@ -134,7 +192,7 @@ private static GameplayAdmissionPointerAuditEntry audit( pointer.realmDisplayName(), pointer.tenantId(), pointer.gameInstanceId(), - pointer.pointerVersion(), + pointerVersion, pointer.catalogRevision(), pointer.realmId(), pointer.playableStateNamespaceId(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 28f1300fc5..6710e33f35 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -47,6 +47,7 @@ import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.InstanceCutoverCompatibilityService; import net.firedevops.firemud.gamesession.service.RemoteFollowupRuntimeService; @@ -983,6 +984,8 @@ public void onNext(GetGameInstanceRuntimeStateResponse value) { assertNotNull(responseRef.get()); assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); + assertEquals( + "Runtime state authority unavailable", responseRef.get().getError().getMessage()); assertFalse(responseRef.get().hasRuntimeState()); Mockito.verify(runtimeRepository).findByTenantIdAndRegionId(1L, "region-7"); } @@ -1902,8 +1905,8 @@ void listAdmissionPointersUsesCurrentSnapshotForIdentityAndLatestAuditForMetadat UUID.fromString("3ce19e6a-a63f-46f4-8e25-b105694c79e9"), UUID.fromString("f673a1e6-648d-4ac3-8f3d-4b7cc4380f2a")); Mockito.when(authorityService.listPointers()).thenReturn(List.of(currentPointer)); - Mockito.when(authorityService.findLatestPointerAudit(1L, "demo", "production")) - .thenReturn(Optional.of(scopedAdmissionPointerAudit(currentPointer))); + stubLatestPointerAudit( + authorityService, currentPointer, scopedAdmissionPointerAudit(currentPointer)); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( @@ -1957,8 +1960,8 @@ void listAdmissionPointersAllowsScopedCallerOnlyForRequestedTenantBeforeAuditVal GameplayAdmissionPointerSnapshot requestedPointer = scopedAdmissionPointer(2L, "tenant-b"); Mockito.when(authorityService.listPointersForTenants(List.of(2L))) .thenReturn(List.of(requestedPointer)); - Mockito.when(authorityService.findLatestPointerAudit(2L, "tenant-b", "production")) - .thenReturn(Optional.of(scopedAdmissionPointerAudit(requestedPointer))); + stubLatestPointerAudit( + authorityService, requestedPointer, scopedAdmissionPointerAudit(requestedPointer)); GameSessionControlPlaneGrpcService service = admissionPointerControlPlaneService(authorityService); @@ -1977,9 +1980,9 @@ public void onNext(ListAdmissionPointersResponse value) { assertEquals("2", responseRef.get().getPointers(0).getTenantId()); Mockito.verify(authorityService).listPointersForTenants(List.of(2L)); Mockito.verify(authorityService, Mockito.never()).listPointers(); - Mockito.verify(authorityService).findLatestPointerAudit(2L, "tenant-b", "production"); + Mockito.verify(authorityService).findLatestPointerAudits(List.of(auditKey(requestedPointer))); Mockito.verify(authorityService, Mockito.never()) - .findLatestPointerAudit(1L, "tenant-a", "production"); + .findLatestPointerAudit(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @Test @@ -1990,8 +1993,8 @@ void listAdmissionPointersDeduplicatesTenantIdsBeforeDispatch() { GameplayAdmissionPointerSnapshot requestedPointer = scopedAdmissionPointer(2L, "tenant-b"); Mockito.when(authorityService.listPointersForTenants(List.of(2L))) .thenReturn(List.of(requestedPointer)); - Mockito.when(authorityService.findLatestPointerAudit(2L, "tenant-b", "production")) - .thenReturn(Optional.of(scopedAdmissionPointerAudit(requestedPointer))); + stubLatestPointerAudit( + authorityService, requestedPointer, scopedAdmissionPointerAudit(requestedPointer)); GameSessionControlPlaneGrpcService service = admissionPointerControlPlaneService(authorityService); AtomicReference responseRef = new AtomicReference<>(); @@ -2008,7 +2011,7 @@ public void onNext(ListAdmissionPointersResponse value) { assertEquals("", responseRef.get().getError().getCode()); assertEquals(1, responseRef.get().getPointersCount()); Mockito.verify(authorityService).listPointersForTenants(List.of(2L)); - Mockito.verify(authorityService).findLatestPointerAudit(2L, "tenant-b", "production"); + Mockito.verify(authorityService).findLatestPointerAudits(List.of(auditKey(requestedPointer))); } @Test @@ -2162,8 +2165,7 @@ void listAdmissionPointersFailsClosedForMissingAuditInRequestedTenant() { GameplayAdmissionPointerSnapshot requestedPointer = scopedAdmissionPointer(2L, "tenant-b"); Mockito.when(authorityService.listPointersForTenants(List.of(2L))) .thenReturn(List.of(requestedPointer)); - Mockito.when(authorityService.findLatestPointerAudit(2L, "tenant-b", "production")) - .thenReturn(Optional.empty()); + stubMissingLatestPointerAudit(authorityService, requestedPointer); GameSessionControlPlaneGrpcService service = admissionPointerControlPlaneService(authorityService); AtomicReference responseRef = new AtomicReference<>(); @@ -2185,10 +2187,9 @@ public void onNext(ListAdmissionPointersResponse value) { void listAdmissionPointersFailsClosedWhenCurrentPointerHasNoAuditHistory() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - Mockito.when(authorityService.listPointers()) - .thenReturn(List.of(scopedAdmissionPointer(1L, "demo"))); - Mockito.when(authorityService.findLatestPointerAudit(1L, "demo", "production")) - .thenReturn(Optional.empty()); + GameplayAdmissionPointerSnapshot currentPointer = scopedAdmissionPointer(1L, "demo"); + Mockito.when(authorityService.listPointers()).thenReturn(List.of(currentPointer)); + stubMissingLatestPointerAudit(authorityService, currentPointer); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( @@ -2213,13 +2214,14 @@ public void onNext(ListAdmissionPointersResponse value) { assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); assertEquals(0, responseRef.get().getPointersCount()); - Mockito.verify(authorityService).findLatestPointerAudit(1L, "demo", "production"); + Mockito.verify(authorityService).findLatestPointerAudits(List.of(auditKey(currentPointer))); } @Test void listAdmissionPointersFailsClosedWhenLatestAuditHasNoCatalogRevision() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + PointerAuditKey auditKey = new PointerAuditKey(1L, "demo", "production"); Mockito.when(authorityService.listPointers()) .thenReturn( List.of( @@ -2239,9 +2241,10 @@ void listAdmissionPointersFailsClosedWhenLatestAuditHasNoCatalogRevision() { 6L, UUID.fromString("11111111-1111-1111-1111-111111111111"), UUID.fromString("22222222-2222-2222-2222-222222222222")))); - Mockito.when(authorityService.findLatestPointerAudit(1L, "demo", "production")) + Mockito.when(authorityService.findLatestPointerAudits(List.of(auditKey))) .thenReturn( - Optional.of( + Map.of( + auditKey, new GameplayAdmissionPointerAuditEntry( "demo", "production", @@ -2293,6 +2296,7 @@ public void onNext(ListAdmissionPointersResponse value) { void listAdmissionPointersFailsClosedWhenLatestAuditDoesNotMatchCurrentPointer() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + PointerAuditKey auditKey = new PointerAuditKey(1L, "demo", "production"); Mockito.when(authorityService.listPointers()) .thenReturn( List.of( @@ -2312,9 +2316,10 @@ void listAdmissionPointersFailsClosedWhenLatestAuditDoesNotMatchCurrentPointer() 6L, UUID.fromString("11111111-1111-1111-1111-111111111111"), UUID.fromString("22222222-2222-2222-2222-222222222222")))); - Mockito.when(authorityService.findLatestPointerAudit(1L, "demo", "production")) + Mockito.when(authorityService.findLatestPointerAudits(List.of(auditKey))) .thenReturn( - Optional.of( + Map.of( + auditKey, new GameplayAdmissionPointerAuditEntry( "demo", "production", @@ -2366,6 +2371,7 @@ public void onNext(ListAdmissionPointersResponse value) { void listAdmissionPointersExposesDurableIdentityFromAuditEntry() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + PointerAuditKey auditKey = new PointerAuditKey(1L, "demo", "production"); Mockito.when(authorityService.listPointers()) .thenReturn( List.of( @@ -2385,9 +2391,10 @@ void listAdmissionPointersExposesDurableIdentityFromAuditEntry() { 6L, UUID.fromString("11111111-1111-1111-1111-111111111111"), UUID.fromString("22222222-2222-2222-2222-222222222222")))); - Mockito.when(authorityService.findLatestPointerAudit(1L, "demo", "production")) + Mockito.when(authorityService.findLatestPointerAudits(List.of(auditKey))) .thenReturn( - Optional.of( + Map.of( + auditKey, new GameplayAdmissionPointerAuditEntry( "demo", "production", @@ -2439,7 +2446,7 @@ public void onNext(ListAdmissionPointersResponse value) { assertEquals(6L, responseRef.get().getPointers(0).getCatalogRevision()); Mockito.verify(authorityService).listPointers(); Mockito.verify(authorityService, Mockito.never()).listPointersForTenants(Mockito.anyList()); - Mockito.verify(authorityService).findLatestPointerAudit(1L, "demo", "production"); + Mockito.verify(authorityService).findLatestPointerAudits(List.of(auditKey)); } @Test @@ -2447,9 +2454,9 @@ void listAdmissionPointersReturnsAuthorityUnavailableForDatabaseShutdownStates() for (String sqlState : List.of("08006", "57P01", "57P02", "57P03")) { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - Mockito.when(authorityService.listPointers()) - .thenReturn(List.of(scopedAdmissionPointer(1L, "demo"))); - Mockito.when(authorityService.findLatestPointerAudit(1L, "demo", "production")) + GameplayAdmissionPointerSnapshot currentPointer = scopedAdmissionPointer(1L, "demo"); + Mockito.when(authorityService.listPointers()).thenReturn(List.of(currentPointer)); + Mockito.when(authorityService.findLatestPointerAudits(List.of(auditKey(currentPointer)))) .thenThrow( new org.jooq.exception.DataAccessException( "audit database unavailable", @@ -2487,9 +2494,9 @@ void listAdmissionPointersKeepsUnexpectedFailuresInternal() { for (RuntimeException failure : unexpectedFailures) { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - Mockito.when(authorityService.listPointers()) - .thenReturn(List.of(scopedAdmissionPointer(1L, "demo"))); - Mockito.when(authorityService.findLatestPointerAudit(1L, "demo", "production")) + GameplayAdmissionPointerSnapshot currentPointer = scopedAdmissionPointer(1L, "demo"); + Mockito.when(authorityService.listPointers()).thenReturn(List.of(currentPointer)); + Mockito.when(authorityService.findLatestPointerAudits(List.of(auditKey(currentPointer)))) .thenThrow(failure); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = @@ -9254,11 +9261,25 @@ void getPreparedVersionUpgradeMapsRecognizedPersistenceAvailabilityFailures() { Mockito.when(fixture.preparationService().getPreparedVersionUpgrade(1L, "pvu-1")) .thenThrow(failure); SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); + AtomicReference responseRef = new AtomicReference<>(); + fixture + .service() + .getPreparedVersionUpgrade( + GetPreparedVersionUpgradeRequest.newBuilder() + .setTenantId("1") + .setPreparationId("pvu-1") + .build(), + new NoopObserver<>() { + @Override + public void onNext(GetPreparedVersionUpgradeResponse value) { + responseRef.set(value); + } + }); + assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); assertEquals( - "AUTHORITY_UNAVAILABLE", - invokeAdmissionReadProof( - fixture.service(), AdmissionReadProofOperation.PREPARED_VERSION, "1", "pvu-1")); + "Prepared version upgrade authority unavailable", + responseRef.get().getError().getMessage()); } } @@ -10555,6 +10576,26 @@ private static GameplayAdmissionPointerSnapshot scopedAdmissionPointer( UUID.fromString("22222222-2222-2222-2222-222222222222")); } + private static PointerAuditKey auditKey(GameplayAdmissionPointerSnapshot pointer) { + return new PointerAuditKey(pointer.tenantId(), pointer.worldSlug(), pointer.realmSlug()); + } + + private static void stubLatestPointerAudit( + GameplayAdmissionPointerAuthorityService authorityService, + GameplayAdmissionPointerSnapshot pointer, + GameplayAdmissionPointerAuditEntry audit) { + PointerAuditKey key = auditKey(pointer); + Mockito.when(authorityService.findLatestPointerAudits(List.of(key))) + .thenReturn(Map.of(key, audit)); + } + + private static void stubMissingLatestPointerAudit( + GameplayAdmissionPointerAuthorityService authorityService, + GameplayAdmissionPointerSnapshot pointer) { + Mockito.when(authorityService.findLatestPointerAudits(List.of(auditKey(pointer)))) + .thenReturn(Map.of()); + } + private static GameplayAdmissionPointerAuditEntry scopedAdmissionPointerAudit( GameplayAdmissionPointerSnapshot pointer) { return new GameplayAdmissionPointerAuditEntry( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java index 05d48cb492..45eb9fc579 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java @@ -5,11 +5,13 @@ import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; @@ -215,5 +217,11 @@ public Optional findLatestPointerAudit( long tenantId, String worldSlug, String realmSlug) { return Optional.empty(); } + + @Override + public Map findLatestPointerAudits( + List keys) { + return Map.of(); + } } } From 75f9d904bfc28bbddb2f7c7a67f6f3e5a68e67cb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 07:05:26 +1300 Subject: [PATCH 71/75] docs: align runtime ownership and paired admission CAS proof --- .../microservices/logging-admin-service/api-contracts.md | 2 +- design/project-management/ai-observations.md | 1 + .../shared-runtime-contracts-and-persistence.md | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index b1bf8487ed..7ca506ddb7 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -113,7 +113,7 @@ The current internal `SetAdmissionPointer` and `ExecutePreparedVersionCutover` r - `OpenAdmissionPointer` performs `CLOSED -> OPEN(target)`. The target must exist, belong to `tenantId`, and be the prepared/active runtime for the same world and realm. It must pass current runtime lifecycle and entitlement/admission checks; display names, slugs, or a caller-supplied instance id are not proof of that relationship. If validation is unavailable or ambiguous, the operation fails closed. `preparedVersionUpgradeId` is forbidden because this operation cannot replace an already open target. - `CloseAdmissionPointer` performs `OPEN(target) -> CLOSED`. Game Session first checks the idempotency record for `controlPlaneRequestId`: an exact completed duplicate replays its original successful response and audit identity before current pointer-state validation. For a new request ID, the request must identify the exact currently open `gameInstanceId`; a missing pointer, already closed pointer, or different current target fails without mutation. Reusing a completed request ID with a different digest conflicts. Closing is a safety operation and therefore does not require the target to remain lifecycle- or entitlement-admissible. It cannot select a replacement target, and `preparedVersionUpgradeId` is forbidden. The resulting pointer makes no `gameInstanceId` gameplay-admissible while preserving the former target in audit evidence. -- Both requests carry the complete routing identity, target `gameInstanceId`, expected route version (`expectedPointerVersion`), reason, and idempotent `controlPlaneRequestId`. The schema does not accept a client-supplied actor: the actor is derived server-side from the authenticated operator session or workload. The response and audit record expose that actor and the resulting monotonic `pointerVersion`. `pointerVersion` is the route version and CAS token for exactly `{tenantId, worldSlug, realmSlug}`. The write succeeds only when the stored version equals the expected version; otherwise it returns a conflict and leaves the route unchanged. An absent route record uses `expectedPointerVersion=0` for the first open rather than an unscoped blind write. +- Both requests carry the complete routing identity, target `gameInstanceId`, expected CAS pair (`expectedPointerVersion` and `expectedCatalogRevision`), reason, and idempotent `controlPlaneRequestId`. For an existing pointer, both expected revisions must match; creating an absent pointer requires the explicit `0/0` pair. The schema does not accept a client-supplied actor: the actor is derived server-side from the authenticated operator session or workload. The response and audit record expose that actor and the resulting monotonic `pointerVersion`. `pointerVersion` is the route version and CAS token for exactly `{tenantId, worldSlug, realmSlug}`. A mismatch returns a conflict and leaves the route unchanged. - Replacing or rolling back `OPEN(old)` to `OPEN(new)` is a prepared cutover, not a generic open. It must use the internal `ExecutePreparedVersionCutover` control-plane operation with one durable `preparedVersionUpgradeId`; that operation revalidates the preparation, source and target identities, and CAS version before atomically swapping the route. Preparation is proof for cutover, not a substitute for route-version concurrency control. - Game Session remains the sole routing-state writer and audits the transition under the same identity and CAS result. Internal callers must not maintain a competing pointer or infer `tenantId` from `worldSlug` or `realmSlug`; Logging & Admin's public REST surface reads the resulting state and audit evidence only. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 386ab596de..9715e879de 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -34,3 +34,4 @@ Entry format: - Observation: the sentinel received `Unknown process id`, while the launching agent could still read the same live process. Shared filesystem access did not imply shared process-handle access; the review was neither restarted nor canceled. - Expected pattern: retain an existing native process wait in its launching agent. For delegated external waits, let the sentinel launch its own canonical read-only waiter for the exact durable trigger or CI run; never retry the evidence-producing operation merely because a handle is unavailable in another agent. - Current status: the launching Gameplay agent retained the live CLI wait. Whether cross-agent process handles are supported in other execution environments is unverified. + - Reconsideration trigger: revisit if a future harness requires cross-platform handle portability or a canonical watcher fix is verified. diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index 7d457b392a..ff0e360ab7 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -174,7 +174,7 @@ Current runtime wiring keeps gameplay ticks, Redis coordination, per-command exe | --- | --- | --- | | Common platform/security | Internal auth propagation, service identity parsing, deprecated gameplay-attestation helpers pending removal and authority-boundary proof, gRPC app-error representation/observability, and proto time-field guard | Shared Java seams, deprecated attestation debt pending removal, gRPC helpers, Gradle/root verification | | Owning domain services | Domain authority, tenant/access enforcement, local transaction boundary, durable local state, and app-error mapping | Service REST/gRPC APIs and service-local Flyway schema | -| Logging & Admin | Non-destructive log-event ingress, moderation policy definition/evaluation, operator projections, and target moderation/report persistence (currently unavailable/gated) | Audit/log-event and moderation/control-plane REST/gRPC contracts | +| Logging & Admin | Current separate `LogEvent` RPC and `log_events` persistence path; typed `CreateLogEvent` RPC is present but returns `UNIMPLEMENTED` and is unavailable; moderation policy definition/evaluation, operator projections, and target moderation/report persistence (currently unavailable/gated) | Audit/log-event and moderation/control-plane REST/gRPC contracts; target receiver boundary: [Account Audit Ingress and Receipt](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt) | | Game Session | Player-session authority, exact script-pin authority and rollout-history ownership, gameplay-attestation call sites pending removal and consumer-level authority proof, lifecycle finalization/compensation, tick runtime coordination, and gameplay control-plane delegation | Session/gameplay gRPC, script-pin and rollout-history contracts, deprecated attestation debt pending removal, Redis/runtime records, and durable SQL ledgers | | Common saga | Shared saga repository ownership and short synchronous saga persistence/runner contract | Schema-qualified jOOQ repositories and saga steps | | jOOQ/Flyway tooling | Generated relational access, migration history, service-schema conventions, and Postgres-backed proof support | Build/codegen tasks, Flyway resources, reset/bootstrap tooling | From b3542688ab40ece2bb43874075d5dfeeef68a4db Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 07:21:59 +1300 Subject: [PATCH 72/75] fix: bound selected admission audit queries and separate status --- .../system-architecture-multi-tenancy.md | 6 +- ...e-session-runtime-and-tick-coordination.md | 2 + ...meplayAdmissionPointerEventRepository.java | 57 ++++++++++++------- ...ayAdmissionPointerEventRepositoryTest.java | 50 ++++++++++++++++ 4 files changed, 90 insertions(+), 25 deletions(-) diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index 3600838220..bb9a7e209e 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -14,9 +14,7 @@ The complete playtest initialization and lifecycle contract is owned by [ADR 013 ## Implementation Status -Implementation status and execution evidence belong in the owning tracker or PR, following the [validation and runtime proof workflow](../developer-workflows/validation-and-runtime-proof.md). - -The realm-catalog, admission-pointer, realm-local character, explicit first-join, and quota-boundary contracts below are normative target behavior. Current runtime proof is partial: `IssueConnectToken` and text `PLAY` consume the current Account membership adapter evidence `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the membership and admission flags are true. Text `PLAY` validates the applicable private/playtest realm grant; `IssueConnectToken` checks the selected pointer/visibility and membership inputs but does not yet validate that applicable grant, so token grant validation remains an incomplete implementation/proof gap. The adapter has no lifecycle-state field. The obsolete implicit membership-writer surface has been removed; the membership-generation live reread at connect-token issuance is not implemented; Game Session stores a positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId` with pointer/audit rows, locks existing pointer rows, compares both pointer version and catalog revision, applies a conditional update, and commits pointer plus audit together. Initial-admission binding is wired only for the opt-in local Compose fixture, not general `StartSession`, strict `JOIN`, or production startup (see the [Game Session runtime status](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md)); external pointer-mutation and cutover control-plane RPCs remain fail-closed, and explicit `CLOSED`, full prepared-execution/hold/drain atomicity, and canonical `{tenantId, realmId}` persistence remain gaps (see the [realm-routing implementation status](../project-management/implementation-tracking/realm-routing-and-playable-state.md)); scoped-role population and tenant switching are not fully implemented/proved; authoritative entitlement freshness plus complete owning-service quota enforcement remain incomplete; and broader authority-generation claims, durable projections, and enforcement remain incomplete across issuer, account, tenant, and membership scopes. Explicit `JOIN`/`Join & Play` remains unimplemented, so the first-join flow remains target-state only. Playtest fork creation, reset, expiry automation, owner manifests, and lifecycle routes are also not implemented or end-to-end proved; this status does not weaken the target namespace and isolation rules above. Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. Required focused proof covers distinct-tenant separation, same-tenant stability across process restart with the persisted assignment/version, concurrent first allocation returning one assignment, rejection of a tag collision across allocation versions, and rejection of an active-binding `bindingRef` whose tenant differs from the requested tenant. No end-to-end proof yet demonstrates these target invariants. The remaining gaps do not change the distinct stable `tenantSlug` and tenant-scoped authored-world `worldSlug` selectors, tenant-local `realmSlug` to durable `realmId` resolution, exact-tenant quota binding, or required `GetAdmissionPointer(tenantId, realmId)` contract. +Implementation status and execution evidence belong in the owning trackers or PR, following the [validation and runtime proof workflow](../developer-workflows/validation-and-runtime-proof.md). Current routing, admission, account/session, and Game Session implementation and proof remain partial; see the [realm-routing tracker](../project-management/implementation-tracking/realm-routing-and-playable-state.md#current-status), [player-access tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status), and [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). These status records do not change the normative tenant, namespace, routing, and isolation contracts in this document. --- @@ -203,7 +201,7 @@ Pointer freshness and cutover rules: Migrations create tables directly inside dedicated service schemas rather than the `public` schema. - Databases are **shared across tenants**. Tenant-owned records carry and enforce `tenantId`; genuinely platform-global records such as the core account identity do not acquire a placeholder tenant merely to satisfy this convention. Relationships between a global record and a game live in explicit tenant-scoped tables. Domain services also scope their versioned data by `version_id` so multiple published or draft configurations can coexist per tenant. - Services enforce the `tenantId` filter on queries for tenant-owned data to prevent cross-game access. They do not apply tenant filters to platform-global account, credential, recovery, or security records; links between those records and a game are represented by explicit tenant-scoped relationships and authorized separately. -- Every Redis key family must use its canonical key builder and representative formats defined in the [Redis Architecture](./system-architecture-redis.md#coordination-key-examples), rather than hand-rolled strings. The target-only authenticated gameplay session family is `session:game:{tenantGameplayTag}::`, where `tenantGameplayTag` is loaded or allocated through the authoritative persisted tenant-to-tag mapping defined above; `tenantId` remains the authoritative identity and validation field. Current Game Session context remains on `sessionctx:*`. For tick-related keys, this prefix is combined with a region identifier into a single normalized region hash tag token (for example `tick:{tenantRegionTag}:lock:`). The hash tag only co-locates related keys in one Redis Cluster slot for shard-local atomic operations; it is not a tenant-isolation boundary. Tenant isolation comes from canonical key builders and owner-side tenant validation. The untagged global account active-binding index and other explicitly global families are exceptions to the physical key-prefix rule; tenant isolation for the account index is enforced by its tenant-qualified `bindingRef` members and owner-controlled validation, never by treating the global key as tenant-local authority. +- Every Redis key family must use its canonical key builder and representative formats defined in the [Redis Architecture](./system-architecture-redis.md#coordination-key-examples), rather than hand-rolled strings. The target-only authenticated gameplay session family is `session:game:{tenantGameplayTag}::`, where `tenantGameplayTag` is a deterministic, injective projection of authoritative `tenantId`, loaded from or allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version; `tenantId` remains the authoritative identity and validation field. Existing assignments are reused, and first allocation atomically enforces uniqueness for both tenant and tag, rejecting a candidate already assigned to another tenant even across allocation versions. Encoding or version changes preserve existing mappings and apply only to future allocations; encoding and version remain opaque to clients and other services. Current Game Session context remains on `sessionctx:*`. Gameplay controller uniqueness is `{tenantId, playableStateNamespaceId, characterId}`; its binding value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`, while server-derived `playableStateScope` remains binding/routing evidence. For tick-related keys, this prefix is combined with a region identifier into a single normalized region hash tag token (for example `tick:{tenantRegionTag}:lock:`). The hash tag only co-locates related keys in one Redis Cluster slot for shard-local atomic operations; it is not a tenant-isolation boundary. Tenant isolation comes from canonical key builders and owner-side tenant validation. The untagged global account active-binding index and other explicitly global families are exceptions to the physical key-prefix rule; tenant isolation for the account index is enforced by its tenant-qualified `bindingRef` members and owner-controlled validation, never by treating the global key as tenant-local authority. - Focused proof for this boundary must demonstrate that distinct `tenantId` values produce distinct tags, a tenant's tag and allocation version remain stable across process restart, concurrent first allocation returns one persisted assignment, a candidate tag collision is rejected when another tenant owns it under a different allocation version, and the owning active-binding validator rejects a `bindingRef` from another tenant. Redis slot co-location alone is not proof of isolation. Apply the [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md) when selecting and recording this focused proof. - The React frontend loads per-tenant, version-scoped assets from a published `manifest.json` in object storage; the Game Design Service is not queried at diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 212604dd28..f57a4b0491 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for Game Session runtime and tick This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. +Gameplay-session context remains on the implementation-local `sessionctx:*` keys and per-instance binding identity. The target authenticated `session:game:{tenantGameplayTag}:...` family, persisted tenant-tag allocation, and namespace-qualified controller uniqueness are not implemented or end-to-end proved; the canonical tenancy and focused-isolation requirements remain in [Multi-Tenancy](../../architecture/system-architecture-multi-tenancy.md#data-separation-per-service). + Retained bootstrap correction: V8 recognizes only the unchanged, provenance-backed historical demo/sandbox pair that was seeded with two public-production realms. It changes sandbox's public flag and advances only its catalog revision, retains runtime pointer and durable realm/namespace identity, and appends an immutable repair event in the same transaction. Unknown, operator-edited, incomplete, extra-public, or conflicting-history catalogs remain untouched and fail closed. This is not World-owner lifecycle or initial-bind proof. PostgreSQL execution remains a required separate check; the local environment has no Docker or PostgreSQL runtime. Admission-catalog foundation status: Game Session pointer and audit rows now persist a separate positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId`; repository updates check both pointer version and catalog revision, and player-facing catalog/read projections fail closed on ambiguous tenant catalogs or incomplete identity. Runtime control-plane reads also reject persisted pointers with nonpositive `catalogRevision` or missing `realmId`/`playableStateNamespaceId` before constructing `GameInstanceRuntimeState`, returning `ADMISSION_POINTER_AUTHORITY_UNAVAILABLE` without partial pin/version metadata or pointer entries. Same-tenant world and realm selectors that collide under case-folding now fail closed in authority-backed catalogs and fixture catalogs while preserving the canonical routing tuple and revision. No-caller text `WORLDS`/`REALMS` and gRPC `ListGameplayWorlds`/`ListGameplayRealms` now share a public-production-only projection that retains the existing catalog health and public-realm cardinality checks; internal pointer health reads and explicit private admission/grant checks still see private realm authority. Caller-authorized private discovery remains unavailable until Account/caller integration. Focused regressions cover mixed-case collisions, single-selector resolution, private-only world omission, and private realm omission; validation remains pending. This is implemented whole-response fail-closed behavior, not successful migration or runtime proof. This does not implement a World-owner-validated initial bind, strict `JOIN`, or production activation. The configuration-driven pointer initializer validates configured seed shape without inserting pointer rows, and GS/WMS raw runtime seeding has been removed. Neither configured seeds nor legacy seed configuration provides World lifecycle proof. The extracted 35-path foundation passed a serialized `run-locked-gradle.sh` invocation of `:game-session-service:spotlessJavaApply :game-session-service:test :game-session-service:compileIntegrationTestJava linkCheck lintMarkdown --no-configuration-cache` on 2026-10-02. This executed unit proof and compiled PostgreSQL migration tests; no PostgreSQL/runtime execution proof is claimed. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java index 427c7a7e6d..7210542b41 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java @@ -5,6 +5,9 @@ import static net.firedevops.firemud.gamesession.jooq.tables.GameplayAdmissionPointerEvent.GAMEPLAY_ADMISSION_POINTER_EVENT; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; @@ -21,6 +24,8 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class GameplayAdmissionPointerEventRepository { + private static final int POINTER_KEY_QUERY_CHUNK_SIZE = 500; + private final DSLContext dsl; public GameplayAdmissionPointerEventRepository(DSLContext dsl) { @@ -70,28 +75,38 @@ public List findLatestByPointerKeys(List uniqueKeys = new ArrayList<>(new LinkedHashSet<>(keys)); + List latestEvents = new ArrayList<>(); + for (int offset = 0; offset < uniqueKeys.size(); offset += POINTER_KEY_QUERY_CHUNK_SIZE) { + List keyChunk = + uniqueKeys.subList( + offset, Math.min(offset + POINTER_KEY_QUERY_CHUNK_SIZE, uniqueKeys.size())); + Condition selectedKeys = DSL.falseCondition(); + for (PointerAuditKey key : keyChunk) { + selectedKeys = + selectedKeys.or( + GAMEPLAY_ADMISSION_POINTER_EVENT + .TENANT_ID + .eq(key.tenantId()) + .and(GAMEPLAY_ADMISSION_POINTER_EVENT.WORLD_SLUG.eq(key.worldSlug())) + .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(key.realmSlug()))); + } + var latestIds = + dsl.select(DSL.max(GAMEPLAY_ADMISSION_POINTER_EVENT.ID)) + .from(GAMEPLAY_ADMISSION_POINTER_EVENT) + .where(selectedKeys) + .groupBy( + GAMEPLAY_ADMISSION_POINTER_EVENT.TENANT_ID, + GAMEPLAY_ADMISSION_POINTER_EVENT.WORLD_SLUG, + GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG); + latestEvents.addAll( + dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER_EVENT) + .where(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.in(latestIds)) + .orderBy(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.asc()) + .fetch(this::toEntity)); } - var latestIds = - dsl.select(DSL.max(GAMEPLAY_ADMISSION_POINTER_EVENT.ID)) - .from(GAMEPLAY_ADMISSION_POINTER_EVENT) - .where(selectedKeys) - .groupBy( - GAMEPLAY_ADMISSION_POINTER_EVENT.TENANT_ID, - GAMEPLAY_ADMISSION_POINTER_EVENT.WORLD_SLUG, - GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG); - return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER_EVENT) - .where(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.in(latestIds)) - .orderBy(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.asc()) - .fetch(this::toEntity); + latestEvents.sort(Comparator.comparing(GameplayAdmissionPointerEvent::getId)); + return latestEvents; } public GameplayAdmissionPointerEvent save(GameplayAdmissionPointerEvent entity) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java index 0ed9ee5223..8ddcdfdd87 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java @@ -6,6 +6,7 @@ import java.sql.Connection; import java.sql.DriverManager; import java.time.Instant; +import java.util.ArrayList; import java.util.List; import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; @@ -100,6 +101,55 @@ void findsLatestAuditByIdForExactMixedTenantPointerKeys() throws Exception { } } + @Test + void chunksLargePointerKeySelectionsAndGloballyOrdersUniqueLatestEvents() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-event-latest-chunks;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerEventRepository repository = + new GameplayAdmissionPointerEventRepository(dsl); + + List keys = new ArrayList<>(); + for (int index = 0; index <= 500; index++) { + keys.add(new PointerAuditKey(9L, "world-" + index, "realm")); + } + keys.add(keys.get(0)); + + GameplayAdmissionPointerEvent secondChunkFirstId = + repository.save(eventForKey(keys.get(500), "2026-09-10T00:00:00Z")); + repository.save(eventForKey(keys.get(0), "2026-09-12T00:00:00Z")); + GameplayAdmissionPointerEvent lastKeyInFirstChunk = + repository.save(eventForKey(keys.get(499), "2026-09-11T00:00:00Z")); + GameplayAdmissionPointerEvent latestFirstKey = + repository.save(eventForKey(keys.get(0), "2026-09-01T00:00:00Z")); + GameplayAdmissionPointerEvent unselectedTenant = event("2026-09-13T00:00:00Z"); + unselectedTenant.setTenantId(11L); + unselectedTenant.setWorldSlug("world-0"); + unselectedTenant.setRealmSlug("realm"); + repository.save(unselectedTenant); + + List latest = repository.findLatestByPointerKeys(keys); + + assertEquals(3, latest.size()); + assertEquals( + List.of(secondChunkFirstId.getId(), lastKeyInFirstChunk.getId(), latestFirstKey.getId()), + latest.stream().map(GameplayAdmissionPointerEvent::getId).toList()); + assertEquals( + List.of("world-500", "world-499", "world-0"), + latest.stream().map(GameplayAdmissionPointerEvent::getWorldSlug).toList()); + } + } + + private static GameplayAdmissionPointerEvent eventForKey(PointerAuditKey key, String occurredAt) { + GameplayAdmissionPointerEvent event = event(occurredAt); + event.setTenantId(key.tenantId()); + event.setWorldSlug(key.worldSlug()); + event.setRealmSlug(key.realmSlug()); + return event; + } + private static GameplayAdmissionPointerEvent event(String occurredAt) { GameplayAdmissionPointerEvent event = new GameplayAdmissionPointerEvent(); event.setWorldSlug("demo"); From 633a86c2208fbcd5cfac73002e6612c02c404c30 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:49:16 +1300 Subject: [PATCH 73/75] test: retain bounded unavailable assertion import --- .../service/impl/LoggingAdminGrpcServiceAuthTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index 8170cb0aa5..4efe39ac9f 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; From 7f8c76f3d93c6e82424667f8a663d8b90b57326e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 17:48:09 +1300 Subject: [PATCH 74/75] Exclude Protobuf extraction tasks from configuration cache --- gradle/proto-convention.gradle | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/gradle/proto-convention.gradle b/gradle/proto-convention.gradle index 2f0c4333f5..fdf7a8e6a0 100644 --- a/gradle/proto-convention.gradle +++ b/gradle/proto-convention.gradle @@ -1,6 +1,8 @@ apply plugin: 'com.google.protobuf' def libs = project.extensions.getByName('libs') +def protobufConfigurationCacheIncompatibilityReason = + "protobuf-gradle-plugin ${libs.plugins.protobuf.get().version.requiredVersion} retains Gradle Project and SourceDirectorySet state with Gradle ${gradle.gradleVersion}" // Define proto source directory before configuring the protobuf plugin so that // the plugin wires the generate tasks and compile dependencies correctly. @@ -30,9 +32,7 @@ protobuf { } generateProtoTasks { all().configureEach { task -> - task.notCompatibleWithConfigurationCache( - "protobuf-gradle-plugin ${libs.plugins.protobuf.get().version.requiredVersion} retains Gradle Project and SourceDirectorySet state with Gradle ${gradle.gradleVersion}" - ) + task.notCompatibleWithConfigurationCache(protobufConfigurationCacheIncompatibilityReason) } ofSourceSet('main').each { task -> task.doNotTrackState("Generated protobuf outputs are rewritten opportunistically and Gradle 9 output snapshotting can observe transiently missing files.") @@ -43,6 +43,14 @@ protobuf { } } +// Protobuf extraction tasks retain the same non-serializable plugin state as +// generation tasks, so keep them out of the configuration cache as well. +def protobufExtractTaskClass = plugins.getPlugin('com.google.protobuf').class.classLoader + .loadClass('com.google.protobuf.gradle.ProtobufExtract') +tasks.withType(protobufExtractTaskClass).configureEach { task -> + task.notCompatibleWithConfigurationCache(protobufConfigurationCacheIncompatibilityReason) +} + // Ensure that the Java compilation runs after Protobuf code generation. tasks.named('compileJava') { dependsOn('generateProto') From c8ce687c5720c71270991e90b8a32163da077279 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 18:20:29 +1300 Subject: [PATCH 75/75] test(game-session): observe CAS blocking without truncated SQL --- ...playAdmissionPointerCasPostgresIntegrationTest.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java index d9e56017ed..7332dd2f2c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java @@ -40,7 +40,9 @@ class GameplayAdmissionPointerCasPostgresIntegrationTest { private static final String REALM_SLUG = "cas-realm"; @Container - static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>("postgres:16-alpine") + .withCommand("postgres", "-c", "fsync=off", "-c", "track_activity_query_size=128"); @BeforeEach void migrateIsolatedContainerSchema() { @@ -272,13 +274,15 @@ private static void awaitPostgresRowLockWait(DSLContext dsl, int waiterPid, int long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); boolean blockedByWinner = false; while (System.nanoTime() < deadline) { + // Activity SQL can be truncated, so lock state and blocker PIDs are the oracle. var lockWaitRecord = Objects.requireNonNull( dsl.fetchOne( "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid = ? " - + "AND wait_event_type = 'Lock' AND query ILIKE '%FOR UPDATE%' " + + "AND wait_event_type = 'Lock' " + "AND ? = ANY(pg_blocking_pids(pid)))", - waiterPid, blockerPid), + waiterPid, + blockerPid), "PostgreSQL lock-wait query returned no row"); blockedByWinner = Objects.requireNonNull(